Send email with picture attachment and body using google script

前端 未结 1 505
刺人心
刺人心 2021-01-07 14:38

Hi im having trouble in sending email with image attachment. because the image file name is randomized and have no way to find out if the body of my message fits the image i

相关标签:
1条回答
  • 2021-01-07 15:01

    To attach a file, you use File.getBlob() to attach it as a blob. For example:

    attachments: [picture1.next().getBlob(),picture2.next().getBlob()]
    

    If you know the exact id of a file (e.g. '0BxDqyd_bUCmvN1E3N0dQOWgycEF'), you can get it as a blob like this:

    var picture3Blob = DriveApp.getFileById('0BxDqyd_bUCmvN1E3N0dQOWgycEF').getBlob();
    

    Here's a working example:

    function sendPics() {
      var picture1 = DriveApp.getFileById('0BxDqyd_bUCmvN1E3N0dQOWgycFE'); //public with link
      var picture2 = DriveApp.getFileById('0BxDqyd_bUCmvTFNjRkRXbXA2Tms'); //public with link
       MailApp.sendEmail({
         to: 'testa@example.com, testb@example.com', 
         subject: "This is a test", 
         body:"Test message",
         attachments: [picture1.getBlob(), picture2.getBlob()]
      });
    }
    

    and here's an example of the pictures being added inline instead of as attachments:

    function sendPicsInline() {
      var picture1 = DriveApp.getFileById('0BxDqyd_bUCmvN1E3N0dQOWgycFE'); //public with link
      var picture2 = DriveApp.getFileById('0BxDqyd_bUCmvTFNjRkRXbXA2Tms'); //public with link
      var inlineImages = {};
      inlineImages[picture1.getId()] = picture1.getBlob();
      inlineImages[picture2.getId()] = picture2.getBlob();
       MailApp.sendEmail({
         to: 'testa@example.com, testb@example.com', 
         subject: "This is a test", 
         body:"Test message",
         htmlBody: 'Test message with pics inline <br>' +
         'first:<br><img src="cid:' + picture1.getId() + '" /><br>' +
         'second:<br><img src="cid:' + picture2.getId() + '" />',
         inlineImages: inlineImages   
      });
    }
    
    0 讨论(0)
提交回复
热议问题