[2020 version] How to send an email using Android Studio Javamail

I wrote a program to send an email directly from the app in Android Studio with reference to How to send an email from Android Zero using Javamail. Could not build due to a series of errors. Most of the articles were written before 2017 (whether my method was wrong or obsolete), and none of them worked, so I searched for the latest introduction method.

Conclusion: The way to download a jar file and import it into a library is old!

The method often described in the article I searched and found was to download three jar files from javamail-android and manually copy them to the libs folder of Android Studio and install them. However, I found that it can be introduced just by writing it in build.gradle without doing such troublesome things, so I will write how to do it.

: one: Described in AndroidManifest.xml (Internet access permission)

Add permissions. Internet access eliminates the need for users to manually turn on permissions. Add the following sentence: <uses-permission android: name =" android.permission.INTERNET "/>

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mailsend">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

: two: Described in dependencies of build.gradle (app level)

This is the point. Please add the following two sentences.

build.gradle


dependencies {
···abridgement···

    implementation 'com.sun.mail:android-mail:1.6.5'
    implementation 'com.sun.mail:android-activation:1.6.5'
}

: three: Describe the layout

This time I will write a program that sends an email when the button is tapped.

activity_main.xml


<?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"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Email sending test"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send" />

</LinearLayout>

: four: Program description

Please change the email address, password, title, and body of your Google account as appropriate. In addition, this program is designed to email you.

To change the destination address, please refer to "msg.setRecipients (javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse (account +"@gmail.com "));Please change account + "@ gmail.com" to the destination address. (Example of sending from the entered Google account to [email protected]:msg.setRecipients (javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse ("[email protected]")) ; `)

You can also change the email type to CC or BCC, or send to multiple addresses by changing the "javax.mail.Message.RecipientType.TO" part. (Click here for details: http://javadrive.s25.xrea.com/javamail/smtp/index3.html)

MainActivity.java


package com.example.mailsend;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button=findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                asyncTask a=new asyncTask();
                a.execute("Gmail account name (@gmail.Before com)",
                        "Gmail password","Test title","send completely\n Write the text here") ;
            }
        });
    }

    private class asyncTask extends android.os.AsyncTask{
        protected String account;
        protected String password;
        protected String title;
        protected String text;

        @Override
        protected Object doInBackground(Object... obj){
            account=(String)obj[0];
            password=(String)obj[1];
            title=(String)obj[2];
            text=(String)obj[3];

            java.util.Properties properties = new java.util.Properties();
            properties.put("mail.smtp.host", "smtp.gmail.com");
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.port", "465");
            properties.put("mail.smtp.socketFactory.post", "465");
            properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

            final javax.mail.Message msg = new javax.mail.internet.MimeMessage(javax.mail.Session.getDefaultInstance(properties, new javax.mail.Authenticator(){
                @Override
                protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                    return new javax.mail.PasswordAuthentication(account,password);
                }
            }));

            try {
                msg.setFrom(new javax.mail.internet.InternetAddress(account + "@gmail.com"));
                //Send an email to yourself
                msg.setRecipients(javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse(account + "@gmail.com"));
                msg.setSubject(title);
                msg.setText(text);

                javax.mail.Transport.send(msg);

            } catch (Exception e) {
                return (Object)e.toString();
            }

            return (Object)"Transmission is complete";

        }
        @Override
        protected void onPostExecute(Object obj) {
            //Display a message on the screen
            Toast.makeText(MainActivity.this,(String)obj,Toast.LENGTH_LONG).show();
        }
    }
}

: iphone: It looks like it was executed

Tap the "Send" button to send the email. When the transmission is complete, the toast will be displayed. 2_R.png Confirmation of reception 1.png

: chains: Reference site

https://it-engineer-info.com/language/android-app/2142/ http://7ujm.net/android/javamail.html https://stackoverflow.com/questions/32103337/android-studio-noclassdeffounderror

Recommended Posts

[2020 version] How to send an email using Android Studio Javamail
How to make an app using Tensorflow with Android Studio
Send an email using JavaMail on AWS
Make an executable jar using Android Studio
[Java] Send an email using Amazon SES
How to use ExpandableListView in Android Studio
How to build an environment for any version of Ruby using rbenv
I want to send an email in Java.
How to make Unity Native Plugin (Android version)
How to write React Native bridge ~ Android version ~
How to make an crazy Android music player
[Android Studio] How to change TextView to any font [Java]
How to make an oleore generator using swagger codegen
[Android Studio] [Java] How to fix the screen vertically
Send an email with a PDF attachment via JavaMail
How to create an application
How to take a screenshot with the Android Studio emulator
An unsupported Java version How to get rid of errors
How to lower java version
I want to manually send an authorization email with Devise
How to check JSF version
[Spring Boot] Send an email
How to handle an instance
How to authorize using graphql-ruby
How to make an image posted using css look like an icon
Android: How to deal with "Could not determine java version from '10 .0.1'"
How to publish an application using AWS (3) EC2 instance environment construction
[Android studio (version 4.0)] Until project creation
How to "hollow" View on Android
How to insert an external library
[Android] How to make Dialog Fragment
How to build CloudStack using Docker
[Android] How to turn the Notification panel on and off using StatusBarManager
[Android] How to pass images and receive callbacks when sharing using ShareCompat
[Swift] How to set an image in the background without using UIImageView.
How to crop an image with libGDX
How to sort a List using Comparator
[Rails] How to upload images using Carrierwave
How to blur an image (super easy)
[Android] How to deal with dark themes
[Java] How to calculate age using LocalDate
How to publish an application on Heroku
How to define an inner class bean
Java: How to send values from Servlet to Servlet
How to install the legacy version [Java]
[Swift5] How to implement animation using "lottie-ios"
How to implement image posting using rails
How to make asynchronous pagenations using Kaminari
How to write an RSpec controller test
How to add application version information to Sentry information
How to send push notifications on AWS
[Rails] How to handle data using enum
Java to C and C to Java in Android Studio
How to insert icons using Font awesome
[Swift] How to generate an ID to uniquely identify a certain thing (using UUID)
How to create an Excel form using a template file with Spring MVC
I'm making an Android app and I'm stuck with errors and how to solve it