You can deploy this function on any of the serverless platforms - AWS Lambda, Google Cloud Functions, Azure Functions, Netlify, Cloudflare Workers, etc.
- Create a new function and paste in the following code.
- You will need to add
nodemailer
to yourpackage.json
(npm i nodemailer
), and follow your platform's instructions on bundling dependencies. - Obtain Gmail API credentials for your account. You will need
clientID
,clientSecret
, andrefreshToken
. Follow this YouTube tutorial - Expose these credentials as the follwing environment variables:
GMAIL_EMAIL_ADDRESS
GMAIL_API_CLIENT_ID
GMAIL_API_CLIENT_SECRET
GMAIL_API_REFRESH_TOKEN
- Deploy!
// 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() }
}
}