Sending AWS SES emails using attachments using AWS Lambda
1 min readApr 3, 2020
Prerequisites
- AWS SES Setup
I am using nodejs to send email, you will require following things to be installed
1. aws-sdk
2. mailcomposer
In the example, I am creating a dummy file and sending it as attachment using AWS SES and AWS Lambda. You need AmazonSESFullAccess and AWSLambdaBasicExecutionRole policies attached to Lambda Role. Once you have tested you can restrict the permissions as your requirement.
var aws = require('aws-sdk');var ses = new aws.SES({region: 'us-east-1'});const fs = require('fs');const mailcomposer = require('mailcomposer');exports.handler = (event, context, callback) => {fs.writeFile("/tmp/test.txt", "Hey there!", function(err) {if(err) {return console.log(err);}console.log("The file was saved!");});const mail = mailcomposer({from: 'FROM',to: 'ToEmail',subject: 'Sample message with attachment',text: 'Hey folks, this is a test message from Pinpoint with an attachment.',attachments: [{filename: "test.txt",path: "/tmp/test.txt"}]});const response = new Promise((resolve, reject) => {mail.build((err, message) => {if (err) {reject(`Error sending raw email: ${err}`)}new aws.SES({region: 'us-east-1'}).sendRawEmail({RawMessage: {Data: message}}).promise().then(rs => console.log(JSON.stringify(rs))).catch(e => console.error(e));})})};
It uses sendRawEmail API to send emails. You need to use promise to make sure the email sent.