Assuming you have basic setup of node.js server, if not please go through this tutorial.
Using fake SMTP provider
To send emails, we need an SMTP server. We will use a nice service called maintrap.io that makes our email testing way easier.
Mailtrap.io is a fake SMTP provider, which send all emails (irrespective of to whom it is sent) into single inbox. So, while developing we don’t have to check emails by logging in to the actual email clients. This becomes handy when many emails or users involved in email sending feature.
To get the fake SMTP configuration, you can login to mailtrap.io and Create Inbox . If you will open inbox it will show you the SMTP config(as shown below). We should use them to send all emails to this particular inbox.
Sending Email
We will be using a package called nodemailer to send the email. Please install the same using npm install nodemailer --save
or yarn add nodemailer
We can configure it in our index.js
file as below:
- Import the
nodemailer
package inindex.js
as below
...
const nodemailer = require("nodemailer");
...
- Create a new endpoint called
/send-email
app.get("/send-email", async (request, response) => {
try {
//email sending code will go here
} catch (e) {
response.send(`An error occurred while sending email`);
}
});
Note: The callback function is
async
because we willawait
for thesendEmail
function(code in upcoming point)
- Create
transport
object that holds the SMTP configuration (copied fom mailtrap.io)
let transporter = nodemailer.createTransport({
host: "smtp.mailtrap.io",
port: 2525,
auth: {
user: "30b7d33f3ac774",
pass: "d75252e55f53d9"
}
});
Note: Make sure to update these SMTP settings with your actual SMTP providers like Mailgun, SendGrid or MailJet when you move your code to production
- Create email data and send the email
const emailData = {
from: "sender@somecompany.com",
to: "receiver@somecomapny.com",
subject: "A test email",
html: "<p> Hi there, this is a test email </p>"
};
// send mail with defined transport object
let info = await transporter.sendMail({
from: emailData.from,
to: emailData.to,
subject: emailData.subject,
html: emailData.html
});
response.send(`An email successfully sent to ${emailData.to}`);
- You can try with any to address, it will send the email to the same mailtrap inbox, as shown below:
The Sandbox
Extract the email sending code to a separate file for reusability (Optional)
Create a new file called sendEmail.service.js
- Create an
async
function in it calledsendEmail
- Move email sending specific code in the
sendEmail
function - Export as module using
module.exports = sendEmail;
at the end
Then in index.js
- Import the
sendEmail
function at the top
const sendEmail = require("./sendEmail.service");
- And call it from
/send-email
route as below
const info = await sendEmail(emailData);
The codesandbox with separate email service