Last active
October 4, 2022 08:15
-
-
Save CastenettoA/90d93774d5f8a4c5816fce5cd7bf85e1 to your computer and use it in GitHub Desktop.
A netlify ready serverless function for sending email with MailJet API
This file contains 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 characters
const Mailjet = require ('node-mailjet') | |
const mailjet = new Mailjet({ | |
apiKey: process.env.MJ_APIKEY_PUBLIC || 'your-public-api-key', | |
apiSecret: process.env.MJ_APIKEY_PRIVATE || 'your-private-api-key' | |
}); | |
exports.handler = async (event) => { | |
const { fromEmail, fromName, toEmail, toName, subject, TextPart, HtmlPart } = JSON.parse(event.body); | |
const request = mailjet | |
.post('send', { version: 'v3.1' }) | |
.request({ | |
Messages: [ | |
{ | |
From: { | |
Email: fromEmail, | |
Name: fromName | |
}, | |
To: [ | |
{ | |
Email: toEmail, | |
Name: toName | |
} | |
], | |
Subject: subject, | |
TextPart: TextPart, | |
HTMLPart: HtmlPart | |
} | |
] | |
}); | |
request | |
.then((result) => { | |
console.log('email inviata: ', JSON.stringify(result.body)) | |
}) | |
.catch((err) => { | |
console.log('errore invio email: ', JSON.stringify(result.body)) | |
}); | |
return { | |
statusCode: 200, | |
body: JSON.stringify({ message: "email sended correctly." }), | |
} | |
} | |
// frontend code for sending a email with the upper netlify function (this code is not tested) | |
// const data = { | |
// fromEmail: 'info@example.com', | |
// fromName: 'Name Surname', | |
// toEmail: '@example_2.com', | |
// toName: 'Name Surname', | |
// subject: 'This is the title', | |
// TextPart: 'This is the main email text', | |
// HtmlPart: 'This is the main email text.' | |
// }; | |
// const r = await fetch('./netlify/funcions/send-email', { | |
// method: 'POST', | |
// headers: { | |
// 'Content-Type': 'applicazion/json' | |
// }, | |
// body: JSON.stringify(data), | |
// }).then((res)=> res.json()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Put this on "/functions/send-email-mailjet.js".
To make it work you need to install the node-mailjet package within the /function directory like this from command line:
cd functions && npm install node-mailjet
Now you can use in the frontend like this: