DEV Community

Discussion on: Sending Email with Netlify Functions

Collapse
 
thetechnaddict profile image
thetechnaddict • Edited

agh, yes - install the dependencies, well done genius - now I'm forbidden, but definitely getting there!!

I'm loving the tutorial - it is super helpful, Jenna, thanks

Collapse
 
jennapederson profile image
Jenna Pederson

Thanks! Glad you got it ironed out.

Thread Thread
 
thetechnaddict profile image
thetechnaddict

Sadly not yet - I'm now forbidden - I can connect and send using curl but the js version is rejected.

Here is the function paired down to basics with hard-coded everything just to get mailgun working

const mailgun = require('mailgun-js');

exports.handler = async (event) =>
{
const mg = mailgun({
apiKey: "key-exampleofverylongsecretkey",
domain: "mg.example.com",
url: "api.eu.mailgun.net/v3/mg.example.com"
});

const data = {
from: 'Name mailgun@mg.example.com',
to: 'bored@otherexample.com',
subject: 'Worldish',
text: 'Hello W',
html: 'HTML'
};

return mg.messages().send(data).then(() => ({
statusCode: 200,
body: "Your message was sent successfully! We'll be in touch."
})).catch(error => ({
statusCode: 422,
body: Error: ${error}
}));
}




ps - I've tried it with 'key-exampleofsecretcode' and 'exampleofsecretcode' and with and without the url and with the url with and without /messages - same result for all
Thread Thread
 
thetechnaddict profile image
thetechnaddict

I went back to testing with the sandbox and the email sent - but ended up in spam. -which could be reasonable since it claims to be from one domain and has been sent by another. - I guess I just have to test it on the server

Thread Thread
 
thetechnaddict profile image
thetechnaddict

If I hardcode sandbox secrets into the file it sends happily from the localhost. If I then switch to using dotenv it fails suggesting that require('dotenv').config() isn't loading up process.env

Thread Thread
 
thetechnaddict profile image
thetechnaddict

Reinstalling dotenv has sorted the problem