Skip to content

Instantly share code, notes, and snippets.

@jonathandavidpollock
Last active June 4, 2021 11:29
Show Gist options
  • Save jonathandavidpollock/b8e73974e79f2e3be314ec9f3a3775ef to your computer and use it in GitHub Desktop.
Save jonathandavidpollock/b8e73974e79f2e3be314ec9f3a3775ef to your computer and use it in GitHub Desktop.
const nodemailer = require('nodemailer');
// const env = process.env.NODE_ENV || 'development';
// const config = require(path.join(__dirname, '/../config/config.json'))[env];
module.exports = (data) => {
nodemailer.createTestAccount((err, account) => {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: ACCOUNT_USERNAME,
pass: ACCOUNT_PASSWORD
}
});
// setup email data with unicode symbols
let mailOptions = {
from: '[email protected]', // sender address
to: data.to, // list of receivers
subject: data.subject, // Subject line
text: data.text, // plain text body
html: data.html // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
error ? console.error(error) : console.log('Message Sent.')
});
})
}
@jonathandavidpollock
Copy link
Author

Send gmail through Node.js

Before beginning

You must have experience in Node.js. You will install the dependency Nodemailer. This package is great because it has no dependencies other than Node itself. Theoretically, this package will work for more than gmail.

Note: We will create two objects: transporter and mailoptions: name, html, etc...

We will then call the sendmail method of the transporter and pass the mailoptions as an argument to the function.

Installation

Step1

Install the nodemailer dependency into your node server.

npm install nodemailer -S

Step 2

Add your account credentials as variables to your environment config. They should look like this.

ACCOUNT_USERNAME: '[email protected]'
ACCOUNT_PASSWORD: 'XXXXXXX'

Step 3

Add the nodemailer.js file to your project. Copy the attached gist below.

Download this Nodemailer Gist

Step 4

Edit the mailoptions variable to your liking. This variable is the email to be sent to the user. There are more options than needed on nodemailer if needed. For example, you can specify the watchText option which is the text that displays on the watch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment