Skip to content

Instantly share code, notes, and snippets.

@CastenettoA
Last active October 4, 2022 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CastenettoA/90d93774d5f8a4c5816fce5cd7bf85e1 to your computer and use it in GitHub Desktop.
Save CastenettoA/90d93774d5f8a4c5816fce5cd7bf85e1 to your computer and use it in GitHub Desktop.
A netlify ready serverless function for sending email with MailJet API
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());
@CastenettoA
Copy link
Author

CastenettoA commented Oct 4, 2022

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:

      const data = {
        fromEmail: 'info@castenettoa.com',
        fromName: 'castenettoa.com',
        toEmail: 'castenetto.andrea@gmail.com',
        toName: 'Andrea Castenetto',
        subject: 'Un nuovo servizio è stato acquistato.',
        TextPart: 'Complimenti. Vai su stripe per saperne di più.',
        HtmlPart: 'Complimenti. Vai su stripe per saperne di più.'
      };


      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