Last active
June 16, 2022 21:11
-
-
Save joshatxantie/6da71c62b1b7af72c6034fcdfa5a519f to your computer and use it in GitHub Desktop.
Send email via Google, Nodemailer
This file contains 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
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See https://gist.github.com/joshatxantie/8a5e3a600392b8c3a9a1a4e5dc488d6e for email template