Sending email with Meteor and Mailgun
Disclaimer: The simplest way to send email with meteor is probably using the email package. This guide helps understand Mailgun API.
Mailgun API has fortunately made it quite easy for JavaScript applications to send email. Feels like The Meteor Way to me. AND they give you 300 emails a day for free.
Their instructions on how to set up DNS for DigitalOcean had me running in circles because of a flaw, so I made my own guide: Mailgun + DigitalOcean
The code presented here is used for the 'Quick Feedback' box at the bottom of http://movieatmyplace.com
Meteor preparation
Because we're using the post method to connect to Mailgun API, we add the http package
meteor add http
Filestructure
All mailgun functions are in mailgun.js, safe for github. And secrets.js is for api-keys and anything that isn't github-safe.
server/
mailgun.js
secrets.js
Also add secrets.js to your .gitignore, by adding this line:
server/secrets.js
Client code
All you need to do here is call out the necessary function from the server, including the variables that you need.
Meteor.call('emailFeedback', body, any_variable);
Server code
After you've registered with Mailgun, your api-key will be shown at the control panel.
server/secrets.js
Please note, that if you're using Meteor Up to deploy your server, these environment variables should instead be listed in mup.json under the "env"
key.
process.env['MAILGUN_API_KEY'] = "key-keepingitasecretlikeapro";
process.env['MAILGUN_DOMAIN'] = "movieatmyplace.com";
process.env['MAILGUN_API_URL'] = "https://api.mailgun.net/v2";
server/mailgun.js
Meteor.startup(function() {
Meteor.methods({
emailFeedback: function (body, any_variable) {
// Don't wait for result
this.unblock();
// Define the settings
var postURL = process.env.MAILGUN_API_URL + '/' + process.env.MAILGUN_DOMAIN + '/messages';
var options = {
auth: "api:" + process.env.MAILGUN_API_KEY,
params: {
"from":"Movie at My Place <info@movieatmyplace.com>",
"to":['krister.viirsaar@gmail.com'],
"subject": 'movieatmyplace.com quick feedback',
"html": body,
}
}
var onError = function(error, result) {
if(error) {console.log("Error: " + error)}
}
// Send the request
Meteor.http.post(postURL, options, onError);
},
});
});
If anything is unclear, feel free to ask a question in the comments.