DEV Community

Abdul-Munim
Abdul-Munim

Posted on

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 can also zip other sources, such as files from file system or a remote file. We just have to convert it to a Buffer to zip it with AdmZip.

We will use the following NodeJS library

  1. NodeMailer
  2. Adm Zip

PS: This whole operation is done in-memory. This should not be used on large files. In such case, Stream should be used.

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();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)