Nodemailer is a popular library in Node.js to send emails.
Features of nodemailer are
- It has zero dependencies
- Secure email delivery with SSL/TLS support
- Supports email transport via popular providers like Amazon SES, Sendgrid etc.
- Easy to add attachments unlike other libraries.
- In this tutorial we’ll learn how to send email attachments using nodemailer.
1. First, add nodemailer to our project.
npm i nodemailer
2. Now let’s create a transport
Like I mentioned above, nodemailer supports other thirdparty providers to be used as transport like Amazon SES, Sendgrid, Mailgun, SMTP etc. In this example, we’ll use SMTP transport.
I’ll be using Typescript for this example.
import nodemailer from "nodemailer";
const smtpTransport = nodemailer.createTransport({
host: "smtp.example.com",
port: 587,
secure: false,
auth: {
user: "username",
pass: "password",
},
});
3. Construct the email body
We can create the email body as an object with from, to, subject and html.
const mailBody = {
from: "username@gmail.com",
to: "receiver@gmail.com",
subject: "Sample email sent using nodemailer",
html: "<h1>Hello World!</h1>"
};
4. Let’s add our attachment
Nodemailer supports different types of attachments like base64, file path, stream etc. To get the complete list of attachment supported by nodemailer, refer their documentation.
In this example, we’ll be using file path. So, let’s modify our mailBody.
const mailBody = {
from: "username@gmail.com",
to: "receiver@gmail.com",
subject: "Sample email sent using nodemailer",
html: "<h1>Hello World!</h1>"
attachments: [
{
filename: 'sample_attachment.png',
path: __dirname + '/sample_attachment.png',
}
]
};
5. Send the email
To send the email, use the transport.sendMail()
function.
smtpTransport.sendMail(mailBody, function (error, info) {
if (error) {
console.log(error);
}
console.log("Email with attachment delivered successfully")
});
Final code to send email attachments using Nodemailer.
import nodemailer from "nodemailer";
const smtpTransport = nodemailer.createTransport({
host: "smtp.example.com",
port: 587,
secure: false,
auth: {
user: "username",
pass: "password",
},
});
const mailBody = {
from: "username@gmail.com",
to: "receiver@gmail.com",
subject: "Sample email sent using nodemailer",
html: "<h1>Hello World!</h1>"
attachments: [
{
filename: 'sample_attachment.png',
path: __dirname + '/sample_attachment.png',
}
]
};
smtpTransport.sendMail(mailBody, function (error, info) {
if (error) {
console.log(error);
}
console.log("Email with attachment delivered successfully")
});
Simple! Hope this tutorial has helped you to understand how to send attachments using nodemailer in your email notifications.
Top comments (0)