const nodemailer = require("nodemailer");
const { google } = require("googleapis");
const oAuth2Client = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
"https://developers.google.com/oauthplayground"
);
oAuth2Client.setCredentials({refresh_token: process.env.GOOGLE_REFRESH_TOKEN});
module.exports.sendMail = async (mailOptions) => {
try {
const accessToken = await oAuth2Client.getAccessToken();
const transport = nodemailer.createTransport({
service: "gmail",
auth: {
type: "OAuth2",
user: process.env.GMAIL_ADDRESS,
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
refreshToken: process.env.GOOGLE_REFRESH_TOKEN,
accessToken: accessToken
}
});
await transport.sendMail(mailOptions);
sendMail()
.then(() => console.log("Email sent!"))
.catch((error) => console.log("Email NOT sent! " + error.message));
} catch (error) {
return error;
}
};
Hello! This is the code that does auth with google and then sends the email wherever the sendEmail function is called. Everything works smoothly in local, but not in production. I have no idea what i am doing wrong. Thank you for the help.
Better to use SendGrid as a service because you need that for production ( 100 emails/day free ), To ensure the email delivery , They have a reasonable free plan ,. And it’s very easy to install.
For debugging you best use mailtrap ( free ) .