Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending mail via aws ses with attachment in node.js

Does anyone have some example of how to send email with attachment in node.js with aws ses?

like image 248
user232343 Avatar asked Apr 13 '14 12:04

user232343


People also ask

How do I send attachments on AWS SES?

To send emails with attachments, you can call the Amazon SES SendRawEmail API, or use the AWS Software Development Kits (SDKs) to compose and send the message programmatically. The message, with attachment(s), will appear in the recipient's email client where it can be viewed or saved to disk.

How do I attach a document to SES email?

File attachments To attach a file to an email, you have to encode the attachment using base64 encoding. Attachments are typically placed in dedicated MIME message parts, which include the following headers: Content-Type: The file type of the attachment.


2 Answers

If you want to avoid suffering, you have to use SES wrapped in Nodemailer. Using the AWS SDK directly, you can't send attachments with ses.sendEmail, you have to use ses.sendRawEmail, which is awful because you have to form the raw E-mail with headers and what-not, and even after I did that, I had a weird error where duplicate E-mails were being sent...

npm install nodemailer

const AWS = require('aws-sdk');
const nodemailer = require("nodemailer");

async function scheduledEmail () {
  let usefulData = 'some,stuff,to,send';
  
  let transporter = nodemailer.createTransport({
    SES: new AWS.SES({ region: 'us-east-1', apiVersion: "2010-12-01" })
  });
  
  let text = 'Attached is a CSV of some stuff.';

  // send mail with defined transport object
  let info = await transporter.sendMail({
    from: '"Some name" <[email protected]>',
    to: "[email protected]",
    subject: "Hello",                // Subject line
    text: text,                      // plaintext version
    html: '<div>' + text + '</div>', // html version
    attachments: [{
        filename: "usefulData.csv",
        content: usefulData
    }]
  });

  console.log("Message sent: %s", info.messageId);
  // Message sent: <[email protected]>
  return info; // or something
}

There are plenty of examples for other ways to set attachments: https://nodemailer.com/message/attachments/

If you're still in the SES sandbox mode, both the to/from addresses have to be verified. Apply to get out of the sandbox mode on the SES Sending statistics page.

like image 145
RaisinBranCrunch Avatar answered Sep 21 '22 10:09

RaisinBranCrunch


There is a great mailing library called ˇNodemailerˇ it also has support for the Amazon SES. Here is a small example of how to send e-mail with attachment https://github.com/nodemailer/nodemailer/blob/master/examples/ses.js

But be aware that Amazon has strange errors when your email sending fails.

like image 26
Risto Novik Avatar answered Sep 21 '22 10:09

Risto Novik