Sending transactional emails with a Google Cloud Functions & Mailgun

Peter Kracik
3 min readMay 13, 2020

--

Recently I needed to implement a contact form to a single page static website. As there is no backend, I had to find a solution how to send emails from the browser.

As email service I decided to use Mailgun as I had found good reviews and for the use I need it — not even 1 mail per day, it should be free. Let’s see that in few months :)

The question was how to invoke their api from client-side javascript. I haven’t found any solution, only some stackoverflow comments, that it is not possible from browser.

So I had to find the simplest and fastest solution to have kind of back-end, which will do this job. I turned to the Google Cloud functions.

One of definitions of cloud functions is this, what was exactly my case.

Trigger your code from Google Cloud services or call it directly from any web, mobile, or backend application. Cloud Functions provides a connective layer of logic that lets you integrate and extend Google Cloud and third-party services, making it possible to rapidly build serverless applications that are highly available, secure, and cost-effective. link

So how to achieve that

  1. You need to have to go to Google cloud console, create a project if you don’t have already and then to the part Cloud functions.

2. Click to Create function and configure it as following

  • Give it a name, in my case “my-function”
  • Select trigger — HTTP, so it can be called with simple POST request
  • Check “Allow unauthenticated invocations” so it can be call anonymously from the website
  • Source code — inline editor
  • Runtime — node.js 10 (or the most recent)

3. Then you can write/copy-paster the code directly to the editor. (small hint, the editor can open in larger view).
I had an issue calling it from my website with CORS, so firstly in the function I set Allow-Origin (don’t forget to change it to only your domain from where it will be called) and then I verify if the type of the request is Options. In this case I return 204 — so the browser will know, that the POST request will be accepted.

4. Add packages nodemailer-mailgun-transport and nodemailer into the package.json

5. Insert the name of the function to be invoke. In this case its send.

6. Define environment variables API_KEY, TO, FROM, CC, DOMAIN

7. Click deploy!

Once it’s successfully deployed, you can run a test directly inside Google Cloud functions interface

or in the Postman for example

Seems good to me.

Now the last step is to implement it to my front-end JS script.

const axios = require('axios');
await axios.post(URL_OF_THE_FUNCTION', {
subject: 'Email subject',
message: `Body of the email in html format.`
});

And that’s all.

full code here:

--

--

Peter Kracik

Senior Software developer & DevOps Coordination Ciricle Lead with experience in graphic design #frontend #backend #devops -> kracik.sk