X

Node.js

How to Send an Email with Nodemailer

June 19, 2021

/*

Nodemailer with Gmail Oauth 2

*/

The nodemailer api is pretty straight forward. It has two methods, the first is nodemailer.createTransport() which takes an object as it's parameter. The object includes a host property, the host to connect to, in this case it's "smtp.gmail.com". The port property, the port to connect to(if secure is false the port is 587, if secure is true the port is 465). The secure property, boolean value, if true the connection will use TLS(Transport Layer Security), If false the connection might use TLS if it's available on the server.

The last property is the auth object. This object takes 6 properties for google oauth. The type property, the authentication type, which is OAuth2. The user property, the email address which your using. The clientID, clientSecret, refreshToken & accessToken is given to you when you sign up with Google's OAuth Playground(which will be covered in another article). The createTransport() method returns an object that will be used to send the email.

<code-div></code-div>

/*

Mail Options Object

*/

The mail options is used in the transport method. It takes multiple properties, but we're only going to be looking at 4. The from propery, the email address of the sender. The to property, a comma seperated list or an array of recipients email addresses that will appear on the To:field. The subject property, the subject of the email. The text property, the plain text version of the message as a string. You can also use the html property, which is the html version of the message as a string.

<code-div></code-div>

/*

SendMail Method

*/

The object we created when we used the nodemailer.createTransport() has the sendMail method attached to it. The sendMail() method takes the mail options object as it's first argument & a callback as it's second. the callback takes an info object that comes with response info, but it really doesn't tell you anything new.

The final result in an express app.

<code-div></code-div>


About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.