nodemail
Nodemail Testing
Posted on June 17, 2022
Initiate your project or reuse your previous project. I will use Node.js here, but I will try to give other code samples for other programming languages.
Please prepare Node.js installation. You can download the installer from here. Currently, I use Node.js version 18.4.0. Feel free to try another version.
package.json
using the npm init
command. You can follow the guidelines to fill your package.json
after you give the npm init
command.I will use Nodemailer for email sending. You may use another library as you wish. In this post, I will cover Nodemailer only.
Install it use npm install nodemailer
.
Basically, you may try the example from Nodemailer directly. But, I will add another example like sending an attachment. You can see the index.js
file below. You see the code similar to the example, but I only add attachments to validate that I can use the attachment feature.
const nodemailer = require("nodemailer");
// async..await is not allowed in global scope, must use a wrapper
async function sendEmail() {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
let testAccount = await nodemailer.createTestAccount();
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: testAccount.user, // generated ethereal user
pass: testAccount.pass, // generated ethereal password
},
});
// send mail with defined transport object
let info = await transporter.sendMail({
from: '"Fred Foo 👻" <foo@example.com>', // sender address
to: "bar@example.com, baz@example.com", // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>", // html body
attachments: [
{
filename: 'hello.json',
content: JSON.stringify({
name: "Hello World!"
})
}
]
});
console.log("Message sent: %s", info.messageId);
// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
}
sendEmail().catch(console.error);
You can check the result using the preview URL provided by the console log.
Visit the Github Repository here:
Posted on June 17, 2022
Sign up to receive the latest update from our blog.