I’m trying to figure out how to send emails with multiple attachments using Mailgun and Google Apps Script. Here’s what I’ve got so far:
var params = {
from: "Sender Name <[email protected]>",
to: "[email protected]",
subject: "Test Email",
text: "This is a test message",
html: "<p>This is a <b>test</b> message</p>"
};
// This works for one attachment
params.attachment = DriveApp.getFileById("fileId").getBlob();
I know Mailgun supports multiple attachments, but I’m stumped on how to implement it in Google Apps Script. I’ve tried a few things like:
var files = {
file1: "id1",
file2: "id2"
};
var attachments = [];
for (var file in files) {
attachments.push(DriveApp.getFileById(files[file]).getBlob());
}
params.attachment = attachments;
But it’s not working. Any ideas on how to properly format multiple attachments for Mailgun using UrlFetchApp? Also, is it possible to set custom names for the attachments? Thanks for any help!
I’ve dealt with this issue before, and I can share what worked for me. The key is to use the ‘attachment’ parameter multiple times in your payload, not as an array. Here’s a snippet that should work:
var params = {
from: 'Sender Name <[email protected]>',
to: '[email protected]',
subject: 'Test Email',
text: 'This is a test message',
html: '<p>This is a <b>test</b> message</p>'
};
var files = {
'attachment1.pdf': 'id1',
'attachment2.docx': 'id2'
};
for (var fileName in files) {
params['attachment[' + fileName + ']'] = DriveApp.getFileById(files[fileName]).getBlob();
}
var options = {
method: 'post',
payload: params
};
UrlFetchApp.fetch('https://api.mailgun.net/v3/YOUR_DOMAIN/messages', options);
This approach allows you to set custom names for attachments and send multiple files. Make sure to replace ‘YOUR_DOMAIN’ with your actual Mailgun domain.
I’ve encountered this problem before, and here’s a solution that worked for me:
Instead of using an array for attachments, you need to format each attachment as a separate parameter in your payload. Here’s an example:
var params = {
from: ‘Sender Name [email protected]’,
to: ‘[email protected]’,
subject: ‘Test Email’,
text: ‘This is a test message’,
html: ‘
This is a test message
’
};
var files = {
‘report.pdf’: ‘1234abcd’,
‘data.xlsx’: ‘5678efgh’
};
Object.keys(files).forEach(function(fileName, index) {
params[‘attachment[’ + (index + 1) + ‘]’] = DriveApp.getFileById(files[fileName]).getBlob().setName(fileName);
});
This approach allows you to send multiple attachments with custom names. The key is using ‘attachment[1]’, ‘attachment[2]’, etc., as Mailgun expects this format for multiple files. Remember to adjust your UrlFetchApp.fetch() call to include these parameters in the payload.
hey luna23, i’ve had similar issues. try this:
for (var file in files) {
params[‘attachment[’ + file + ‘]’] = DriveApp.getFileById(files[file]).getBlob();
}
this way, you can send multiple attachments and give em custom names. hope it helps!