NodeMailer NPM Tutorial
source link: https://www.mailslurp.com/blog/nodemailer-npm/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
NodeMailer NPM Tutorial
NodeMailer is a popular NodeJS package for sending and receiving emails. It’s open source and has no external dependencies! Let’s see it in action:
Installing NodeMailer
First create a new NodeJS project with npm init -y
.
Then install NodeMailer from NPM with npm install --save nodemailer
.
Next setup your SMTP connection
Import nodemailer
package and create a new instance.
const nodemailer = require("nodemailer");
Then connect your SMTP server:
const transporter = nodemailer.createTransport({
host: "your-smtp-server",
port: 587,
secure: false,
auth: {
user: "smtp-user",
pass: "smtp-password"
}
});
Note: if you don’t have access to an SMTP server use MailSlurp instead!
Sending emails
You can send emails as follows:
let info = await transporter.sendMail({
from: "[email protected]",
to: "[email protected], [email protected]",
subject: "Hello",
text: "Hello world",
});
What about receiving email?
Unfortunately NodeMailer can’t easily receive emails but there are tons of email APIs out there to help.
With MailSlurp you can create test email addresses then receive emails in Javascript using them. Let’s see it in action:
npm install --save mailslurp-client
Then create an inbox and wait for emails to be received.
const MailSlurp = require('mailslurp-client').default;
const mailslurp = new MailSlurp({ apiKey });
const inbox = await mailslurp.createInbox();
Use the wait for methods to receive the email
const email = await mailslurp.waitForLatestEmail(inbox.id, timeout);
// { body: "Hello world", subject: "Hello", ...rest }
Use SMTP servers with MailSlurp
Creating inboxes
You can create mailboxes in Javascript using MailSlurp.
const { id, emailAddress } = await mailslurp.createInbox();
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK