Skip to content

Instantly share code, notes, and snippets.

@munim
Last active September 4, 2022 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save munim/02e1bc10bf4e0fbb17c5bf6689906a8a to your computer and use it in GitHub Desktop.
Save munim/02e1bc10bf4e0fbb17c5bf6689906a8a to your computer and use it in GitHub Desktop.
Send Email with Zip attachment having multiple files through Amazon SES using NodeJS

Send Email with Zip attachment having multiple files through Amazon SES using NodeJS

We want to send an email with the following requirements:

  1. Email to have an Zip attachment.
  2. Zip file containing multiple log files
  3. Email needs to go through Amazon SES.
  4. Implementation to be done using NodeJS

We will use the following NodeJS library

  1. NodeMailer
  2. Adm Zip

Below is the code:

const NodeMailer = require("nodemailer");
const AdmZip = require("adm-zip");

const createSampleZip = () => {
  const zip = new AdmZip();

  zip.addFile("file1.txt", Buffer.from("content of file 1"));
  zip.addFile("file2.txt", Buffer.from("content of file 2"));

  return zip.toBuffer();
};

const sendEmail = () => {
  var sender = NodeMailer.createTransport({
    host: "email-smtp.eu-central-1.amazonaws.com",
    port: 587,
    secure: false, // upgrade later with STARTTLS
    auth: {
      user: "<<ses-smtp-username>>",
      pass: "<<ses-smtp-password>>",
    },
  });

  var mail = {
    from: "noreply@example.com",
    to: "recipient@gmail.com",
    subject: "test email with attachment",
    text: "mail body text with attachment",
    html: "<h1>mail body in html with attachment</h1>",
    // More options regarding attachment here: https://nodemailer.com/message/attachments/
    attachments: [
      {
        filename: "zipfile.zip",
        content: createSampleZip(),
      },
    ],
  };

  console.log("starting to send email");
  sender.sendMail(mail, function (error, info) {
    if (error) {
      console.log(error);
    } else {
      console.log("Email sent successfully: " + info.response);
    }
  });
};

sendEmail();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment