找不到方法 sendEmail(对象)

Cannot find method sendEmail(object)

尝试在 Google 表格上编写脚本时,出现错误:

Cannot find method sendEmail(object)

对于以下代码。如您所知,这是一封发给新客户的介绍电子邮件,向客户介绍他的客户代表。

  var clientname = spreadsheet.getRange('C2').getValue();
  var clientemail = spreadsheet.getRange('P2').getValue();
  var repname = spreadsheet.getRange('H2').getValue();
  var repmobile = spreadsheet.getRange('AA2').getValue();
  var repemail = spreadsheet.getRange('AB2').getValue();

     GmailApp.sendEmail({
        to: clientemail,
        subject: EMAIL_SUBJECT,
        htmlBody: createEmailBody(clientname, repname, repmobile, repemail),
        name: 'myname', 
        from: 'welcome@mydoamin.com', 
        replyTo: repemail
      });

感谢大家的大力帮助,我现在将代码修改为:

GmailApp.sendEmail({
    recipient: clientemail, 
    subject: email_subject, 
    htmlBody: createEmailBody(clientname.toString(), repname.toString(), repmobile.toString(), repemail.toString()),
    {name: 'myname',
    from: 'welcome@mydomain.com', 
    replyTo: repemail}
  });

现在的错误是:

Invalid property ID

在以“{name”开头的行上

根据您的要求修改此代码。

代码复制自官方文档。正确的做法是:

function myFunction() {
// The code below will send an email with the current date and time.
var now = new Date();
GmailApp.sendEmail("email@example.com", "current time", "The time is: " + now.toString()); 
}

编辑:HTML 要求的正文样本:

function myFunction() {
// The code below will send an email with the current date and time.
var now = new Date();
GmailApp.sendEmail("email@example.com", "current time", "The time is: " + now.toString(),{htmlBody: '<h1>hello</h1>'});
  }

此为补充回答:

您需要学会理解错误消息 - 它们是您调试时最好的朋友,但它们并不总是直观的。在您的情况下,错误状态为:找不到方法 sendEmail(object)。尝试像解析模板字符串一样解析它,消息说:

  1. 无法找到方法
  2. 搜索的方法是sendEmail
  3. 它作为单个参数传递 object 的实例

既然明显有一个叫sendEmail的方法(在确保没有错别字之后),你可以放心地去掉前两部分。这给我们留下了 "instance of object" - 那么一个自然的问题就是 "is it allowed to pass an object to this method?"。如果你查看文档,它不是。

但是您可以首先避免所有这些。有一个博客 post 我觉得非常有用 - 6 deadly sins of GAS Add-on development. The first one strikes an apple - you will be much better off not using the script editor and install an IDE 或支持自动完成的编辑器(无论是 VS Code、Netbeans 还是其他)。

也就是说,重复其他答案,方法签名的结构如下:

 sendEmail( recipient, subject,  body,   options )
________________________________________________
  name        arg0       arg1    arg2    [arg3]

请注意前三个参数是强制性,只有第四个是可选。 如果您再次查看参考文档,options 是所有 高级 参数所在的位置。

备注

  1. 关于大括号:我假设您知道这一点,但以防万一:这是一个对象文字(初始化程序)notation,用于实例化一个对象。如果方法签名另有说明,则不必将所有参数包装在一个对象中(不过我认为你走在正确的轨道上——最好用一个配置参数声明你的 API,只是不要违反public 合同)。

参考资料

  1. sendEmail 选项 spec
  2. sendEmail 无选项 spec
  3. MailApp方法sendEmailspec

解决方案

您没有正确使用 sendEmail method,因为您将对象作为单个参数而不是正确的参数传递。根据上面链接的文档,您的参数应该如下:

  • 收件人(字符串)
  • 主题(字符串)
  • 正文(字符串)
  • 选项(对象)

因此,你的方法最终会是这样的:

GmailApp.sendEmail(clientemail, email_subject,createEmailBody(clientname.toString(), repname.toString(), repmobile.toString(), repemail.toString()),{
    name: 'myname',
    from: 'welcome@mydomain.com', 
    replyTo: repemail}
  );

希望对您有所帮助。让我知道您是否需要其他任何东西或者您不明白什么。 :)