Last active
June 4, 2021 11:29
-
-
Save jonathandavidpollock/b8e73974e79f2e3be314ec9f3a3775ef to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.') | |
}); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
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.
Step 2
Add your account credentials as variables to your environment config. They should look like this.
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.