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.
Table of Contents
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.
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 19 20 |
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.
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 |
<?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.
- Now let’s code the basics in MainActivity.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 |
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.
- 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.Â
- 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 2 3 |
https://api.mailgun.net/v3/mydomain.com/ |
- As we are using the sandbox domain. So the actual API in my case is
1 2 3 |
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.
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.
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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.
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 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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.
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 102 103 |
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 2 3 |
<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.Â
- 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.
[sociallocker id=1372] Mailgun Android Example Source Code [/sociallocker]
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 🙂