Android Development
JavaMail API
Email Sending
Mobile App Programming
Android Java Integration

Sending Email in Android using JavaMail API without using the default/built-in app

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Android applications often require the functionality to send emails for various purposes such as feedback, support, or automated response systems. While the easiest method is to use an Intent to launch the default email client, this approach may not suit all needs, especially when the application requires sending emails silently or without user intervention, such as in background services. In such cases, using the JavaMail API provides a robust solution. This article explains how to implement email functionality in Android using the JavaMail API without launching the default app.

Introduction to JavaMail API

The JavaMail API, which provides a platform-independent and protocol-independent framework to build mail and messaging applications, is widely used in Java EE and Java SE environments. The API is capable of composing, reading, and sending emails via SMTP, POP3, and IMAP. The JavaMail API comes as a part of Java EE but isn't included in the standard Android SDK. To use JavaMail in Android, you need to explicitly add the library to your project.

Setting up JavaMail in an Android Project

To integrate JavaMail in your Android application, you first need to include the JavaMail library and its dependencies into your project. You can do this using Gradle by adding the following dependencies in your build.gradle file:

gradle
implementation 'com.sun.mail:android-mail:1.6.6'
implementation 'com.sun.mail:android-activation:1.6.6'

Configuring the Email Session

To send an email, you need to create a Session object, which requires properties detailing the mail server configuration. Here is an example of setting up a session to use a Gmail SMTP server:

java
1Properties props = new Properties();
2props.put("mail.smtp.auth", "true");
3props.put("mail.smtp.starttls.enable", "true");
4props.put("mail.smtp.host", "smtp.gmail.com");
5props.put("mail.smtp.port", "587");
6
7Session session = Session.getInstance(props, 
8    new javax.mail.Authenticator() {
9        protected PasswordAuthentication getPasswordAuthentication() {
10            return new PasswordAuthentication("[email protected]", "YOUR_PASSWORD");
11        }
12    });

Creating and Sending the Email

After setting up the Session, you can create a Message object and set its properties such as from, to, subject, and content. Here's how you can send a simple text email:

java
1try {
2    Message message = new MimeMessage(session);
3    message.setFrom(new InternetAddress("[email protected]"));
4    message.setRecipients(Message.RecipientType.TO,
5            InternetAddress.parse("[email protected]"));
6    message.setSubject("Mail Subject");
7    message.setText("Hello, this is a test mail!");
8
9    Transport.send(message);
10    System.out.println("Mail sent successfully!");
11} catch (MessagingException e) {
12    e.printStackTrace();
13}

Handling Permissions and Internet Access

Network operations in Android, including sending emails, require the INTERNET permission. Make sure to declare this in your AndroidManifest.xml:

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

Summary Table

ParameterValue
Mail protocolSMTP
Hostsmtp.gmail.com
Port587
AuthenticationYes (email, password)
TLS/SSLRequired (StartTLS enabled)
PermissionINTERNET

Additional Considerations

  • Privacy and Security: Storing email credentials in the application can raise security concerns. Consider encrypted storage options or server-based authentication mechanisms.
  • Library Updates: The JavaMail API versions and their Android adaptations may change. Always check for the latest versions and compatibility.
  • Handling Attachments: Sending emails with attachments involves additional steps to handle multipart content.

Conclusion

Using JavaMail API allows Android applications to send emails without user intervention, providing more control over mail configuration and delivery. This method is particularly useful for applications requiring automatic or background emailing tasks. Ensure to manage credentials securely and keep library dependencies updated for best practices.

This guide provides a basic but comprehensive introduction to sending emails in Android without the built-in app. For more complex requirements such as HTML content, attachments, or integrated messaging protocols, further customization of the JavaMail API can be explored.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.