Open In App

How to Send Email in Android App Without Using Intent?

Last Updated : 26 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

It is crucial to establish an email connection in the Android application. This enables us to send important messages to users. For example, when the user joins the app first time sending a welcome email is a common practice. Additionally in some applications if a user signs in from a new location a notification is sent to inform them of this activity. The potential applications of this functionality are extensive and can greatly enhance the user experience. In this article, we are going to see how to send an email to one email to the user that we already specified. A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementation

Step 1:

If you’re using Gmail to send mail to users using your personal account then you need your email and app password to get the app password simply go to manage your account search for the app password enter your Google account password and after that, you can specify app name of your choice and create an app password you’ll get one unique password you will get your app password like that
ss1

Step 2: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 3: Adding Dependencies and Permissions

This two dependencies includes the core functionality of JavaMail Api used for sending and Receiving mails in android apps,add this two dependencies in your build.gradle file and sync the project

dependencies {
//..Other Dependencies
implementation 'com.sun.mail:android-mail:1.6.6'
implementation 'com.sun.mail:android-activation:1.6.7'
}

add Jitpack(JitPack is a package repository service) go to settings.gradle of your app


pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
//add 1st here
maven { url 'https://jitpack.io' }

}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
//add here also
maven { url 'https://jitpack.io' }

}
}

rootProject.name = "Gfg App"
include ':app'

Add Internet Permission in Your AndroidMainfest.xml file

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

Step 4: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. We have created one basic UI you can add more text fields and create your own UI,this ui has one text view for banner and one edittext and one button.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:orientation="vertical"
    tools:context=".Test">
  
   <TextView
       android:id="@+id/tv"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_marginBottom="680dp"
       android:text="Geeks For Geeks App"
       android:textColor="#31CC20"
       android:textSize="40dp"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent" />
  
   <EditText
       android:id="@+id/messageEditText"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginBottom="80dp"
       android:hint="Enter your message"
       android:textColor="@color/white"
       android:textColorHint="@color/white"
       app:layout_constraintBottom_toTopOf="@+id/sendEmail"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent" />
  
   <Button
       android:id="@+id/sendEmail"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Send Email"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent"
       app:layout_constraintTop_toTopOf="parent"
       app:layout_constraintVertical_bias="0.628" />
  
</androidx.constraintlayout.widget.ConstraintLayout>


Step 5: Working on Kotlin File

You can specify your own Email and Password and Receiver Email id,if your’re using other smtp port number MimeMessage is a class in the JavaMail API that represents an email message. “MIME” stands for Multipurpose Internet Mail Extensions which is a standard that extends the format of email messages to support text in character sets other than ASCII as well as attachments of audio, video, images, application programs.

Kotlin




package com.ayush.gfgapp
  
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import javax.mail.Authenticator
import javax.mail.Message
import javax.mail.MessagingException
import javax.mail.PasswordAuthentication
import javax.mail.Session
import javax.mail.Transport
import javax.mail.internet.AddressException
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage
  
class Test : AppCompatActivity(){
  
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)        
        
        val btn = findViewById<Button>(R.id.sendEmail)
        val messageEditText = findViewById<EditText>(R.id.messageEditText)
          
        // Setting up a click listener for the button
        btn.setOnClickListener {
            val message = messageEditText.text.toString()
            sendEmail(message)
        }
    }
      
    private fun sendEmail(message:String) {
        try {
            // Defining sender's email and password
            val senderEmail = "example@gmail.com"
            val password = "rqbianlmzsiezetj"
              
            // Defining receiver's email
            val receiverEmail = "example2@gmail.com"
  
            // Defining the SMTP server host
            val stringHost = "smtp.gmail.com"
  
            // Seting up email properties
            val properties = System.getProperties()
            properties["mail.smtp.host"] = stringHost
            properties["mail.smtp.port"] = "465"
            properties["mail.smtp.ssl.enable"] = "true"
            properties["mail.smtp.auth"] = "true"
  
            // Creating a session with authentication
            val session = Session.getInstance(properties, object : Authenticator() {
                override fun getPasswordAuthentication(): PasswordAuthentication {
                    return PasswordAuthentication(senderEmail, password)
                }
            })
  
            // Creating a MimeMessage
            val mimeMessage = MimeMessage(session)
              
            // Adding the recipient's email address
            mimeMessage.addRecipient(Message.RecipientType.TO, InternetAddress(receiverEmail))
  
            // Seting the subject and message content
            // You can Specify yours
            mimeMessage.subject = "TEST#01"
            mimeMessage.setText(message)
  
            // Creating a separate thread to send the email
            val t = Thread {
                try {
                    Transport.send(mimeMessage)
                } catch (e: MessagingException) {
                    // Handling messaging exception 
                    Toast.makeText(this@Test,"Error Occured",Toast.LENGTH_SHORT).show()
                    e.printStackTrace()
                }
            }
            t.start()
        } catch (e: AddressException) {
            // Handling address exception 
            Toast.makeText(this@Test,"Error Occured $e",Toast.LENGTH_SHORT).show()
        } catch (e: MessagingException) {
            // Handling messaging exception (e.g. network error)
            Toast.makeText(this@Test,"Error Occured $e",Toast.LENGTH_SHORT).show()
        }
          
        // Displaying a toast message indicating that the email was sent successfully
        Toast.makeText(this@Test,"Sent Succesfully ",Toast.LENGTH_SHORT).show()
    }
}


Note: Most important don’t use your personal Email Address for production Use ,Use your Bussiness Email other than personal.

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads