Simplified Coding

  • About
  • Contact Us
  • Advertise
  • Privacy Policy
Home » Mailgun Android Example: Sending Emails with Mailgun

Mailgun Android Example: Sending Emails with Mailgun

September 15, 2018 by Belal Khan 6 Comments

Have you tried creating an app that can send emails? I have posted a tutorial earlier explaining how to send emails using Javamail API. But the problem with Javamail API is an SMTP server is required and in the tutorial we were using Google SMTP. So in this Mailgun Android Example, we will learn sending emails using Mailgun.

Contents

  • 1 What is Mailgun?
  • 2 Mailgun Android Example
    • 2.1 Creating a new Android Studio Project
    • 2.2 Adding Dependencies
    • 2.3 Designing User Interface
    • 2.4 Sending Email using Mailgun
      • 2.4.1 Testing Mailgun API using Postman
        • 2.4.1.1 Base URL
        • 2.4.1.2 Authentication
        • 2.4.1.3 Sending Email
    • 2.5 Using the Mailgun API in Android
      • 2.5.1 Creating API interface
      • 2.5.2 Creating a Singleton Retrofit Client
  • 3 Mailgun Android Example – Source Code
    • 3.1 Sharing is Caring:
    • 3.2 Related

What is Mailgun?

Mailgun is an email service provider for developers. It gives transactional email API Service, so you do not need to worry about creating your own SMTP server. Mailgun gives us RESTful API to perform email operations.

Mailgun Android Example

So now let’s create our email sender app. As always we will open Android Studio and we will create a new project. But before going further, just make sure that you have created an account in Mailgun.

Creating a new Android Studio Project

  • For this example, I have created a project name My Email Sender.
  • Once the project is loaded we will add the required dependencies in our project.

Adding Dependencies

Here I am going to use Retrofit Library. Now retrofit has nothing to do with Mailgun, it is a network library which makes networking easier in our application. Mailgun provides RESTful API for sending emails, and to make the API call we are going to use Retrofit. Though it is optional you can use other libraries as well, or if you don’t want to use any library you can do it without a library as well.

I have already posted tutorials about http calls from android with and without retrofit. You can go through the below links to learn in detail.

  • Retrofit Android Tutorial
  • Android User Registration Tutorial 

But for this post I am going to use Retrofit as it is the best library now. 

  • To add retrofit into your project, open app level build.gradle file and add the following dependencies.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
dependencies {
    //defining retrofit version
    def retrofit_version = '2.4.0'
 
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
 
 
    //adding the dependencies
    implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
    implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
 
 
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

  • After adding the above three lines, sync your project.

Designing User Interface

  • As this is only an example, I am not going to design a very cool or awesome UI. For the simplicity let’s not worry about the look of the app. But yes, you can play with the design as much as you want.
  • For designing a simple UI like me, copy the below xml code to your activity_main.xml file.

activity_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">
 
 
    <EditText
        android:id="@+id/editTextTo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Recipient Email" />
 
    <EditText
        android:id="@+id/editTextFrom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Sender Email" />
    
    <EditText
        android:id="@+id/editTextSubject"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Subject" />
 
    <EditText
        android:id="@+id/editTextMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:hint="message"
        android:lines="7" />
 
    <Button
        android:id="@+id/buttonSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send" />
 
</LinearLayout>

  • The above code will generate the following user interface.
Mailgun Android Example

Mailgun Android Example

  • Now let’s code the basics in MainActivity.java.

MainActivity.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package net.simplifiedcoding.myemailsender;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
 
public class MainActivity extends AppCompatActivity {
 
    private EditText editTextTo;
    private EditText editTextFrom;
    private EditText editTextSubject;
    private EditText editTextMessage;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editTextTo = findViewById(R.id.editTextTo);
        editTextFrom = findViewById(R.id.editTextFrom);
        editTextSubject = findViewById(R.id.editTextSubject);
        editTextMessage = findViewById(R.id.editTextMessage);
 
        findViewById(R.id.buttonSend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendEmail();
            }
        });
    }
 
    private void sendEmail() {
        String to = editTextTo.getText().toString().trim();
        String from = editTextFrom.getText().toString().trim();
        String subject = editTextSubject.getText().toString().trim();
        String message = editTextMessage.getText().toString().trim();
 
        if (!Patterns.EMAIL_ADDRESS.matcher(to).matches()) {
            editTextTo.setError("Valid Recipient required");
            editTextTo.requestFocus();
            return;
        }
 
        if (!Patterns.EMAIL_ADDRESS.matcher(from).matches()) {
            editTextFrom.setError("Valid Sender required");
            editTextFrom.requestFocus();
            return;
        }
 
        if (subject.isEmpty()) {
            editTextSubject.setError("Subject required");
            editTextSubject.requestFocus();
            return;
        }
 
        if (message.isEmpty()) {
            editTextMessage.setError("Message required");
            editTextMessage.requestFocus();
            return;
        }
 
        //send email if validation passes
 
    }
 
}

  • The above written code is very simple, and I don’t think there is a need to explain it. We simply initialised the view objects and we added input validations.

Sending Email using Mailgun

  • Now open your Mailgun account, and click on domains. Here you will see a sandbox domain. If you own a domain you can add it here. But for this example I am going to use the sandbox domain.

Android Mailgun Example

  • If you will use Sandbox domain, you need to add authorized recipients and only those recipients who are authorized will receive the email using sandbox domain. So make sure you add an authorized recipient for testing. 

Mailgun Example Android

  • As you can see above, I have added an authorized recipient.
  • If you want to send emails to any email you need to add your domain here.

Testing Mailgun API using Postman

  • As I already told you Mailgun provides us RESTful Web Service to do operations. And here our task is to send email. So let’s first understand how the Mailgun API works.
Base URL
  • Below is the base URL of our Mailgun API.

1
https://api.mailgun.net/v3/mydomain.com/

  • As we are using the sandbox domain. So the actual API in my case is

1
https://api.mailgun.net/v3/sandbox66d14f253bbf4cb483e451417a933b57.mailgun.org/

  • Remember it is my Mailgun API, for your case you have to use your own custom or sandbox domain. 
Authentication
  • Mailgun API uses HTTP Basic Authentication, where user name is api and password is your api key.
  • To find your API key, click on the domain and you will see the API Key.

Android Mailgun Example

Sending Email
  • Now let’s try sending an email using POSTMAN. (For those who don’t know what is POSTMAN, it is a REST API Development Tool). It is free, if you don’t have search on google and download.
  • For sending an email we will send a POST Request to /messages (We need to add the base URL before).
Endpoint Method Parameters
messages POST to, from, subject, text
  • You can send more parameters, for the details go through the official documentation.
  • Now open POSTMAN and put the URL, required parameters, Basic Auth values and send an HTTP Post request.

Sending Email Mailgun

  • You can see it is working fine.

Using the Mailgun API in Android

  • I hope you got the idea that what we are going to do. It is a simple POST request that we need to make from our Android App and here I am using Retrofit for this.
  • So we need an interface for the API call.

Creating API interface

  • Create an interface named Api and write the following code.

Api.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package net.simplifiedcoding.smsapp;
 
 
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
 
public interface Api {
 
    @FormUrlEncoded
    @POST("messages")
    Call<ResponseBody> sendEmail(
            @Field("from") String from,
            @Field("to") String to,
            @Field("subject") String subject,
            @Field("text") String text
    );
 
}

  • We have now defined the API call.
  • Now we need a Retrofit Client to make the call.

Creating a Singleton Retrofit Client

  • Create a new class named Retrofit Client and write the following code.

RetrofitClient.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package net.simplifiedcoding.myemailsender;
 
import android.util.Base64;
 
import java.io.IOException;
 
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
 
public class RetrofitClient {
 
 
    private static final String BASE_URL = "https://api.mailgun.net/v3/sandboxc241453a79904554a01be513a4783c14.mailgun.org/";
 
    private static final String API_USERNAME = "api";
 
    //you need to change the value to your API key
    private static final String API_PASSWORD = "579769dd1dffd1fdcbe6a95006b5a6d8-c1fe131e-3317072c";
 
    private static final String AUTH = "Basic " + Base64.encodeToString((API_USERNAME+":"+API_PASSWORD).getBytes(), Base64.NO_WRAP);
 
    private static RetrofitClient mInstance;
    private Retrofit retrofit;
 
    private RetrofitClient() {
        OkHttpClient okClient = new OkHttpClient.Builder()
                .addInterceptor(
                        new Interceptor() {
                            @Override
                            public Response intercept(Chain chain) throws IOException {
                                Request original = chain.request();
 
                                //Adding basic auth
                                Request.Builder requestBuilder = original.newBuilder()
                                        .header("Authorization", AUTH)
                                        .method(original.method(), original.body());
 
                                Request request = requestBuilder.build();
                                return chain.proceed(request);
                            }
                        })
                .build();
 
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okClient)
                .build();
    }
 
    public static synchronized RetrofitClient getInstance() {
        if (mInstance == null) {
            mInstance = new RetrofitClient();
        }
        return mInstance;
    }
 
    public Retrofit getClient() {
        return retrofit;
    }
 
    public Api getApi() {
        return retrofit.create(Api.class);
    }
}

  • And we have the Retrofit Client as well. Now we only need to make the call to send email.
  • And to do this we will use the following code.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
        RetrofitClient.getInstance()
                .getApi()
                .sendEmail(from, to, subject, message)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (response.code() == HTTP_OK) {
                            try {
                                JSONObject obj = new JSONObject(response.body().string());
                                Toast.makeText(MainActivity.this, obj.getString("message"), Toast.LENGTH_LONG).show();
                            } catch (JSONException | IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
 
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });

  • So the final code for our MainActivity.java will be.

MainActivity.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package net.simplifiedcoding.myemailsender;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
 
import org.json.JSONException;
import org.json.JSONObject;
 
import java.io.IOException;
 
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
 
import static java.net.HttpURLConnection.HTTP_OK;
 
public class MainActivity extends AppCompatActivity {
 
