Search code examples
google-apps-scriptgoogle-drive-apigmailgmail-apiemail-attachments

Adding Google Drive Files as Attachments to Previously Created Draft in Google Apps Script


I am currently working on an Apps Script project where I need to add two Google Drive files as attachments to an existing Gmail draft without modifying other parts of the draft, such as its subject or body. However, the current implementation that retrieves the draft, updates its content, and adds the attachments seems to cause a disruption in the draft's structure, even resulting in a change of the draft's ID.

I would like to know if there is a more efficient and reliable method to add these Google Drive files to the draft without altering its existing content or affecting the draft's ID. Ideally, I want to preserve the structure of the draft and solely append the new attachments to the existing ones.

Here is a snippet of the code I am currently using:

var fileId1 = 'xxxxxxxxxxxxxxxxxxxxxx';
var fileId2 = 'yyyyyyyyyyyyyyyyyyyyyy';

// Retrieve the existing draft
var draft = GmailApp.getDraft(draftId);
var recipient = draft.getMessage().getTo();
var subject = draft.getMessage().getSubject();
var body = draft.getMessage().getBody();

// Get the existing attachments of the draft
var existingAttachments = draft.getMessage().getAttachments();

// Attach the first file to the email
var file1 = DriveApp.getFileById(fileId1);
var attachmentBlob1 = file1.getAs(MimeType.PDF);

// Attach the second file to the email
var file2 = DriveApp.getFileById(fileId2);
var attachmentBlob2 = file2.getAs(MimeType.PDF);

// Combine existing attachments with new attachments
var allAttachments = existingAttachments.concat(attachmentBlob1, attachmentBlob2);

// Update the draft with recipient, subject, body, and attachments
draft.update(recipient, subject, body, {
  attachments: allAttachments
});

I appreciate any insights or alternative methods that will help me achieve the desired functionality while maintaining the draft's structure and integrity. Thank you!


Solution

  • Finally, I decided to create the draft from scratch using Gmail.app in app script using create draft code. It works fine! this is the code snippet:

      var attachments = [];
    
    
        var file = DriveApp.getFileById("Your attachment file id");
        attachments.push(file.getAs(MimeType.PDF));
    
      // Create the draft with attachments
      var draft = GmailApp.createDraft(
        "Your email address", 
        "Your subject", 
        "Your email body", 
        {
          attachments: attachments,
        }