If you want to learn how to automate your emailing process, you have come to the right place. I’m going to cover in this article the basic essentials you need to be able to start email automation with Node.js. This will include how to content to a email server, how to send the emails, and how to populate the email with text or HTML.
Getting Started
To get started, you will want to boot up a IDE of your choosing and begin to install a package. You can grab another package if you want to put this is a Cron job. The package(s) you need are nodeMailer and node-cron then include them into your index file. I will also include a video down below that shows you whole process.
let nodemailer = require('nodeMailer');
const cron = require('node-cron');
It is also a good idea to create another file for your password for the email server. That way if you use version-control system, you can .gitignore that file so it is not publicly available. Then include that file as well.
let constants = require('./constants');
Next, you are going to need to find some information out about your email server. You will need the host and port number. I will be using AOL for this example. If that is what you are using, you can grab that information from the code. You will need to create a transporter that nodeMailer uses. Then pass in the host, port, and an auth object that includes the service, user, and password. You will also see how to use the constants variable here.
Email Automation with Node.js
var transporter = nodemailer.createTransport({
host: 'smtp.aol.com',
port: '587',
auth: {
service: 'aol',
user: 'test2211',
pass: constants.pass
}
});
The code above will allow you to connect to AOLs server. Now that you are connect, you will need to set the parameters for the email to send. You will need to create a mailOptions object that will have from, to, subject line, and if you want text or HTML. Yes, you can add HTML to the email to make it more appealing. I am going to include HTML in my example, if you want to use text, change out html for text and remove the HTML tags.
var mailOptions = {
from: 'test2211@aol.com',
to: 'c908453@urhen.com',
subject: 'News letter - ' buildDate(),
html: '<h1>Todays topics include...</h1>'
};
You are all done in setting up the email and connecting to the server so all you need to do now is to send it.
transporter.sendMail(mailOptions, function(error, info){
if (error) { c
onsole.log(error);
} else {
console.log('Email sent: ' info.response);
}
});
The transporter object has a sendMail method that takes the mailOptions and a function on a response that passes in an error and info. Info will tell you about the response from the server like if the message was sent, or the recipient email was invalid. There you have it. That is all that is to sending out emails with Node.js. To automate it, you can wrap all of it in a Cron job. The video below includes that along with a dynamic date function.