Last active
September 5, 2022 14:18
-
-
Save hvalls/8e10015b26ed918f604e492363d2a52d to your computer and use it in GitHub Desktop.
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
const nodemailer = require("nodemailer"); | |
const { google } = require("googleapis"); | |
const OAuth2 = google.auth.OAuth2; | |
const clientId = process.env.CLIENT_ID; | |
const clientSecret = process.env.CLIENT_SECRET; | |
const refreshToken = process.env.REFRESH_TOKEN; | |
const from = process.env.FROM; | |
const to = process.env.TO; | |
const createTransport = async () => { | |
const oauth2Client = new OAuth2( | |
clientId, | |
clientSecret, | |
"https://developers.google.com/oauthplayground" | |
); | |
oauth2Client.setCredentials({ refresh_token: refreshToken }); | |
const accessToken = await new Promise((resolve, reject) => { | |
oauth2Client.getAccessToken((err, token) => { | |
if (err) { | |
reject(); | |
} | |
resolve(token); | |
}); | |
}); | |
const transport = nodemailer.createTransport({ | |
service: "gmail", | |
auth: { | |
type: "OAuth2", | |
user, | |
accessToken, | |
clientId, | |
clientSecret, | |
refreshToken | |
} | |
}); | |
return transport; | |
}; | |
/** | |
* Example: | |
* | |
* const transport = await createTransport(); | |
* await transport.sendMail({ | |
* subject: "This is the subject", | |
* text: "Hello from nodemailer", | |
* from, | |
* to | |
* }); | |
* | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment