Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Send Emails In An Ionic 2 App Via The Rackspace Mailgun API

Not too long ago I wrote about sending emails in an Ionic Framework app using the Rackspace Mailgun API. To get you up to speed, I often get a lot of questions regarding how to send emails without opening the default mail application from within an Ionic Framework application. There are a few things that could be done. You can either spin up your own API server and send emails from your server via an HTTP request or you can make use of a service.

To compliment the previous post I wrote for Ionic Framework, I figured it would be a good idea to demonstrate how to use Mailgun in an Ionic 2 application.

Mailgun, for the most part, is free. It will take a lot of emails before you enter the paid tier. Regardless, you’ll need an account to follow along with this tutorial.

Let’s start by creating a new Ionic 2 project. From the Command Prompt (Windows) or Terminal (Mac and Linux), execute the following:

ionic start MailgunApp blank --v2
cd MailgunApp
ionic platform add ios
ionic platform add android

A few important things to note here. The first thing to note is the use of the --v2 tag. This is an Ionic 2 project, and to create Ionic 2 projects, the appropriate Ionic CLI must be installed. Finally, you must be using a Mac if you wish to add and build for the iOS platform.

This project uses no plugins or external dependencies. This means we can start coding our application.

Coding the Mailgun Logic

Starting with the logic file, open your project’s app/pages/home/home.ts file and include the following code:

import {Component} from '@angular/core';
import {Http, Request, RequestMethod} from "@angular/http";

@Component({
    templateUrl: 'build/pages/home/home.html'
})
export class HomePage {

    http: Http;
    mailgunUrl: string;
    mailgunApiKey: string;

    constructor(http: Http) {
        this.http = http;
        this.mailgunUrl = "MAILGUN_URL_HERE";
        this.mailgunApiKey = window.btoa("api:key-MAILGUN_API_KEY_HERE");
    }

    send(recipient: string, subject: string, message: string) {
        var requestHeaders = new Headers();
        requestHeaders.append("Authorization", "Basic " + this.mailgunApiKey);
        requestHeaders.append("Content-Type", "application/x-www-form-urlencoded");
        this.http.request(new Request({
            method: RequestMethod.Post,
            url: "https://api.mailgun.net/v3/" + this.mailgunUrl + "/messages",
            body: "[email protected]&to=" + recipient + "&subject=" + subject + "&text=" + message,
            headers: requestHeaders
        }))
        .subscribe(success => {
            console.log("SUCCESS -> " + JSON.stringify(success));
        }, error => {
            console.log("ERROR -> " + JSON.stringify(error));
        });
    }
}

There is a lot going on in the above snippet so let’s break it down.

First you’ll notice the following imports:

import {
    Http,
    Request,
    RequestMethod
} from "@angular/http";

The Mailgun API is accessed via HTTP requests. To make HTTP requests we must include the appropriate Angular dependencies. More on HTTP requests can be seen in a previous post I wrote specifically on the topic.

Next we define our Mailgun domain URL and corresponding API key. For prototyping I usually just use the sandbox domain and key, but it doesn’t cost any extra to use your own domain. However, notice the following:

this.mailgunApiKey = window.btoa("api:key-MAILGUN_API_KEY_HERE");

We are making use of the btoa function that will create a base64 encoded string. Having a base64 encoded string is a requirement when using the authorization header of a request.

Finally we get into the heavy lifting. The send function is where all the magic happens.

The send function expects an authorization header as well as a content type. The Mailgun API expects form data to be sent, not JSON data. This data is to be sent via a POST request.

Creating the Simple UI

This brings us into our UI. To keep things simple our UI is just going to be a form that submits to the send function. Open your project’s app/pages/home/home.html file and include the following code:

<ion-header>
    <ion-navbar>
        <ion-title>Mailgun App</ion-title>
</ion-header>

<ion-content class="home">
    <ion-list>
        <ion-item>
            <ion-label floating>Recipient (To)</ion-label>
            <ion-input type="text" [(ngModel)]="recipient"></ion-input>
        </ion-item>
        <ion-item>
            <ion-label floating>Subject</ion-label>
            <ion-input type="text" [(ngModel)]="subject"></ion-input>
        </ion-item>
        <ion-item>
            <ion-label floating>Message</ion-label>
            <ion-textarea [(ngModel)]="message"></ion-textarea>
        </ion-item>
    </ion-list>
    <div padding>
        <button block (click)="send(recipient, subject, message)">Send</button>
    </div>
</ion-content>

The above form has two standard text input fields for the recipient and subject. There is a text area for the message body and a button for submitting the form data. The input elements are all bound using an ngModel. This allows us to pass the fields into the send function.

Give it a try, you should be able to send emails now via HTTP.

Conclusion

You just saw how to send emails without opening an email client on the users device. This could be useful for sending logs to the developer, or maybe a custom feedback form within the application. Previously I wrote about how to use Mailgun in an Ionic Framework application, but this time we saw how with Ionic 2, Angular, and TypeScript.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

Close

Subscribe To Our Newsletter

Stay up to date on the latest in web, mobile, and game development, plus receive exclusive content by subscribing to The Polyglot Developer newsletter.

Unsubscribe at any time without hassle.