Created
May 13, 2020 08:11
-
-
Save AnalyzePlatypus/5ba15477efeab790ac1d65ba14873e21 to your computer and use it in GitHub Desktop.
Revisions
-
AnalyzePlatypus created this gist
May 13, 2020 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,60 @@ # Sending email with serverless functions You can deploy this function on any of the serverless platforms - AWS Lambda, Google Cloud Functions, Azure Functions, Netlify, Cloudflare Workers, etc. 1. Create a new function and paste in the following code. 2. You will need to add `nodemailer` to your `package.json` (`npm i nodemailer`), and follow your platform's instructions on bundling dependencies. 3. Obtain Gmail API credentials for your account. You will need `clientID`, `clientSecret`, and `refreshToken`. Follow [this YouTube tutorial](https://www.youtube.com/watch?v=JJ44WA_eV8E) 4. Expose these credentials as the follwing environment variables: ``` GMAIL_EMAIL_ADDRESS GMAIL_API_CLIENT_ID GMAIL_API_CLIENT_SECRET GMAIL_API_REFRESH_TOKEN ``` 5. Deploy! ```js // 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() } } } ```