Appscript Send Email Attachment Image

347 views Asked by At

I use this code to send an email with an attachment, and it works perfectly!

However, I can only attach .PDF file

How could I allow image attachment?

Thanks anyone who can help.

function sendEmails() {

  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('BD');
  const numRows = sh.getLastRow();
  const pdf = sh.getRange(numRows, 21).getValue();
  const fileid = pdf.slice(33, 66); //cut url id file drive
  const file = DriveApp.getFileById(fileid)

  var id_img_1 = '1flyOEuH1WWYCrQF91feRPIdvjsFh-YfX'
  var id_img_2 = '1S3p6maECfBiF3J0PnOVfZ64YRxHj00On'
  var picture1 = DriveApp.getFileById(id_img_1); 
  var picture2 = DriveApp.getFileById(id_img_2);
  var inlineImages = {};
      inlineImages[picture1.getId()] = picture1.getBlob();
      inlineImages[picture2.getId()] = picture2.getBlob();
  var my_id = numRows;
      my_id -= 1;

  sh.getRange(numRows, 1).setValue(my_id)    
  var email = sh.getRange(numRows, 2).getValue();

MailApp.sendEmail({

to: email,
subject: "test",
attachments: [file.getAs(MimeType.PDF)],
body: "Test message",
htmlBody:'<img src="cid:' + picture1.getId() + '" />' +
         "</pre><br/>\n"+
         "</pre><br/>\n"+
         '<img src="cid:' + picture2.getId() + '" />' +
         "</pre><br/>\n",
      inlineImages: inlineImages
      
      });

Tks

1

There are 1 answers

0
Tanaike On

Although I'm not sure whether I could correctly understand allow image attachment, from your current script, in order to attach the images as the attachment files, how about the following modification?

From:

attachments: [file.getAs(MimeType.PDF)],

To:

attachments: [file.getAs(MimeType.PDF), picture1, picture2],
  • If you don't want to use the images as the inline images, please remove your htmlBody and inlineImages.