DEV Community

Bervianto Leo Pratama
Bervianto Leo Pratama

Posted on

Email Testing using Ethereal

Preparation

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.

Initiate your project

  • Prepare file package.json using the npm init command. You can follow the guidelines to fill your package.json after you give the npm init command.

Install Nodemailer

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.

Let's get started

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);


Enter fullscreen mode Exit fullscreen mode

You can check the result using the preview URL provided by the console log.

Console log

Test Result

Visit the Github Repository here:

GitHub logo berviantoleo / nodemail

Nodemail Testing

nodemail

Nodemail Testing






Thank you

Thanks

Top comments (0)

Some comments have been hidden by the post's author - find out more