Send mail with Netlify and Mailgun
Tags: javascript, node, netlify, mailgun
Published: 2020-02-23 16:52:24

---
title: Send mail with Netlify and Mailgun
published: true
description: Easily send mail with Netlify functions and Mailgun
tags: #javascript #nodejs #netlify #mailgun
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/t4kc6tg7wk70ogqza7x5.png
---

For a side project I wanted to send activation emails with license keys. My project was a chrome extension and didn't have much of backend, So I hosted it on recently discovered Netlify and ended up using Netlify functions for little bit backend that I had. 

## Prerequisites
We will be writing functions in nodejs so some knowledge of javascript will be required.

### Get Mailgun api key
To get your private api key, go to __Settings > Api Keys__.

![Api keys](https://dev-to-uploads.s3.amazonaws.com/i/dm7veyr5uvnyqt687phm.png)

### Setup Netlify Functions
We will use netlify-lambda for building and locally running netlify functions. To install netlify-lambda - 

`npm install netlify-lambda`

It is suggested that you don't install it as dev dependency.

We also need to create `netlify.toml` file to define where functions will be build and served from.
```toml
[build]
	command = "npm run build"
	functions = "functions/build" # folder where build functions exist
	publish = "public" # folder where functions will be served from
```

#### Create scripts in package.json
netlify-lambda exposes two commands which will help us to build and serve our files

* `netlify-lambda build <folder>` - build functions from <folder> to destination folder defined in `netilfy.toml`. It our case it was 'functions/build'.
* `netlify-lambda serve <folder>` - serves functions present in <folder> locally.

With this information, we can create two scripts in our `package.json`
```javascript
{
  ...
  "scripts": {
    "build": "netlify-lambda build functions",
    "serve": "netlify-lambda serve functions"
  }
  ...
}
```

### Create function for sending mail
With everything setup we can finally write function which will send mail. Mailgun's npm library makes super easy. But first let's install it-

`npm install mailgun-js`

Now create a file in functions folder `sendmail.js`. Name of the file is very important as it will part of function url (in this case it will be something like `https://blahblah.blah/.netlify/functions/sendmail`).

Every function have following general systax which exports a handler- 
```javascript
exports.handler = function(event, context, callback) 
{
    // your server-side functionality
}
```

Let's do some mailgun magic- 
```javascript
const mailgun = require('mailgun-js');

exports.handler = function(event, context, callback) 
{
    const mg = mailgun({
        apiKey: "YOUR_PRIVATE_KEY", 
        domain: "YOUR_DOMAIN"
    });

    const data = {
        from: 'Name <something@YOUR_DOMAIN>',
	to: 'elon@musk.com',
	subject: 'SUBJECT',
	text: 'TEXT',
	html: 'HTML'
    };

   mg.messages().send(data, (error, body) => 
   {
        if (error)
        {
            return console.log(error);
        }

        callback(null, {
            statusCode: 200,
            body: "Mail sent"
        });
   });
}
```

### Test & Deploy
We can locally test our function by running `npm run serve` in terminal. 
To deploy we have to just push commit to github like any other netlify site. Please don't forget to set build command in your deploy settings.

![Build settings](https://dev-to-uploads.s3.amazonaws.com/i/6onvttc1gdibfll3jv03.png)

__And it's done__
Mailgun and Netlify make it really simple and easy to do something like this, that too for free. Netlify functions are really powerful and gives you more freedom than something like firebase function for free.