0

Is there a way to attach gmail message body content into the attachment that is also present in the same mail? For example: I have some body text content and 9 page of pdf, so final object/blob could be of 10 pages with body as the first page and remaining 9 pages from the attachment.

I am uploading the final object on google drive.

Or alternative way could be is there a way to add body content when I am creating a file on google drive?

mimetype: pdf

var attachment = message.getAttachments()[0];
const folderId = 'MyFolderId';
  Drive.Files.insert({
    title: attachment.getName(),
    mimeType: attachment.getContentType(),
    parents: [{ id: folderId }]
  },
    attachment.copyBlob()
  );
  • What is the mimeType of your attachment / the file you want to save on your drive? – ziganotschka May 22 '20 at 12:51
  • mimetype is a pdf – Utkarsh Mishra May 22 '20 at 13:43
  • In this case you would need to manually convert the pdf to Google Docs with OCR conversion, paste the email body text into the same document and convert it back to pdf. It might be less convoluted to use a 3rd party pdf merge API. – ziganotschka May 22 '20 at 13:54
  • I would like to suggest another solution. Rough outline. Get the message body using `getPlainBody()`. Save it as PDF. Get the attachment. Merge them. You can consider reading [this answer](https://stackoverflow.com/a/57533158/13338210) to understand what it takes to merge PDFs. Consider (posting an answer) / (editing the question for doubts) after you try this approach or the approach as suggested by @ziganotschka –  May 22 '20 at 16:12

1 Answers1

0

So basically I convert the body text to pdf, and then used convertapi to merge the attachment pdf into 1 pdf.

This is how you can convert body text to pdf in the same formatting as in the Email

var blobFile = Utilities.newBlob(message.getBody(), 'text/html').getAs('application/pdf').setName('yourfilename.pdf');

Then used this answer to use the convertapi to merge those pdfs into one and finally saved the file into drive.

This is the modified merge function I used:

function merge(formData) {
  var options = {
    'method' : 'post',
    'payload' : formData,
    'muteHttpExceptions': true
  };

  var response = UrlFetchApp.fetch('https://v2.convertapi.com/convert/pdf/to/merge?Secret=<SECRET_KEY>', options);

  if(response.getResponseCode() == 200) {
    var contentText = JSON.parse(response.getContentText());
    var blob = Utilities.base64Decode(contentText.Files[0].FileData);
    return blob;
  }
  return "null";
}

Used the merge fetchcall and saved the file in drive

var folder = DriveApp.getFolderById("your_folder_id");
var formdata = {};
formdata['Files[0]'] = blobFile.copyBlob();
formdata['Files[1]'] = attachment.copyBlob();
var mergedData = merge(formdata);
if(mergedData == "null") return;
folder.createFile(Utilities.newBlob(mergedData,'application/pdf',"your_file.pdf"));