Using JavaMail API in Android with Kotlin

Himanshu Choudhary
3 min readMar 24, 2019

I once have a requirement to send email from my application so, I searched over the internet and didn’t find any which can help me out. So, I gathered information from various websites and then finally able to complete the task.

In this post, I will build a simple function to send an email from your android application.

About JavaMail API:

According to javatpoint, the JavaMail is an API that is used to compose, write and read electronic messages (emails).

The JavaMail API provides protocol-independent and plateform-independent framework for sending and receiving mails.

Gradle dependencies:

In project build.gradle:

In repositories add :

google()
jcenter()
mavenCentral()

maven { url "https://maven.google.com" }

In app build.gradle:

Add dependencies:

implementation 'com.sun.mail:android-mail:1.6.0'
implementation 'com.sun.mail:android-activation:1.6.0'

Before writing mail sending function we have to make a singleton class named as AppExecutors for different threads which we will be using further.

@Singleton
open class AppExecutors(
private val diskIO: Executor,
private val networkIO: Executor,
private val mainThread: Executor
) {
constructor(): this(
Executors.newSingleThreadExecutor(),
Executors.newFixedThreadPool(3),
MainThreadExecutor()
)

fun diskIO(): Executor {
return diskIO
}

fun networkIO(): Executor {
return networkIO
}

fun mainThread(): Executor {
return mainThread
}

private class MainThreadExecutor : Executor {
private val mainThreadHandler = Handler(Looper.getMainLooper())
override fun execute(command: Runnable) {
mainThreadHandler.post(command)
}
}
}

Make a appExecutors variable as:

lateinit var appExecutors: AppExecutors

if you have to use the send email method in an activity then, initialize appExecutors variable in onCreate.

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
appExecutors = AppExecutors()
}

In case of fragment intialize it in onAttach as:

override fun onAttach(context: Context?) {
appExecutors = AppExecutors()
super.onAttach(context)
}

Now, we have make a separate class for initializing email and password.

public class Credentials {
public static final String EMAIL = "youremail@gmail.com";
public static final String PASSWORD ="yourpassword";
}

The function for sending email will be as:

private fun sendEmail(){
appExecutors.diskIO().execute {
val props = System.getProperties()
props.put("mail.smtp.host", "smtp.gmail.com")
props.put("mail.smtp.socketFactory.port", "465")
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.port", "465")

val session = Session.getInstance(props,
object : javax.mail.Authenticator() {
//Authenticating the password
override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication(Credentials.EMAIL, Credentials.PASSWORD)
}
})

try {
//Creating MimeMessage object
val mm = MimeMessage(session)
val emailId = emailEditText.text.toString()
//Setting sender address
mm.setFrom(InternetAddress(Config.EMAIL))
//Adding receiver
mm.addRecipient(Message.RecipientType.TO,
InternetAddress(emailId))
//Adding subject
mm.subject = "Your mail's subject."
//Adding message
mm.setText("Your mail body.")

//Sending email
Transport.send(mm)

appExecutors.mainThread().execute {
//Something that should be executed on main thread.
}

} catch (e: MessagingException) {
e.printStackTrace()
}
}
}

Important note:

Your code part is finished. Now, you have to change some settings in your Gmail account.

Steps to be followed:

  1. Login to your account.
  2. Click on the image on the left of your account profile image, then click on account option.
  3. Click on security option and turn on access to Less secure app access.

“I hope this post will help you. Thank you for reading.Comment if you have any questions.”

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Responses (3)

Write a response