Skip to content

Instantly share code, notes, and snippets.

@joshatxantie
Last active June 16, 2022 21:11
Show Gist options
  • Save joshatxantie/6da71c62b1b7af72c6034fcdfa5a519f to your computer and use it in GitHub Desktop.
Save joshatxantie/6da71c62b1b7af72c6034fcdfa5a519f to your computer and use it in GitHub Desktop.
Send email via Google, Nodemailer
require('dotenv').config();
const fs = require('fs'),
path = require('path'),
Handlebars = require('handlebars'),
nodemailer = require('nodemailer'),
{ google } = require('googleapis'),
OAuth2 = google.auth.OAuth2,
{
GMAIL_REFRESH_TOKEN,
GMAIL_CLIENT_SECRET,
GMAIL_CLIENT_ID,
GMAIL_CLIENT_EMAIL,
SIGNED_UP_EMAILS,
} = process.env,
EMAIL_FOLDER = '../static/'; // This is the path to your email templates (Handle bars)
const oauth2Client = new OAuth2(
GMAIL_CLIENT_ID, // ClientID
GMAIL_CLIENT_SECRET, // Client Secret
'https://developers.google.com/oauthplayground' // Redirect URL
);
oauth2Client.setCredentials({
refresh_token: GMAIL_REFRESH_TOKEN,
});
const send = (options) => {
const accessToken = oauth2Client.getAccessToken();
const smtpTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: GMAIL_CLIENT_EMAIL,
clientId: GMAIL_CLIENT_ID,
clientSecret: GMAIL_CLIENT_SECRET,
refreshToken: GMAIL_REFRESH_TOKEN,
accessToken: accessToken,
},
tls: {
rejectUnauthorized: false,
},
});
smtpTransport.sendMail(options, (error, response) => {
error ? console.log(error) : console.log(response);
smtpTransport.close();
});
};
const email = (email, locals) => {
return {
from: `Support <[email protected]>`,
to: email,
subject: 'Subject',
html: Handlebars.compile(
fs.readFileSync(
path.join(__dirname, , 'template.hbs'), // name of the email template
'utf8'
)
)(locals),
text: '',
};
};
exports.sendEmail = (email, locals) => send(resetEmailOptions(email, locals));
@joshatxantie
Copy link
Author

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