Search code examples
google-apps-scriptgmailinline-images

Send e-mail with InlineImages


I've created a script to send emails to a list of e.mail addresses with a PDF attachment. Now I want to "pimp it", adding a picture taken from Drive at the beginning of the email.

I found this method on Google Developers - sendEmail(recipient, subject, body, options) - but it's not crystal clear to me on how it works.

This is the code I wrote so far, but it's not working. I keep reading only the text, without any picture. It should take the first 50 rows of a spreadsheet, send an email to the address in column 9 and update column 11 once done.

 var sheet = SpreadsheetApp.setActiveSheet(source.getSheets()[2]);
 var row = 3
 var subject = "Subject";
 var imageId = DriveApp.getFileById("0B-OVYDHfkqhXOTF6aWVSSUtSbUE");
 var htmlText = "<img src = "cid:imageId" />  Dear Friend, <BR> <BR> Text";

 for (var i = 0; i <= 50; i++) {
   var emailAddress = sheet.getRange(row + i, 9).getValue()
   var message = "Hi,\n \n" + "text";

   MailApp.sendEmail(emailAddress, subject, message, {
     name: "Alternative Name",
     htmlbody: htmlText,
     attachments: [budgetPDF],
     inLineImages: imageId
   })

   sheet.getRange(row + i, 11).setValue("Sent");

Could you please tell me what I'm doing wrong?

Thanks for your help!


Solution

  • You don't get the blob of the file.

    var imageId = DriveApp.getFileById("0B-OVYDHfkqhXOTF6aWVSSUtSbUE");
    var imageIdBlob = imageId.getBlob();
    var htmlText = "<img src = 'cid:imageIdBlob' />  Dear Friend, <BR> <BR> Text";
    .....
    .....
    MailApp.sendEmail(emailAddress, subject, message, {
         name: "Alternative Name",
         htmlbody: htmlText,
         attachments: [budgetPDF],
         inLineImages: imageIdBlob
       })
    

    As I don't know the format of the file you can also use getAs().

    Stéphane