You can deploy this function on any of the serverless platforms - AWS Lambda, Google Cloud Functions, Azure Functions, Netlify, Cloudflare Workers, etc.
GMAIL_EMAIL_ADDRESS
GMAIL_API_CLIENT_ID
GMAIL_API_CLIENT_SECRET
GMAIL_API_REFRESH_TOKEN
// Docs on event and context https://www.netlify.com/docs/functions/#the-handler-method
const nodemailer = require("nodemailer");
function createMailClient() {
return nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
type: 'OAuth2',
user: process.env.GMAIL_EMAIL_ADDRESS,
clientId: process.env.GMAIL_API_CLIENT_ID,
clientSecret: process.env.GMAIL_API_CLIENT_SECRET,
refreshToken: process.env.GMAIL_API_REFRESH_TOKEN,
}
});
}
const mailClient = createMailClient();
exports.handler = async (event, context) => {
try {
const json = JSON.parse(event.body);
const gmailResponse = await mailClient.sendMail({
from: '"Benedict Arnold" <[email protected]>', // sender address
to: "Sir Henry Clinton <[email protected]>", // list of receivers
subject: json.subject,
text: json.text, // plain text body
html: json.html
});
return {
statusCode: 200,
body: "Message sent!" + gmailResponse.messageId
}
} catch (err) {
return { statusCode: 500, body: err.toString() }
}
}