Abdul-Munim
Posted on September 4, 2022
We want to send an email with the following requirements:
- Email to have an Zip attachment.
- Zip file containing multiple log files
- Email needs to go through Amazon SES.
- 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
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();
đ đȘ đ
đ©
Abdul-Munim
Posted on September 4, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Can Node.js Really Handle Millions of Users? The Ultimate Guide to Massive Scale Applications
November 28, 2024
javascript Conclusion of My Node.js Journey and a Sneak Peek into My Upcoming AWS Series
November 15, 2024