Skip to content

Instantly share code, notes, and snippets.

@hvalls
Last active September 5, 2022 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hvalls/8e10015b26ed918f604e492363d2a52d to your computer and use it in GitHub Desktop.
Save hvalls/8e10015b26ed918f604e492363d2a52d to your computer and use it in GitHub Desktop.
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