    private EditText editTextTo;
    private EditText editTextFrom;
    private EditText editTextSubject;
    private EditText editTextMessage;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editTextTo = findViewById(R.id.editTextTo);
        editTextFrom = findViewById(R.id.editTextFrom);
        editTextSubject = findViewById(R.id.editTextSubject);
        editTextMessage = findViewById(R.id.editTextMessage);
 
        findViewById(R.id.buttonSend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendEmail();
            }
        });
    }
 
    private void sendEmail() {
        String to = editTextTo.getText().toString().trim();
        String from = editTextFrom.getText().toString().trim();
        String subject = editTextSubject.getText().toString().trim();
        String message = editTextMessage.getText().toString().trim();
 
        if (!Patterns.EMAIL_ADDRESS.matcher(to).matches()) {
            editTextTo.setError("Valid Recipient required");
            editTextTo.requestFocus();
            return;
        }
 
        if (!Patterns.EMAIL_ADDRESS.matcher(from).matches()) {
            editTextFrom.setError("Valid Sender required");
            editTextFrom.requestFocus();
            return;
        }
 
        if (subject.isEmpty()) {
            editTextSubject.setError("Subject required");
            editTextSubject.requestFocus();
            return;
        }
 
        if (message.isEmpty()) {
            editTextMessage.setError("Message required");
            editTextMessage.requestFocus();
            return;
        }
 
        RetrofitClient.getInstance()
                .getApi()
                .sendEmail(from, to, subject, message)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (response.code() == HTTP_OK) {
                            try {
                                JSONObject obj = new JSONObject(response.body().string());
                                Toast.makeText(MainActivity.this, obj.getString("message"), Toast.LENGTH_LONG).show();
                            } catch (JSONException | IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
 
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
 
    }
 
}

  • Lastly add internet permission to your AndroidManifest.xml file.

1
    <uses-permission android:name="android.permission.INTERNET" />

  • Now you can try running the application. But make sure you are sending the email to an authorized recipient or else you will not receive the email. 
Mailgun Android Example

Mailgun Android Example

  • As you can see it is working fine. If you did not receive the email, check your spam folder.

Mailgun Android Example – Source Code

So guys, if you are having any trouble building the email sender, you can clone my source code. The link to the repository is given below.

Mailgun Android Example Source Code

So that is all for this Mailgun Android Example friends. If you have any question please let me know in the comments. And if you found this post helpful share it with your friends. Thank You 🙂

Sharing is Caring:

  • Tweet
  • Share on Tumblr
  • More
  • Pocket
  • Print
  • Email

Related

Filed Under: Android Application Development, Android Intermediate

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, android etc.

Comments

  1. Rahul Nag says

    September 15, 2018 at 10:14 am

    Hi ….

    U r a great person….and ur videos are really awesome…..

    Love u…and love ur video too

    Reply
  2. sathish kumar says

    October 22, 2018 at 1:39 pm

    how to add multiple recipients to code?

    Reply
  3. Robert says

    October 28, 2018 at 6:03 pm

    Any idea on how to send attachment in that email. Excellent tutorial btw, excellent.

    Reply
    • George says

      February 18, 2019 at 4:16 pm

      Did you get a reply to this?

      Reply
  4. Bhanwarlal suthar says

    November 27, 2018 at 3:48 am

    javax.ws.rs.ProcessingException

    Reply
  5. Preet R Gandhi says

    March 16, 2019 at 7:32 am

    Is there any open source company for android sending mail?

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Search




Download our Android App

Simplified Coding in Google Play

About Me

Belal Khan

Hello I am Belal Khan, founder and owner of Simplified Coding. I am currently pursuing MCA from St. Xavier's College, Ranchi. I love to share my knowledge over Internet.

Connect With Me

Follow @codesimplified
Simplified Coding

Popular Tutorials

  • Android Login and Registration Tutorial with PHP MySQL
  • JSON Parsing in Android – Fetching From MySQL Database
  • Android Volley Tutorial – Fetching JSON Data from URL
  • Android Upload Image to Server using Volley Tutorial
  • Android TabLayout Example using ViewPager and Fragments
  • Retrieve Data From MySQL Database in Android using Volley
  • Android Navigation Drawer Example using Fragments
  • Retrofit Android Example – Fetching JSON from URL
  • Firebase Cloud Messaging Tutorial for Android
  • Android Volley Tutorial – User Registration and Login




Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy

About Simplified Coding

Simplified Coding is a blog for all the students learning programming. We are providing various tutorials related to programming and application development. You can get various nice and simplified tutorials related to programming, app development, graphics designing and animation. We are trying to make these things simplified and entertaining. We are writing text tutorial and creating video and visual tutorials as well. You can check about the admin of the blog here and check out our sitemap

Quick Links

  • Advertise Here
  • Privacy Policy
  • Disclaimer
  • About
  • Contact Us
  • Write for Us

Categories

Android Advance Android Application Development Android Beginners Android Intermediate Ionic Framework Tutorial JavaScript Kotlin Android Others PHP Advance PHP Tutorial React Native

Copyright © 2017 · Simplified Coding· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.