Sending Email in Android using JavaMail API without using the default/built-in app
Solution 1
Send e-mail in Android using the JavaMail API using Gmail authentication.
Steps to create a sample Project:
MailSenderActivity.java:
public class MailSenderActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button send = (Button) this.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
GMailSender sender = new GMailSender("[email protected]", "password");
sender.sendMail("This is Subject",
"This is Body",
"[email protected]",
"[email protected]");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
});
}
}
GMailSender.java:
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new com.provider.JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}catch(Exception e){
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
JSSEProvider.java:
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Alexander Y. Kleymenov
* @version $Revision$
*/
import java.security.AccessController;
import java.security.Provider;
public final class JSSEProvider extends Provider {
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
ADD 3 jars found in the following link to your Android Project
Click here - How to add External Jars
And don't forget to add this line in your manifest:
<uses-permission android:name="android.permission.INTERNET" />
Just click below link to change account access for less secure apps https://www.google.com/settings/security/lesssecureapps
Run the project and check your recipient mail account for the mail. Cheers!
P.S. And don't forget that you cannot do network operation from any Activity in android.
Hence it is recommended to use AsyncTask
or IntentService
to avoid network on main thread exception.
Jar files: https://code.google.com/archive/p/javamail-android/
Solution 2
Thank you for your valuable information. Code is working fine. I am able to add attachment also by adding following code.
private Multipart _multipart;
_multipart = new MimeMultipart();
public void addAttachment(String filename,String subject) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
BodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.setText(subject);
_multipart.addBodyPart(messageBodyPart2);
}
message.setContent(_multipart);
Solution 3
Could not connect to SMTP host: smtp.gmail.com, port: 465
Add this line in your manifest:
<uses-permission android:name="android.permission.INTERNET" />
Solution 4
You can use JavaMail API to handle your email tasks. JavaMail API is available in JavaEE package and its jar is available for download. Sadly it cannot be used directly in an Android application since it uses AWT components which are completely incompatible in Android.
You can find the Android port for JavaMail at the following location: http://code.google.com/p/javamail-android/
Add the jars to your application and use the SMTP method
Solution 5
100% working code with demo You can also send multiple emails using this answer.
Download Project HERE
Step 1: Download mail, activation, additional jar files and add in your project libs folder in android studio. I added a screenshot see below Download link
Login with gmail (using your from mail) and TURN ON toggle button LINK
Most of the people forget about this step i hope you will not.
Step 2 : After completing this process. Copy and past this classes into your project.
GMail.java
import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class GMail {
final String emailPort = "587";// gmail's smtp port
final String smtpAuth = "true";
final String starttls = "true";
final String emailHost = "smtp.gmail.com";
String fromEmail;
String fromPassword;
List<String> toEmailList;
String emailSubject;
String emailBody;
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
public GMail() {
}
public GMail(String fromEmail, String fromPassword,
List<String> toEmailList, String emailSubject, String emailBody) {
this.fromEmail = fromEmail;
this.fromPassword = fromPassword;
this.toEmailList = toEmailList;
this.emailSubject = emailSubject;
this.emailBody = emailBody;
emailProperties = System.getProperties();
emailProperties.put("mail.smtp.port", emailPort);
emailProperties.put("mail.smtp.auth", smtpAuth);
emailProperties.put("mail.smtp.starttls.enable", starttls);
Log.i("GMail", "Mail server properties set.");
}
public MimeMessage createEmailMessage() throws AddressException,
MessagingException, UnsupportedEncodingException {
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
for (String toEmail : toEmailList) {
Log.i("GMail", "toEmail: " + toEmail);
emailMessage.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail));
}
emailMessage.setSubject(emailSubject);
emailMessage.setContent(emailBody, "text/html");// for a html email
// emailMessage.setText(emailBody);// for a text email
Log.i("GMail", "Email Message created.");
return emailMessage;
}
public void sendEmail() throws AddressException, MessagingException {
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromEmail, fromPassword);
Log.i("GMail", "allrecipients: " + emailMessage.getAllRecipients());
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
transport.close();
Log.i("GMail", "Email sent successfully.");
}
}
SendMailTask.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import java.util.List;
public class SendMailTask extends AsyncTask {
private ProgressDialog statusDialog;
private Activity sendMailActivity;
public SendMailTask(Activity activity) {
sendMailActivity = activity;
}
protected void onPreExecute() {
statusDialog = new ProgressDialog(sendMailActivity);
statusDialog.setMessage("Getting ready...");
statusDialog.setIndeterminate(false);
statusDialog.setCancelable(false);
statusDialog.show();
}
@Override
protected Object doInBackground(Object... args) {
try {
Log.i("SendMailTask", "About to instantiate GMail...");
publishProgress("Processing input....");
GMail androidEmail = new GMail(args[0].toString(),
args[1].toString(), (List) args[2], args[3].toString(),
args[4].toString());
publishProgress("Preparing mail message....");
androidEmail.createEmailMessage();
publishProgress("Sending email....");
androidEmail.sendEmail();
publishProgress("Email Sent.");
Log.i("SendMailTask", "Mail Sent.");
} catch (Exception e) {
publishProgress(e.getMessage());
Log.e("SendMailTask", e.getMessage(), e);
}
return null;
}
@Override
public void onProgressUpdate(Object... values) {
statusDialog.setMessage(values[0].toString());
}
@Override
public void onPostExecute(Object result) {
statusDialog.dismiss();
}
}
Step 3 : Now you can change this class according to your needs also you can send multiple mail using this class. i provide xml and java file both.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="30dp">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="From Email" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:cursorVisible="true"
android:editable="true"
android:ems="10"
android:enabled="true"
android:inputType="textEmailAddress"
android:padding="5dp"
android:textColor="#000000">
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="Password (For from email)" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:ems="10"
android:inputType="textPassword"
android:padding="5dp"
android:textColor="#000000" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="To Email" />
<EditText
android:id="@+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:ems="10"
android:inputType="textEmailAddress"
android:padding="5dp"
android:textColor="#000000" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="Subject" />
<EditText
android:id="@+id/editText4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:ems="10"
android:padding="5dp"
android:textColor="#000000" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="Body" />
<EditText
android:id="@+id/editText5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:ems="10"
android:inputType="textMultiLine"
android:padding="35dp"
android:textColor="#000000" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Email" />
</LinearLayout>
SendMailActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Arrays;
import java.util.List;
public class SendMailActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button send = (Button) this.findViewById(R.id.button1);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("SendMailActivity", "Send Button Clicked.");
String fromEmail = ((TextView) findViewById(R.id.editText1))
.getText().toString();
String fromPassword = ((TextView) findViewById(R.id.editText2))
.getText().toString();
String toEmails = ((TextView) findViewById(R.id.editText3))
.getText().toString();
List<String> toEmailList = Arrays.asList(toEmails
.split("\\s*,\\s*"));
Log.i("SendMailActivity", "To List: " + toEmailList);
String emailSubject = ((TextView) findViewById(R.id.editText4))
.getText().toString();
String emailBody = ((TextView) findViewById(R.id.editText5))
.getText().toString();
new SendMailTask(SendMailActivity.this).execute(fromEmail,
fromPassword, toEmailList, emailSubject, emailBody);
}
});
}
}
Note Dont forget to add internet permission in your AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET"/>
Hope it work if it not then just comment down below.
Vinayak Bevinakatti
Hi! I am an experienced mobile app enthusiast. I enjoy creating apps for Android and iOS. I've worked on Android, iOS, BlackBerry platforms for developing both native and hybrid apps. "Be Proactive, Not Reactive"
Updated on February 04, 2022Comments
-
Vinayak Bevinakatti over 2 years
I am trying to create a mail sending application in Android.
If I use:
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
This will launch the built-in Android application; I'm trying to send the mail on button click directly without using this application.
-
Rich over 13 yearsYour code seems to use hard coded username and password. Is this currently a security risk (meaning, have the apk's that get uploaded to the market been decompiled)?
-
Avi Shukron about 13 yearsWorking for me!!! do not forget to add to your app manifest the uses-permission INTERNET
-
CITBL almost 13 yearsYou have a problem in GMailSender.sendMail(). The problem is that no errors go outside of sendMail because you have try..catch inside it surrounding all the code. You should remove try..catch from sendMail. Otherwise it's impossible to detect errors
-
jfisk over 12 yearsis it possible to use this to attach a jpeg?
-
pumpkee over 12 yearsis there anyway to get an email sent without putting the password into the code? I think users would be startled if i would ask them for their email pw...
-
Paresh Mayani over 12 years@Vinayank do you know how can we check whether the mail sent is successful or fail?
-
Noby over 12 yearsi am getting this error javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
-
Justin about 12 yearsSo we have to ask the user for their password to make this work? That does not lower customer interaction.
-
Som about 12 yearsI am getting java.lang.NoClassDefFoundError: com.som.mail.GMailSender ???? What could be the reason ? The class is there in my project but this Exception is coming.
-
M.A.Murali about 12 yearsHi Thanks for the code. but i got java.lang.NoClassDefFoundError on GMailSender sender = new GMailSender(...) on mailsenderactivity. i included all jars and added to build path. i spent some time to resolve it.but i do not get solution. please help me.
-
swathi almost 12 yearsIs it possible to send mail without hard coded username and password?
-
Admin almost 12 yearsFor throes wanting to send the email from the user without them having to enter it into the application. you may be interested in stackoverflow.com/questions/2112965/…
-
amit almost 12 yearsIt works, thanks. But I'm getting proguard errors when I export. Anybody have the proguard lines to resolve the erors? "can't find referenced class javax.security", etc.
-
Tom almost 12 yearsFor those complaining/asking about how to get user's password - that's not the idea here. This is meant to be used with your (developer's) e-mail account. If you want to rely on user's e-mail account you should use the e-mail intent, which is widely discussed in other posts.
-
android developer almost 12 yearsdo you know of a sample code that also shows how to receive email and do something with it on gmail ?
-
Hesham Saeed over 11 yearsIf someone is afraid of his password, you can put it in resources and use it in code. I decompiled some apps and couldn't get any xml file content, only java files.
-
Muhammad Umar over 11 years@Vinayak.B I am experiencing AuthenticationFailedException at Transport.send(message). I am using simulators right now but My internet works fine. Antivirus is disabled too and i have checked my pass and email too. Any ideas?
-
Adithya over 11 yearsthis works fine using emulator but i am not able to send it using my phone (Galaxy S2). Is there some specific settings i need to do to send it via phone ?
-
Stealth Rabbi over 11 yearsRather than linking directly to the JARs, link to the project page. You need to adhere to the licenses of android-javamail
-
Sahil Mahajan Mj over 11 yearsthanx a lot. this code works. Is there any way to send a file through email using this code.!
-
Spring Breaker over 11 yearsThis code seems to be a nice one but it shows error in file import section. it shows these imports cant be resolved .could you please check it and tell me whats wrong here?
-
Mahaveer Muttha over 11 years@Vinayak.B, Hello All can anybody tell me how to add image and text to body part of this method?? i want to send one image and some text in body of mail....
-
Garbage over 11 yearsAdd this to GmailSender.java
-
User42590 about 11 yearsis there any way that we only provide user email address and not pass?
-
srinivas about 11 yearsJSSEProvider class is licensed is there any problem in future terms.
-
Big.Child about 11 yearsCan I attach .pdf file ? Please someone tell me.
-
Vaibs almost 11 years@Vinayak.B I am getting Class not fount exception for GMailSender. Did others who got this error fixed it?
-
cwiggo almost 11 yearsThis line: Security.addProvider(new com.provider.JSSEProvider()); in GmailSender.java is being highlighted as an error. Does anyone know the solution to this line of code? What does it need to point to, my package name? Thanks
-
Rupesh Nerkar almost 11 yearsthis code is work for android 2.3 but not far latest version android 4.0. means mail is not send on android 4.0.3
-
Tushar Pandey almost 11 yearsthanks vinayak , but now how to find that email is not received at the other end .
-
Ranjit over 10 yearsi use all this things as vinayak gives. Also add all the permissions in my manifest. the problem is when I try to send the mail it takes some time to process but nothings happens. Can anybody helps me here plz..
-
bancer over 10 yearsFor those having problems with Android 4 follow the tutorial jondev.net/articles/… and execute the actual sending from
AsyncTask
. -
PankajAndroid over 10 yearsit's not working for me same code i had put with permision. there is no error yet not sending mail
-
Henrique de Sousa over 10 yearsSame problem for me as @AndroidDev even using 2.3. Will try other solution.
-
Karthik over 10 years@Vinayak.B i have tried with gmail its working fine. And i checked other domains its showing message send and it does not show any error but i m not receiving emails?
-
Kirit Vaghela over 10 yearsHow to set mine type for mail. i.e I want to send email for text/html .
-
Chris Sim over 10 years@Chris right click on the project - properties - java build path - order and export - and tick all the jars plus private libraries
-
Chris Sim over 10 yearsthank you so match for ur awesome answer!!! and thank u AvrahamShukron for your comment guys RupeshNerkar , TusharPandey , RanjitPati , AndroidDev , HenriqueSousa and Karthik maybe it hapened with u like it happened with me: i created a new project and i forgot to add the permission: <uses-permission android:name="android.permission.INTERNET" /> hope I helped u
-
0xC0DED00D over 10 years@KeyLimePiePhotonAndroid Add internet permission to your manifest
-
Paolo Rovelli over 10 yearsConsidering how easy it is to reverse engineering an APK package, do you think this is a safe approach? I mean, storing a password in plain text doesn't sound too good to me...
-
Chris Sim over 10 yearsThis code works on many phones, but it dont on devices version>9 cz there is something like privacy that doesn't allow the new phones to send email .. so I followed this link: jondev.net/articles/… and now its working.. thnx bancer
-
eawedat over 10 years@Vinayak.B when run the code the app is freezing "The application gmail (process com.example.gmail) has stopped unexpectedly. Please try again." , I do not know what is wrong. When I uncomment try{ }catch { } to see the error , eclipse does not allow me to do that.
-
H P over 10 yearsThis is working for me in test mode but not in production. Any ideas?
-
Phantômaxx over 10 years@Vinayak B.: The question is: how do you get this information? "[email protected]", "password"
-
rajshree about 10 years@Vinayak.B sir i am getting authontication failed execption
-
user1050755 about 10 yearsAny maven repository for that?
-
Kshitij Aggarwal about 10 yearsSorry but I'm not aware of that
-
roger_that about 10 yearshow to use this code if I want to use any other email client such as of my org? Would changing just the host name and port be sufficient?
-
SweetWisher ツ about 10 yearsI don't want static password.. i want dynamic data as the user has signed in to the device...how can I implement this requirement... as username and password can vary from device to device
-
Rashid about 10 yearsAdd the jar files activation.jar , additionnal.jar , javax.mail.jar
-
kodartcha about 10 yearsI get the following error when trying your method: 05-13 11:51:50.454: E/AndroidRuntime(4273): android.os.NetworkOnMainThreadException 05-13 11:51:50.454: E/AndroidRuntime(4273): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1156). I have internet permissions. Any advice?
-
Rashid about 10 yearsTry calling the method inside a thread... Its a time consuming process...it cannot run on the main thread...
-
Syamantak Basu almost 10 yearsAm using exactly this code in my Android Project.The mail is working fine for me. But the attachment part is not working. Am trying to attach a .txt file.But the mail am receiving consists of an unknown type of file that am unable to open. Please help.
-
Syamantak Basu almost 10 years@Rashid ofcourse I did that. When I was using Intent previously,my attached file was coming right.
-
Murali Murugesan over 9 yearsCould you please add a code/link for
AsyncTask implementation?
We are gettingAsyncFutureTask
exception. -
Paulo Matuki over 9 yearsThat is a good point. But can you please give an example of alternate email provider that worked with code (only replacing smtp and login details). I've tried it with hushmail and email.com but without success. Will keep trying with others.
-
Steve over 9 yearscan you tell me by default how to send an email verification for adding new users?
-
T D Nguyen over 9 yearsjavax.mail.AuthenticationFailedException any solution for android 4.4.4?
-
T D Nguyen over 9 yearsjavax.mail.AuthenticationFailedException when sending email althought the user/password are correct. Any solution android 4.4.4?
-
Admin over 9 years@VinayakB Is it possible to replace the body string as generated bitmap QR code?
-
Pratik Butani over 9 yearsIs there any code if mail not sent successfully then it will be stored as draft.
-
NoSixties about 9 yearsI'm getting the following exception message: No provider for smtp. Any idea what could be causing this? I added the jar files to compile in gradle and I also included them in settings.gradle
-
vijay about 9 yearsHi frdz its not working for me ..Error:: android.os.NetworkOnMainThreadException
-
vijay about 9 yearsjavax.mail.AuthenticationFailedException error came what can i do?
-
Wesley about 9 years@PauloMatuki , @Mark , Hi, have you guys solve the
suspicioud activity
problem? -
Bamaco about 9 yearsUse to work great, now getting javax.mail.MessagingException, Could not connect to SMTP host: smtp.gmail.com, port: 465; stack shows caused by javax.net.ssl.SSLHandshakeException: com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate: null
-
artbristol about 9 yearsI've ported the latest JavaMail and it's available on Maven Central under
eu.ocathain.com.sun.mail:javax.mail:1.5.2
-
gaborous almost 9 yearsHere is seemingly the original link for the code of this answer, and with additional instructions (ie, you need to enable less secure apps on your Gmail account). Another related tutorial here.
-
Ashish Tanna almost 9 yearsThanks! It worked for me. But there was a problem when I used this code, both outlook and gmail were rejecting the mails. The solution was to set the "from" field :
message.setFrom(new InternetAddress(user));
-
Calvin almost 9 yearswhen i called setcontent it overwrote my body content. am i doing anything wrong. i want to add attachment with other textual body content
-
Patel Hiren over 8 yearsI have try this solution but get the "javax.mail.AuthenticationFailedException" even email and password are correct.
-
anshad over 8 yearsJust click below link to disable security check google.com/settings/security/lesssecureapps
-
wrapperapps over 8 yearsthat maven/gradle line didn't work for me. the 1.5.4 download from your bitbucket also didn't work for me. it failed at the same line as regular non-Android javamail does, which is MimeMessage.setText(text).
-
artbristol over 8 years@wrapperapps sorry to hear that. "it works for me!". Feel free to open an issue on the bitbucket repo
-
Razel Soco over 8 yearsfor javax.mail.AuthenticationFailedException , you need to turn on this setting google.com/settings/security/lesssecureapps
-
Rajesh Satvara about 8 yearsError:Execution failed for task ':MyMailApp:dexDebug'. > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_05\bin\java.exe'' finished with non-zero exit value 2 GOT THIS ERROR
-
Inzimam Tariq IT almost 8 yearshow many minutes will it take to send a mail. Because my app run without any exception but there is no mail in both of my recipient mail ids.
-
jgrocha almost 8 yearsTo solve
Could not send email android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork
it is necessary to see this solution stackoverflow.com/questions/25093546/… -
Yonah Karp almost 8 yearsIs this secure? If I replace the "fromEmail" and "fromPassword" with a hardcoded user and password, do I have to worry about security issues?
-
user3051460 almost 8 yearsIs it possible to receive email using your method? I want to receive an email
-
phil over 7 yearscause the links to the 3 jars are dead here is an update: code.google.com/archive/p/javamail-android/downloads
-
CyberMew over 7 yearsHow can I customise the receiver name and sender name? It just plainly shows the email addresses only.
-
Jude Maranga over 7 yearsHello guys, can you help me? I got no errors but my test recipient email did not get the mail. Anyone who knows the possible reason for this?
-
Cristan over 7 yearsThose 3 libraries have the GPL license, which will be an issue with closed source projects.
-
Kaushal28 over 7 yearsFor this we need SMTP username and password right? And this is not free :(
-
Admin over 7 yearsfor
filename
variable here, you have to specify file path. For example :String path = Environment.getExternalStorageDirectory().getPath() + "/temp_share.jpg";
-
Saveen about 7 yearsIs there any way to make it important mail or set higher priority using this way?
-
Sachin Varma about 7 yearsThose who are facing the problem of "error javax.mail.AuthenticationFailedException",please enable the toggle button from myaccount.google.com/u/0/lesssecureapps
-
Rasool Mohamed almost 7 yearsHi Vinayak Bevinakatti, This code works perfectly with my Mobile Data but its not working on my WIFI. Please assist me. Below are the errors
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465; nested exception is: java.net.ConnectException: failed to connect to smtp.gmail.com/2404:6800:4003:c00::6d (port 465) after 90000ms: isConnected failed: ENETUNREACH (Network is unreachable) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
-
Shawnzey almost 7 yearsis this still working? i tried it but i get no errors but no email either.
-
Umit Kaya almost 7 yearsThis wont work UNLESS you add a new thread: see here ssaurel.com/blog/…
-
Mitja Gustin over 6 yearsYou shuld add recepients one by one in a loop, catching AddressException , otherwise the code fails if usermail is not valid on server. try { final InternetAddress address = new InternetAddress(recepient); try { msg.addRecipient(Message.RecipientType.TO, address); } catch (MessagingException e) { log.log(Level.WARNING, e.getMessage(), e); } } catch (javax.mail.internet.AddressException ex) { log.log(Level.WARNING, ex.getMessage(), ex); }
-
mpsbhat about 6 yearsCan we use webmail ([email protected]) as a sender email?
-
Erich García about 6 yearsI using it and works perfect. But I made some modifications for use it with different email provider and when send email to Gmail it return me "From" header is missing... How solve it?
-
Abdulmalek Dery over 5 years@Vinayak Bevinakatti thank you so much this code worked just fine on preMarshmallow OSs but didn't work on Marshmallow or above "the Transport.send(message) hang and never return" do have any idea how could we send email on those systems
-
Totumus Maximus over 5 years@ArpitPatel this works pretty neatly. But I am also worried about security. If you use gmail, google might block certain apps that try to do just this.
-
Arpit Patel over 5 years@TotumusMaximus If you worried about security than you can use your email and password using api
-
michasaucer over 5 yearsI Copy paste that code and . Code walk all through methods, when it go to
Transport
, i dont have anything on my mailbox. How to find error? -
Henri L. over 5 yearsThis code used to work until a couple of days ago (10-feb-2019). Any idea as to why this no longer works? I do not get any error msg, but no email is sent.
-
Thiagarajan Hariharan almost 5 yearsSession.getDefaultInstance(props, this) crashes the app for me - no exceptions thrown. getDefaultInstance(new Properties(), null) & getInstance(props, this) crash as well. Anyone have this issue?
-
Jawad Malik over 4 yearsHello, i am using this api in my app but it's not working and always calling onfailcallback
-
Cornelius Roemer over 4 yearsSuper outdated - surely not the best way to do this in 2020.
-
AndroidManifester over 4 yearsThis code helps you to add multiple files stackoverflow.com/a/3177640/2811343 ;) :)
-
Mostafa Amer over 4 yearsthank you so much, I want to ask you how to know if recipients email is a real email address? is there a specific exception thrown for this?
-
Android Geek over 4 yearsmust use Async task or background service otherwsie it wont work
-
Sevket about 4 yearsNo exception or error but there is no email inbox or spam
-
Abhishek almost 4 years
setContentView(R.layout.activity_main)
Shouldn't it beR.layout.activity_mail
in SendMailActivity.java ? -
Arpit Patel almost 4 yearsSorry that is Typo I changed that.
-
Abhishek almost 4 years
-
Arpit Patel almost 4 yearsDid you add the permission in AndroidManifest.xml file?
-
Abhishek almost 4 yearsMy AdGuard on android was causing that issue. Damn it, I feel so dumb now. >﹏<. Thanks for the help anyways @ArpitPatel
-
AbhayBohra almost 4 yearsI am getting this error - More than one file was found with OS independent path 'META-INF/mimetypes.default'.
-
Arpit Patel over 3 yearsFor those who ask about how to get the user's password - that's not the idea here. This is meant to be used with your (developer's) e-mail account. If you want to rely on the user's e-mail account you should use the e-mail intent, which is widely discussed in other posts.
-
sanevys over 3 years@HenriL. most likely your developer email got restricted. You need to tun on again less secure apps in gmail.
-
Dids over 3 yearsIf there's no error but you're not getting any email use thread go to this link: ssaurel.com/blog/… it should work.
-
Shailendra Madda almost 3 yearsAlso, you can include a username and password in the app-level build.gradle file and get it wherever you need. For those complaining/asking about how to get a user's password. inside build.gradle (app level)
buildConfigField 'String', 'fromEmail', '"[email protected]"' buildConfigField 'String', 'toEmails', '"[email protected]"' buildConfigField 'String', 'emailPassword', '"test@123"'
In activity use it like:BuildConfig.fromEmail, BuildConfig.emailPassword
-
AlessandroF over 2 yearsI am geting "Required type: Provider - Provided: JSSEProvider" on Security.addProvider(new com.example.liberha.JSSEProvider()); in GmailSender.java. Does anyone know how to fix that?