简体   繁体   中英

Google apps script: use the mailapp.sendmail service to send mails with only occasional attachments

Please be patient, I am new to GAS. I am trying to use the mailapp.sendmail service to send mails with only occasional attachments. Somehow it ends with either the variant without attachment works or the one with attachment, but never both of them. Here is the code:

function sendMail(tomail, subject, fill_cell, messageTemplate, EMAIL_SENT, fileAttach) {
  if (fileAttach == "noFile" )
     { var fileAttachHolder = ' ' }
   else
     { var fileAttachHolder = fileAttach + '.getAs(MimeType.PDF) '};   
  MailApp.sendEmail(tomail, subject,'', {htmlBody: messageTemplate, attachments: [fileAttachHolder]});
  fill_cell.setValue(EMAIL_SENT);
  SpreadsheetApp.flush();
  // Browser.msgBox('Mail sent: '+ subject);
}

calling the function like this:

 if ((emailSent != EMAIL_SENT)  && row[4] > now ) {  // Prevents sending duplicates or outdated
  sendMail(
    emailAddress,
    "Hi, " + row[1] + " " + row[3],
    sheet.getRange(startRow + i, 18),
    HMESSAGE,
    EMAIL_SENT            
  );

I guess it has to do with how I define the attachment variable. Grateful for help. Martin

An attachments must be in your drive and this file is a blobType.

I can show you an example of my script.

function sendEmail() {

var Rainfall = DriveApp.getFilesByName('Untitled document')
var Rainfall2 = DriveApp.getFilesByName('128x128_tl_icon.png')

MailApp.sendEmail({
to:"mymail@gmail.com", 
subject: "Images for Social Media", 
body:"Hi Joe, here are the images for Social Media",


attachments: [Rainfall.next(), Rainfall2.next()]
  })

}
sendEmail()

finally found a solution, I am sure not the most elegant but it works:

    function sendMail(tomail, subject, fill_cell, messageTemplate, EMAIL_SENT) {  
  MailApp.sendEmail(tomail, subject,'', {htmlBody: messageTemplate});
  fill_cell.setValue(EMAIL_SENT);
  SpreadsheetApp.flush();

}

    function sendMailwAtt(tomail, subject, fill_cell, messageTemplate, EMAIL_SENT, fileAttach) {  
  MailApp.sendEmail(tomail, subject,'', {htmlBody: messageTemplate, attachments: [fileAttach.next()]});
  fill_cell.setValue(EMAIL_SENT);
  SpreadsheetApp.flush();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM