Reputation: 952
I am trying to send mail with a PDF attachment using Mailjet from Google Apps Script. I can send regular mail without issue, but not quite sure how to include an attachment.
Mailjet documentation: https://dev.mailjet.com/guides/#sending-with-attached-files
I think my problem is the Base64Content. I don't really understand how to encode the attachment. When I execute the below code, an email is being sent with a PDF attachment, but when I try and open the PDF it displays: "Cannot display PDF (test.pdf is of invalid format)".
var newDoc = DocumentApp.openById(newDocid)
var attachment = newDoc.getAs(MimeType.PDF);
var mailjeturl = "https://api.mailjet.com/v3.1/send";
var mailjetparams = {
"Messages":[{
"From": {"Email": '[email protected]',"Name": 'Robert'},
"To": [{"Email": '[email protected]'}],
"Subject": 'subject',
"HTMLPart": 'this message',
"Attachments": [{"ContentType": "application/pdf",
"Filename": "test.pdf",
"Base64Content": Utilities.base64Encode(attachment)}]
}]
}
var mailjetoptions = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(mailjetparams),
'headers': {'Authorization': 'Basic ' + Utilities.base64Encode(MAILJET_KEY)}
};
var response = JSON.parse(UrlFetchApp.fetch(mailjeturl, mailjetoptions))
Upvotes: 0
Views: 2035
Reputation: 4273
Try to encode like this:
var pdf = newDoc.getAs('application/pdf').getBytes();
var attach = {fileName:'test.pdf',content:pdf, mimeType:'application/pdf'};
var mailjetparams = {
"Messages":[{
"From": {"Email": '[email protected]',"Name": 'Robert'},
"To": [{"Email": '[email protected]'}],
"Subject": 'subject',
"HTMLPart": 'this message',
"Attachments": [attach]
}]
}
Upvotes: 2
Reputation: 201398
How about the following modification? I thought that the reason of the error may be Utilities.base64Encode(attachment)
.
attachment
retrieved by newDoc.getAs(MimeType.PDF)
is Blob. The Blob cannot be directly converted to base64 using Utilities.base64Encode()
. So please convert Blob to byte array, and convert to base64.
When this is reflected to your script. The modification part is as follows.
var attachment = newDoc.getAs(MimeType.PDF);
var attachment = newDoc.getAs(MimeType.PDF).getBytes();
or
var attachment = newDoc.getBlob().getBytes();
When Google Document is retrieved as a Blob, Google converts automatically to PDF. You can also use this.
If I misunderstand your question, I'm sorry.
Upvotes: 1