Skip to content

Instantly share code, notes, and snippets.

@Oliver-ke
Created November 16, 2020 10:00
Show Gist options
  • Save Oliver-ke/565d2e5112ea0688c872a1756a576783 to your computer and use it in GitHub Desktop.
Save Oliver-ke/565d2e5112ea0688c872a1756a576783 to your computer and use it in GitHub Desktop.
Util function to send mails from cloud function
const Mailgun = require('mailgun-js');
const DOMAIN = 'mail.myfortvest.com';
const API_KEY = process.env.MAIL_API_KEY || '';
const PUBLIC_KEY = process.env.MAIL_PUBLIC_KEY || '';
const mailgun = Mailgun({ apiKey: API_KEY, domain: DOMAIN, publicApiKey: PUBLIC_KEY });
const sendMail = async (payload) => {
const {variable, desc, ...rest} = payload;
const variableKey = Object.keys(payload.variable);
const variableValues = Object.values(payload.variable);
const message = {...rest};
message.from = `${desc} <[email protected]>`;
variableKey.forEach((key, idx) => {
message[`v:${key}`] = variableValues[idx];
});
try {
await mailgun.messages().send(message);
} catch (error) {
throw new Error(error);
}
}
/**
* Responds to any HTTP request.
*
* @param {!express:Request} req HTTP request context.
* @param {!express:Response} res HTTP response context.
*/
exports.mailHandler = async (req, res) => {
const payload = req.body.payload;
return await Promise.all(payload.map((message) => sendMail(message)))
.then(() => res.status(200).json({success: true}))
};
const testPayload = {
"payload": [
{
"desc": "Accepted",
"subject": "Request accepted",
"template": "on-investee-accept",
"to": "[email protected]",
"variable": {
"user": "Kelechi Oliver",
"paymentLink": "https://myfortvest.com/pay/investee?u=jjsuudbbe"
}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment