In an HTTP request one can specify most parameters multiple times, HTTP supports this out of the box. But how can this be done when using Class UrlFetchApp of Google Apps Script?
I am trying to send mail using Mailgun API and want to attach multiple attachments. Here's what Mailgun API says about this:
Note that you can specify most parameters multiple times, HTTP supports this out of the box. This makes sense for parameters like cc, to or attachment.
Here are some other similar questions related to other languages or platforms but none of these help:
- Set more than one HTTP header with the same name?
- Sending HTTP request with multiple parameters having same name
- handling duplicate keys in HTTP post in order to specify multiple values
Here's my code that works for a single attachment. Note that the function mailgun() takes exact same arguments as GmailApp.sendEmail() for consistency purposes:
function mailgun(recipient, subject, body, options){
var params = {
"method":"POST",
"headers": {
"Authorization" : "Basic " + Utilities.base64Encode('api:key-goes-here')
},
"payload": {
"to": recipient,
"subject": subject,
"text": body,
"html": options.htmlBody
},
"muteHttpExceptions": true,
};
if(options.hasOwnProperty("bcc"))
params.payload.bcc = options.bcc;
if(options.hasOwnProperty("cc"))
params.payload.cc = options.cc;
if(options.hasOwnProperty("replyTo"))
params.payload['h:Reply-To'] = options.replyTo;
if(options.hasOwnProperty("name")){
params.payload.from = options.name + ' <' + options.from + '>';
} else {
params.payload.from = options.from;
}
if(options.hasOwnProperty("attachments")){
params.payload.attachment = options.attachments[0];
}
var response = UrlFetchApp.fetch('https://api.mailgun.net/v3/domain.com/messages', params);
var responseCode = response.getResponseCode();
var responseObj = JSON.parse(response.getContentText());
if(responseCode != 200) return 'Mailgun error: '+responseObj.message;
return true;
}
If I use this code, the mail goes through but without attachments:
if(options.hasOwnProperty("attachments")){
params.payload.attachment = [options.attachments[0],
options.attachments[1]
];
}
The Mailgun API says 'You can post multiple attachment values'. This is a little misleading, as essentially they mean that 'you can specify attachment parameter multiple times' to send multiple attachments.
As payload is an object this is not possible using UrlFetchApp and I guess the only way is to manually build the multipart payload without relying on auto-generation of UrlFetchApp.
This is the Curl request that works. Need to emulate this using urlFetch:
curl -s --user 'api:key-goes-here' \
https://api.mailgun.net/v3/domain.com/messages \
-F from='Support <support@domain.com>' \
-F to=example@domain.com \
-F subject='Hello' \
-F text='Testing some Mailgun awesomness!' \
-F attachment='@image.png' \
-F attachment='@license.txt' \