674

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.

Alireza Sabahi
  • 539
  • 1
  • 9
  • 26
Vinayak Bevinakatti
  • 38,839
  • 25
  • 103
  • 135

25 Answers25

772

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("username@gmail.com", "password");
                    sender.sendMail("This is Subject",   
                            "This is Body",   
                            "user@gmail.com",   
                            "user@yahoo.com");   
                } 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/

Community
  • 1
  • 1
Vinayak Bevinakatti
  • 38,839
  • 25
  • 103
  • 135
  • 55
    Your 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)? – Rich Sep 23 '10 at 19:10
  • 11
    Working for me!!! do not forget to add to your app manifest the uses-permission INTERNET – Avi Shukron May 05 '11 at 23:49
  • 6
    You 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 – CITBL Jun 18 '11 at 17:31
  • 4
    is it possible to use this to attach a jpeg? – jfisk Aug 30 '11 at 19:16
  • 18
    is 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... – pumpkee Sep 21 '11 at 00:46
  • 2
    @Vinayank do you know how can we check whether the mail sent is successful or fail? – Paresh Mayani Sep 23 '11 at 10:25
  • 2
    i am getting this error javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com; – Noby Dec 07 '11 at 14:18
  • 2
    So we have to ask the user for their password to make this work? That does not lower customer interaction. – Justin Mar 14 '12 at 14:41
  • 5
    I 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. – Som May 03 '12 at 07:03
  • 7
    Hi 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. – M.A.Murali May 09 '12 at 18:15
  • 3
    Is it possible to send mail without hard coded username and password? – swathi Jun 05 '12 at 05:17
  • For throes wanting to send the email from the user without them having to enter it into the application. you may be interested in http://stackoverflow.com/questions/2112965/how-to-get-the-android-devices-primary-e-mail-address –  Jun 11 '12 at 08:04
  • It 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. – amit Jul 01 '12 at 02:02
  • 59
    For 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. – Tom Jul 09 '12 at 16:52
  • do you know of a sample code that also shows how to receive email and do something with it on gmail ? – android developer Jul 22 '12 at 07:27
  • 3
    If 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. – Hesham Saeed Sep 01 '12 at 00:11
  • @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? – Muhammad Umar Sep 01 '12 at 04:38
  • this 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 ? – Adithya Sep 30 '12 at 08:19
  • 2
    Rather than linking directly to the JARs, link to the project page. You need to adhere to the licenses of android-javamail – Stealth Rabbi Nov 05 '12 at 15:01
  • 2
    thanx a lot. this code works. Is there any way to send a file through email using this code.! – Sahil Mahajan Mj Nov 14 '12 at 05:15
  • This 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? – Spring Breaker Nov 21 '12 at 13:15
  • @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.... – Mahaveer Muttha Jan 22 '13 at 07:44
  • is there any way that we only provide user email address and not pass? – User42590 Apr 04 '13 at 11:36
  • JSSEProvider class is licensed is there any problem in future terms. – srinivas May 03 '13 at 07:47
  • Can I attach .pdf file ? Please someone tell me. – Big.Child May 08 '13 at 11:10
  • @Vinayak.B I am getting Class not fount exception for GMailSender. Did others who got this error fixed it? – Vaibs May 31 '13 at 07:51
  • 3
    This 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 – cwiggo Jun 06 '13 at 13:07
  • 6
    this 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 – Rupesh Nerkar Jun 11 '13 at 08:04
  • 1
    thanks vinayak , but now how to find that email is not received at the other end . – Tushar Pandey Jul 04 '13 at 10:58
  • 1
    i 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.. – Ranjit Aug 22 '13 at 09:53
  • 4
    For those having problems with Android 4 follow the tutorial http://www.jondev.net/articles/Sending_Emails_without_User_Intervention_%28no_Intents%29_in_Android and execute the actual sending from `AsyncTask`. – bancer Sep 11 '13 at 09:04
  • 5
    it's not working for me same code i had put with permision. there is no error yet not sending mail – PankajAndroid Sep 20 '13 at 04:34
  • 2
    Same problem for me as @AndroidDev even using 2.3. Will try other solution. – Henrique de Sousa Sep 20 '13 at 22:34
  • 1
    @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? – Karthik Oct 03 '13 at 12:47
  • How to set mine type for mail. i.e I want to send email for text/html . – Kirit Vaghela Oct 15 '13 at 10:09
  • @Chris right click on the project - properties - java build path - order and export - and tick all the jars plus private libraries – Chris Sim Oct 18 '13 at 13:03
  • thank 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: hope I helped u – Chris Sim Oct 18 '13 at 13:12
  • 4
    Considering 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... – Paolo Rovelli Dec 02 '13 at 11:23
  • This 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: http://www.jondev.net/articles/Sending_Emails_without_User_Intervention_%28no_Intents%29_in_Android and now its working.. thnx bancer – Chris Sim Dec 06 '13 at 14:37
  • @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. – eawedat Dec 20 '13 at 11:56
  • This is working for me in test mode but not in production. Any ideas? – H P Dec 28 '13 at 23:17
  • 3
    @Vinayak B.: The question is: how do you get this information? "username@gmail.com", "password" – Phantômaxx Jan 09 '14 at 12:03
  • @Vinayak.B sir i am getting authontication failed execption – rajshree Feb 19 '14 at 09:12
  • I 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 – SweetWisher ツ Apr 21 '14 at 09:21
  • 1
    Could you please add a code/link for `AsyncTask implementation?` We are getting `AsyncFutureTask` exception. – Murali Murugesan Nov 06 '14 at 07:31
  • can you tell me by default how to send an email verification for adding new users? – Steve Jan 12 '15 at 11:09
  • 1
    javax.mail.AuthenticationFailedException when sending email althought the user/password are correct. Any solution android 4.4.4? – T D Nguyen Jan 19 '15 at 03:26
  • @VinayakB Is it possible to replace the body string as generated bitmap QR code? –  Jan 31 '15 at 06:30
  • Is there any code if mail not sent successfully then it will be stored as draft. – Pratik Butani Feb 04 '15 at 07:34
  • 1
    I'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 – NoSixties Feb 23 '15 at 14:24
  • 2
    Hi frdz its not working for me ..Error:: android.os.NetworkOnMainThreadException – vijay Mar 05 '15 at 04:25
  • Use 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 – Bamaco Apr 04 '15 at 18:32
  • 5
    Here is seemingly the [original link for the code of this answer](http://www.ssaurel.com/blog/how-to-send-an-email-with-javamail-api-in-android/), and with additional instructions (ie, you need to [enable less secure apps on your Gmail account](https://www.google.com/settings/security/lesssecureapps)). Another [related tutorial here](http://www.jondev.net/articles/Sending_Emails_without_User_Intervention_(no_Intents)_in_Android). – gaborous Aug 11 '15 at 10:03
  • Thanks! 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));` – Ashish Tanna Aug 17 '15 at 20:59
  • I have try this solution but get the "javax.mail.AuthenticationFailedException" even email and password are correct. – Patel Hiren Sep 14 '15 at 13:34
  • 2
    Just click below link to disable security check https://www.google.com/settings/security/lesssecureapps – anshad Oct 19 '15 at 13:11
  • Error: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 – Rjz Satvara Feb 27 '16 at 05:03
  • 1
    how 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. – Inzimam Tariq IT Jun 08 '16 at 09:53
  • 3
    cause the links to the 3 jars are dead here is an update: https://code.google.com/archive/p/javamail-android/downloads – phil Aug 26 '16 at 11:23
  • How can I customise the receiver name and sender name? It just plainly shows the email addresses only. – CyberMew Aug 29 '16 at 04:29
  • 2
    Hello 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? – Jude Maranga Oct 08 '16 at 10:30
  • 1
    Those 3 libraries have the GPL license, which will be an issue with closed source projects. – Cristan Oct 11 '16 at 15:32
  • For this we need SMTP username and password right? And this is not free :( – Kaushal28 Nov 09 '16 at 09:46
  • Those who are facing the problem of "error javax.mail.AuthenticationFailedException",please enable the toggle button from https://myaccount.google.com/u/0/lesssecureapps – Sachin Varma Apr 12 '17 at 08:06
  • Hi **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.jav‌​a:1391)` – Rasool Mohamed Jun 28 '17 at 19:02
  • 3
    is this still working? i tried it but i get no errors but no email either. – Shawnzey Jul 23 '17 at 21:38
  • 3
    This wont work UNLESS you add a new thread: see here http://www.ssaurel.com/blog/how-to-send-an-email-with-javamail-api-in-android/ – Umit Kaya Aug 09 '17 at 15:29
  • You 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); } – Mitja Gustin Oct 12 '17 at 13:44
  • Can we use webmail (noreply@example.com) as a sender email? – mpsbhat Mar 17 '18 at 04:05
  • @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 – Abdulmalek Dery Sep 12 '18 at 08:23
  • I 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? – michasaucer Jan 22 '19 at 17:09
  • 1
    This 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. – Henri L. Feb 12 '19 at 08:23
  • Session.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? – Thiagarajan Hariharan Jul 06 '19 at 07:56
  • Super outdated - surely not the best way to do this in 2020. – Cornelius Roemer Dec 27 '19 at 22:27
  • thank 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? – Mostafa Amer Jan 25 '20 at 12:10
  • must use Async task or background service otherwsie it wont work – Android Geek Jan 28 '20 at 09:41
  • 2
    No exception or error but there is no email inbox or spam – Sevket Apr 26 '20 at 21:02
  • I am getting this error - More than one file was found with OS independent path 'META-INF/mimetypes.default'. – AbhayBohra Jul 29 '20 at 06:41
  • @HenriL. most likely your developer email got restricted. You need to tun on again less secure apps in gmail. – sanevys Dec 01 '20 at 13:59
  • If there's no error but you're not getting any email use thread go to this link: http://www.ssaurel.com/blog/how-to-send-an-email-with-javamail-api-in-android/ it should work. – Dids Feb 09 '21 at 16:32
73

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);
Bo Persson
  • 86,087
  • 31
  • 138
  • 198
ashok reddy
  • 805
  • 8
  • 14
  • 6
    Add this to GmailSender.java – Garbage Jan 23 '13 at 09:12
  • when i called setcontent it overwrote my body content. am i doing anything wrong. i want to add attachment with other textual body content – Calvin Aug 19 '15 at 12:50
  • 1
    for `filename` variable here, you have to specify file path. For example :`String path = Environment.getExternalStorageDirectory().getPath() + "/temp_share.jpg";` –  Nov 09 '16 at 12:57
  • This code helps you to add multiple files https://stackoverflow.com/a/3177640/2811343 ;) :) – AndroidManifester Jan 19 '20 at 20:01
55

Could not connect to SMTP host: smtp.gmail.com, port: 465

Add this line in your manifest:

<uses-permission android:name="android.permission.INTERNET" />
ManuV
  • 559
  • 4
  • 2
40

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

Kshitij Aggarwal
  • 4,960
  • 5
  • 32
  • 41
32

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

libs add

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.

Arpit Patel
  • 8,321
  • 4
  • 56
  • 70
  • 2
    Is this secure? If I replace the "fromEmail" and "fromPassword" with a hardcoded user and password, do I have to worry about security issues? – Yonah Karp Jul 24 '16 at 18:04
  • Is it possible to receive email using your method? I want to receive an email – user3051460 Jul 29 '16 at 10:12
  • 1
    @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. – Totumus Maximus Nov 29 '18 at 11:48
  • @TotumusMaximus If you worried about security than you can use your email and password using api – Arpit Patel Dec 28 '18 at 19:54
  • `setContentView(R.layout.activity_main)` Shouldn't it be `R.layout.activity_mail` in SendMailActivity.java ? – Abhishek Jul 09 '20 at 08:45
  • Sorry that is Typo I changed that. – Arpit Patel Jul 09 '20 at 12:26
  • [This](https://pepipost.com/tutorials/send-email-in-android-using-javamail-api/) uses JavaMail API and worked perfectly fine for me. @ArpitPatel Thanks for this much detailed explanation. It helped me to understand the process very well but I got this [error](https://stackoverflow.com/a/2849357/10036857) and unfortunately, the solution didn't work. – Abhishek Jul 09 '20 at 18:12
  • Did you add the permission in AndroidManifest.xml file? – Arpit Patel Jul 09 '20 at 18:36
  • My AdGuard on android was causing that issue. Damn it, I feel so dumb now. >﹏<. anyways="" for="" help="" thanks="" the=""> – Abhishek Jul 10 '20 at 08:27
  • For 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. – Arpit Patel Oct 16 '20 at 13:57
30

In order to help those getting a Network On Main Thread Exception with an SDK Target >9. This is using droopie's code above but will work similarly for any.

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

android.os.NetworkOnMainThreadException

You can use AsyncTask as below

public void onClickMail(View view) {
    new SendEmailAsyncTask().execute();
}

class SendEmailAsyncTask extends AsyncTask <Void, Void, Boolean> {
    Mail m = new Mail("from@gmail.com", "my password");

    public SendEmailAsyncTask() {
        if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(), "SendEmailAsyncTask()");
        String[] toArr = { "to mail@gmail.com"};
        m.setTo(toArr);
        m.setFrom("from mail@gmail.com");
        m.setSubject("Email from Android");
        m.setBody("body.");
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(), "doInBackground()");
        try {
            m.send();
            return true;
        } catch (AuthenticationFailedException e) {
            Log.e(SendEmailAsyncTask.class.getName(), "Bad account details");
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            Log.e(SendEmailAsyncTask.class.getName(), m.getTo(null) + "failed");
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
daniula
  • 6,639
  • 4
  • 29
  • 47
Ryan Heitner
  • 11,746
  • 6
  • 65
  • 104
24

SMTP

Using SMTP is one way to go, and the others have already pointed out ways how to do it. Just note that while doing this, you completely circumvent the built in mail app, and you will have to provide the address of the SMTP server, the user name and password for that server, either statically in your code, or query it from the user.

HTTP

Another way would involve a simple server side script, like php, that takes some URL parameters and uses them to send a mail. This way, you only need to make an HTTP request from the device (easily possible with the built in libraries) and don't need to store the SMTP login data on the device. This is one more indirection compared to direct SMTP usage, but because it's so very easy to make HTTP request and send mails from PHP, it might even be simpler than the direct way.

Mail Application

If the mail shall be send from the users default mail account that he already registered with the phone, you'd have to take some other approach. If you have enough time and experience, you might want to check the source code of the Android Email application to see if it offers some entry point to send a mail without user interaction (I don't know, but maybe there is one).

Maybe you even find a way to query the users account details (so you can use them for SMTP), though I highly doubt that this is possible, because it would be a huge security risk and Android is built rather securely.

Lena Schimmel
  • 6,934
  • 5
  • 41
  • 56
23

here is an alt version that also works for me and has attachments (posted already above but complete version unlike the source link, which people posted they cant get it to work since its missing data)

import java.util.Date; 
import java.util.Properties; 
import javax.activation.CommandMap; 
import javax.activation.DataHandler; 
import javax.activation.DataSource; 
import javax.activation.FileDataSource; 
import javax.activation.MailcapCommandMap; 
import javax.mail.BodyPart; 
import javax.mail.Multipart; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeBodyPart; 
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart; 


public class Mail extends javax.mail.Authenticator { 
  private String _user; 
  private String _pass; 

  private String[] _to; 
  private String _from; 

  private String _port; 
  private String _sport; 

  private String _host; 

  private String _subject; 
  private String _body; 

  private boolean _auth; 

  private boolean _debuggable; 

  private Multipart _multipart; 


  public Mail() { 
    _host = "smtp.gmail.com"; // default smtp server 
    _port = "465"; // default smtp port 
    _sport = "465"; // default socketfactory port 

    _user = ""; // username 
    _pass = ""; // password 
    _from = ""; // email sent from 
    _subject = ""; // email subject 
    _body = ""; // email body 

    _debuggable = false; // debug mode on or off - default off 
    _auth = true; // smtp authentication - default on 

    _multipart = new MimeMultipart(); 

    // There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added. 
    MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); 
    mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); 
    mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); 
    mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); 
    mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
    mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); 
    CommandMap.setDefaultCommandMap(mc); 
  } 

  public Mail(String user, String pass) { 
    this(); 

    _user = user; 
    _pass = pass; 
  } 

  public boolean send() throws Exception { 
    Properties props = _setProperties(); 

    if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) { 
      Session session = Session.getInstance(props, this); 

      MimeMessage msg = new MimeMessage(session); 

      msg.setFrom(new InternetAddress(_from)); 

      InternetAddress[] addressTo = new InternetAddress[_to.length]; 
      for (int i = 0; i < _to.length; i++) { 
        addressTo[i] = new InternetAddress(_to[i]); 
      } 
        msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); 

      msg.setSubject(_subject); 
      msg.setSentDate(new Date()); 

      // setup message body 
      BodyPart messageBodyPart = new MimeBodyPart(); 
      messageBodyPart.setText(_body); 
      _multipart.addBodyPart(messageBodyPart); 

      // Put parts in message 
      msg.setContent(_multipart); 

      // send email 
      Transport.send(msg); 

      return true; 
    } else { 
      return false; 
    } 
  } 

  public void addAttachment(String filename) throws Exception { 
    BodyPart messageBodyPart = new MimeBodyPart(); 
    DataSource source = new FileDataSource(filename); 
    messageBodyPart.setDataHandler(new DataHandler(source)); 
    messageBodyPart.setFileName(filename); 

    _multipart.addBodyPart(messageBodyPart); 
  } 

  @Override 
  public PasswordAuthentication getPasswordAuthentication() { 
    return new PasswordAuthentication(_user, _pass); 
  } 

  private Properties _setProperties() { 
    Properties props = new Properties(); 

    props.put("mail.smtp.host", _host); 

    if(_debuggable) { 
      props.put("mail.debug", "true"); 
    } 

    if(_auth) { 
      props.put("mail.smtp.auth", "true"); 
    } 

    props.put("mail.smtp.port", _port); 
    props.put("mail.smtp.socketFactory.port", _sport); 
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
    props.put("mail.smtp.socketFactory.fallback", "false"); 

    return props; 
  } 

  // the getters and setters 
  public String getBody() { 
    return _body; 
  } 

  public void setBody(String _body) { 
    this._body = _body; 
  }

  public void setTo(String[] toArr) {
      // TODO Auto-generated method stub
      this._to=toArr;
  }

  public void setFrom(String string) {
      // TODO Auto-generated method stub
      this._from=string;
  }

  public void setSubject(String string) {
      // TODO Auto-generated method stub
      this._subject=string;
  }  

  // more of the getters and setters ….. 
}

and to call it in an activity...

@Override 
public void onCreate(Bundle icicle) { 
  super.onCreate(icicle); 
  setContentView(R.layout.main); 

  Button addImage = (Button) findViewById(R.id.send_email); 
  addImage.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View view) { 
      Mail m = new Mail("gmailusername@gmail.com", "password"); 

      String[] toArr = {"bla@bla.com", "lala@lala.com"}; 
      m.setTo(toArr); 
      m.setFrom("wooo@wooo.com"); 
      m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device."); 
      m.setBody("Email body."); 

      try { 
        m.addAttachment("/sdcard/filelocation"); 

        if(m.send()) { 
          Toast.makeText(MailApp.this, "Email was sent successfully.", Toast.LENGTH_LONG).show(); 
        } else { 
          Toast.makeText(MailApp.this, "Email was not sent.", Toast.LENGTH_LONG).show(); 
        } 
      } catch(Exception e) { 
        //Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show(); 
        Log.e("MailApp", "Could not send email", e); 
      } 
    } 
  }); 
} 
droopie
  • 439
  • 3
  • 10
  • @KeyLimePiePhotonAndroid Add internet permission to your manifest – noob Nov 11 '13 at 12:14
  • how 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? – roger_that Mar 19 '14 at 06:02
  • javax.mail.AuthenticationFailedException any solution for android 4.4.4? – T D Nguyen Jan 19 '15 at 03:23
  • javax.mail.AuthenticationFailedException error came what can i do? – vijay Mar 05 '15 at 06:08
  • 2
    for javax.mail.AuthenticationFailedException , you need to turn on this setting https://www.google.com/settings/security/lesssecureapps – Razel Soco Feb 04 '16 at 11:13
  • 1
    To solve `Could not send email android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork` it is necessary to see this solution http://stackoverflow.com/questions/25093546/android-os-networkonmainthreadexception-at-android-os-strictmodeandroidblockgua – jgrocha Jun 12 '16 at 09:08
  • Is there any way to make it important mail or set higher priority using this way? – Saveen Mar 30 '17 at 07:31
16

GmailBackground is small library to send an email in background without user interaction :

Usage:

    BackgroundMail.newBuilder(this)
            .withUsername("username@gmail.com")
            .withPassword("password12345")
            .withMailto("toemail@gmail.com")
            .withType(BackgroundMail.TYPE_PLAIN)
            .withSubject("this is the subject")
            .withBody("this is the body")
            .withOnSuccessCallback(new BackgroundMail.OnSuccessCallback() {
                @Override
                public void onSuccess() {
                    //do some magic
                }
            })
            .withOnFailCallback(new BackgroundMail.OnFailCallback() {
                @Override
                public void onFail() {
                    //do some magic
                }
            })
            .send();

Configuration:

repositories {
    // ...
    maven { url "https://jitpack.io" }
 }
 dependencies {
            compile 'com.github.yesidlazaro:GmailBackground:1.2.0'
    }

Permissions:

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

Also for attachments, you need to set READ_EXTERNAL_STORAGE permission:

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

Source

(I've tested it myself)

M. Usman Khan
  • 4,258
  • 1
  • 48
  • 62
S.R
  • 2,602
  • 2
  • 17
  • 43
  • I 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? – Erich García Apr 21 '18 at 16:50
  • Hello, i am using this api in my app but it's not working and always calling onfailcallback – Jawad Malik Sep 20 '19 at 08:42
15

Word of warning if using "smtp.gmail.com" as the default smtp server.

Google will force you to change your linked email account password frequently due to their over zealous "suspicious activity" polices. In essence it treats repeated smtp requests from different countries within a short time frame as "suspicious activity". As they assume you (the email account holder) can only be in one country at a time.

When google systems detect "suspicious activity" it will prevent further emails until you change the password. As you will have hard coded the password into the app you have to re-release the app each time this happens, not ideal. This happened 3 times in a week to me, I even stored the password on another server and dynamically fetched the password each time google forced me to change it.

So I recommend using one of the many free smtp providers instead of "smtp.gmail.com" to avoid this security problem. Use the same code but change "smtp.gmail.com" to your new smtp forwarding host.

Mark
  • 1,186
  • 2
  • 16
  • 34
  • 2
    That 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. – Paulo Matuki Nov 11 '14 at 12:54
  • @PauloMatuki , @Mark , Hi, have you guys solve the `suspicioud activity` problem? – Wesley Mar 24 '15 at 09:28
8

Edit: JavaMail 1.5.5 claims to support Android, so you shouldn't need anything else.

I've ported the latest JavaMail (1.5.4) to Android. It's available in Maven Central, just add the following to build.gradle~~

compile 'eu.ocathain.com.sun.mail:javax.mail:1.5.4'

You can then follow the official tutorial.

Source code is available here: https://bitbucket.org/artbristol/javamail-forked-android

artbristol
  • 30,694
  • 5
  • 61
  • 93
  • that 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). – wrapperapps Dec 02 '15 at 06:31
  • @wrapperapps sorry to hear that. "it works for me!". Feel free to open an issue on the bitbucket repo – artbristol Jan 23 '16 at 13:20
8

I found a shorter alternative for others who need help. The code is:

package com.example.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailTLS {

    public static void main(String[] args) {

        final String username = "username@gmail.com";
        final String password = "password";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("username", "password");
            }
          });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("from-email@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("to-email@gmail.com"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

Source: Sending Email via JavaMail API

Hope this Helps! Good Luck!

Shreshth Kharbanda
  • 1,280
  • 9
  • 20
5

For sending a mail with attachment..

public class SendAttachment{
                    public static void main(String [] args){ 
             //to address
                    String to="abc@abc.com";//change accordingly
                    //from address
                    final String user="efg@efg.com";//change accordingly
                    final String password="password";//change accordingly 
                     MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
                   mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
                  mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
                  mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
                  mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
                  mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
                  CommandMap.setDefaultCommandMap(mc); 
                  //1) get the session object   
                  Properties properties = System.getProperties();
                  properties.put("mail.smtp.port", "465"); 
                  properties.put("mail.smtp.host", "smtp.gmail.com");
                    properties.put("mail.smtp.socketFactory.port", "465");
                    properties.put("mail.smtp.socketFactory.class",
                            "javax.net.ssl.SSLSocketFactory");
                    properties.put("mail.smtp.auth", "true");
                    properties.put("mail.smtp.port", "465");

                  Session session = Session.getDefaultInstance(properties,
                   new javax.mail.Authenticator() {
                   protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication(user,password);
                   }
                  });

                  //2) compose message   
                  try{ 
                    MimeMessage message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(user));
                    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
                    message.setSubject("Hii"); 
                    //3) create MimeBodyPart object and set your message content    
                    BodyPart messageBodyPart1 = new MimeBodyPart();
                    messageBodyPart1.setText("How is This"); 
                    //4) create new MimeBodyPart object and set DataHandler object to this object    
                    MimeBodyPart messageBodyPart2 = new MimeBodyPart();
                //Location of file to be attached
                    String filename = Environment.getExternalStorageDirectory().getPath()+"/R2832.zip";//change accordingly
                    DataSource source = new FileDataSource(filename);
                    messageBodyPart2.setDataHandler(new DataHandler(source));
                    messageBodyPart2.setFileName("Hello"); 
                    //5) create Multipart object and add MimeBodyPart objects to this object    
                    Multipart multipart = new MimeMultipart();
                    multipart.addBodyPart(messageBodyPart1);
                    multipart.addBodyPart(messageBodyPart2); 
                    //6) set the multiplart object to the message object
                    message.setContent(multipart ); 
                    //7) send message 
                    Transport.send(message); 
                   System.out.println("MESSAGE SENT....");
                   }catch (MessagingException ex) {ex.printStackTrace();}
                  }
                }
Rashid
  • 492
  • 8
  • 19
  • Add the jar files activation.jar , additionnal.jar , javax.mail.jar – Rashid May 06 '14 at 06:11
  • 1
    I 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? – kodartcha May 13 '14 at 09:54
  • 1
    Try calling the method inside a thread... Its a time consuming process...it cannot run on the main thread... – Rashid May 13 '14 at 09:56
  • Am 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 May 22 '14 at 06:49
  • @Rashid ofcourse I did that. When I was using Intent previously,my attached file was coming right. – Syamantak Basu May 22 '14 at 07:10
5

Those who are getting ClassDefNotFoundError try to move that Three jar files to lib folder of your Project,it worked for me!!

Pratik Butani
  • 51,868
  • 51
  • 228
  • 375
Omkar Gokhale
  • 351
  • 5
  • 6
4

I am unable to run Vinayak B's code. Finally i solved this issue by following :

1.Using this

2.Applying AsyncTask.

3.Changing security issue of sender gmail account.(Change to "TURN ON") in this

RonTLV
  • 2,010
  • 2
  • 19
  • 31
Patriotic
  • 1,186
  • 2
  • 15
  • 27
3

Did you consider using Apache Commons Net ? Since 3.3, just one jar (and you can depend on it using gradle or maven) and you're done : http://blog.dahanne.net/2013/06/17/sending-a-mail-in-java-and-android-with-apache-commons-net/

Anthony Dahanne
  • 4,410
  • 2
  • 37
  • 39
3

Without user intervention, you can send as follows:

  1. Send email from client apk. Here mail.jar, activation.jar is required to send java email. If these jars are added, it might increase the APK Size.

  2. Alternatively, You can use a web-service at the server side code, which will use the same mail.jar and activation.jar to send email. You can call the web-service via asynctask and send email. Refer same link.

(But, you will need to know the credentials of the mail account)

Nishanthi Grashia
  • 9,645
  • 5
  • 41
  • 55
2

In case that you are demanded to keep the jar library as small as possible, you can include the SMTP/POP3/IMAP function separately to avoid the "too many methods in the dex" problem.

You can choose the wanted jar libraries from the javanet web page, for example, mailapi.jar + imap.jar can enable you to access icloud, hotmail mail server in IMAP protocol. (with the help of additional.jar and activation.jar)

Zephyr
  • 5,408
  • 31
  • 32
2

I tried using the code that @Vinayak B submitted. However I'm getting an error saying: No provider for smtp

I created a new question for this with more information HERE

I was able to fix it myself after all. I had to use an other mail.jar and I had to make sure my "access for less secure apps" was turned on.

I hope this helps anyone who has the same problem. With this done, this piece of code works on the google glass too.

Community
  • 1
  • 1
NoSixties
  • 2,286
  • 1
  • 22
  • 58
2

All the code provided in the other answers is correct and is working fine, but a bit messy, so I decided to publish a library (still in development though) to use it in a easier way: AndroidMail.

You have just to create a MailSender, build a mail and send it (already handled in background with an AsyncTask).

MailSender mailSender = new MailSender(email, password);

Mail.MailBuilder builder = new Mail.MailBuilder();
Mail mail = builder
    .setSender(senderMail)
    .addRecipient(new Recipient(recipient))
    .setText("Hello")
    .build();

mailSender.sendMail(mail);

You can receive a notification for the email sent and it has also the support for different Recipients types (TO, CC and BCC), attachments and html:

MailSender mailSender = new MailSender(email, password);

Mail.MailBuilder builder = new Mail.MailBuilder();
Mail mail = builder
    .setSender(senderMail)
    .addRecipient(new Recipient(recipient))
    .addRecipient(new Recipient(Recipient.TYPE.CC, recipientCC))
    .setText("Hello")
    .setHtml("<h1 style=\"color:red;\">Hello</h1>")
    .addAttachment(new Attachment(filePath, fileName))
    .build();

mailSender.sendMail(mail, new MailSender.OnMailSentListener() {

    @Override
    public void onSuccess() {
        // mail sent!
    }

    @Override
    public void onError(Exception error) {
        // something bad happened :(
    }
});

You can get it via Gradle or Maven:

compile 'it.enricocandino:androidmail:1.0.0-SNAPSHOT'

Please let me know if you have any issue with it! :)

Enrichman
  • 10,469
  • 11
  • 62
  • 96
1

Here are a lot solutions. However I think we must change the configuration of the GMail to allow accessing from less secure devices. Go to the link below and enable it. It works for me

https://myaccount.google.com/lesssecureapps?pli=1

0
 Add jar files mail.jar,activation.jar,additionnal.jar

 String sub="Thank you for your online registration" ; 
 Mail m = new Mail("emailid", "password"); 

 String[] toArr = {"ekkatrainfo@gmail.com",sEmailId};
 m.setFrom("ekkatrainfo@gmail.com"); 

     m.setTo(toArr);
     m.setSubject(sub);
    m.setBody(msg);



                     try{


                            if(m.send()) { 

                            } else { 

                            } 
                          } catch(Exception e) { 

                            Log.e("MailApp", "Could not send email", e); 
                          } 

  package com.example.ekktra;

   import java.util.Date;
   import java.util.Properties;

   import javax.activation.CommandMap;
   import javax.activation.DataHandler;
   import javax.activation.DataSource;
   import javax.activation.FileDataSource;
   import javax.activation.MailcapCommandMap;
   import javax.mail.BodyPart;
   import javax.mail.Multipart;
   import javax.mail.PasswordAuthentication;
   import javax.mail.Session;
   import javax.mail.Transport;
   import javax.mail.internet.InternetAddress;
   import javax.mail.internet.MimeBodyPart;
   import javax.mail.internet.MimeMessage;
   import javax.mail.internet.MimeMultipart;

   public class Mail extends javax.mail.Authenticator { 
     private String _user; 
     private String _pass; 

     private String[] _to; 

     private String _from; 

     private String _port; 
     private String _sport; 

     private String _host; 

     private String _subject; 
     private String _body; 

     private boolean _auth; 

     private boolean _debuggable; 

     private Multipart _multipart; 


   public Mail() { 
      _host = "smtp.gmail.com"; // default smtp server 
      _port = "465"; // default smtp port 
      _sport = "465"; // default socketfactory port 

      _user = ""; // username 
      _pass = ""; // password 
      _from = ""; // email sent from 
      _subject = ""; // email subject 
      _body = ""; // email body 

      _debuggable = false; // debug mode on or off - default off 
      _auth = true; // smtp authentication - default on 

      _multipart = new MimeMultipart(); 

      // There is something wrong with MailCap, javamail can not find a handler for the        multipart/mixed part, so this bit needs to be added. 
      MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); 
   mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); 
   mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); 
   mc.addMailcap("text/plain;; x-java-content-  handler=com.sun.mail.handlers.text_plain"); 
   mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
   mc.addMailcap("message/rfc822;; x-java-content- handler=com.sun.mail.handlers.message_rfc822"); 
    CommandMap.setDefaultCommandMap(mc); 
   } 

 public Mail(String user, String pass) { 
  this(); 

  _user = user; 
   _pass = pass; 
 } 

public boolean send() throws Exception { 
   Properties props = _setProperties(); 

  if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") &&   !_subject.equals("") /*&& !_body.equals("")*/) { 
    Session session = Session.getInstance(props, this); 

    MimeMessage msg = new MimeMessage(session); 

     msg.setFrom(new InternetAddress(_from)); 

    InternetAddress[] addressTo = new InternetAddress[_to.length]; 
     for (int i = 0; i < _to.length; i++) { 
      addressTo[i] = new InternetAddress(_to[i]); 
    } 
      msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); 

    msg.setSubject(_subject); 
    msg.setSentDate(new Date()); 

  // setup message body 
  BodyPart messageBodyPart = new MimeBodyPart(); 
    messageBodyPart.setText(_body); 
    _multipart.addBodyPart(messageBodyPart); 

     // Put parts in message 
    msg.setContent(_multipart); 

    // send email 
    Transport.send(msg); 

    return true; 
   } else { 
     return false; 
   } 
  } 

   public void addAttachment(String filename) throws Exception { 
    BodyPart messageBodyPart = new MimeBodyPart(); 
    DataSource source = new FileDataSource(filename); 
      messageBodyPart.setDataHandler(new DataHandler(source)); 
    messageBodyPart.setFileName(filename); 

   _multipart.addBodyPart(messageBodyPart); 
 } 

  @Override 
  public PasswordAuthentication getPasswordAuthentication() { 
     return new PasswordAuthentication(_user, _pass); 
  } 

   private Properties _setProperties() { 
   Properties props = new Properties(); 

    props.put("mail.smtp.host", _host); 

  if(_debuggable) { 
    props.put("mail.debug", "true"); 
  } 

  if(_auth) { 
    props.put("mail.smtp.auth", "true"); 
   } 

    props.put("mail.smtp.port", _port); 
    props.put("mail.smtp.socketFactory.port", _sport); 
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
    props.put("mail.smtp.socketFactory.fallback", "false"); 

    return props; 
   } 

   // the getters and setters 
  public String getBody() { 
   return _body; 
 } 

 public void setBody(String _body) { 
  this._body = _body; 
 }

  public void setTo(String[] toArr) {
     // TODO Auto-generated method stub
    this._to=toArr;
 }

public void setFrom(String string) {
    // TODO Auto-generated method stub
    this._from=string;
}

 public void setSubject(String string) {
    // TODO Auto-generated method stub
    this._subject=string;
  }  


   }
dhiraj kakran
  • 459
  • 1
  • 6
  • 19
0

Sending email programmatically with Kotlin.

  • simple email sending, not all the other features (like attachments).
  • TLS is always on
  • Only 1 gradle email dependency needed also.

I also found this list of email POP services really helpful:

https://support.office.com/en-gb/article/pop-and-imap-email-settings-for-outlook-8361e398-8af4-4e97-b147-6c6c4ac95353

How to use:

    val auth = EmailService.UserPassAuthenticator("you@gmail.com", "yourPassword")
    val to = listOf(InternetAddress("to@email.com"))
    val from = InternetAddress("you@gmail.com")
    val email = EmailService.Email(auth, to, from, "Test Subject", "Hello Body World")
    val emailService = EmailService("smtp.gmail.com", 465)
    
    GlobalScope.launch { // or however you do background threads
        emailService.send(email)
    }

The code:

import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart

class EmailService(private val server: String, private val port: Int) {

    data class Email(
        val auth: Authenticator,
        val toList: List<InternetAddress>,
        val from: Address,
        val subject: String,
        val body: String
    )

    class UserPassAuthenticator(private val username: String, private val password: String) : Authenticator() {
        override fun getPasswordAuthentication(): PasswordAuthentication {
            return PasswordAuthentication(username, password)
        }
    }

    fun send(email: Email) {
        val props = Properties()
        props["mail.smtp.auth"] = "true"
        props["mail.user"] = email.from
        props["mail.smtp.host"] = server
        props["mail.smtp.port"] = port
        props["mail.smtp.starttls.enable"] = "true"
        props["mail.smtp.ssl.trust"] = server
        props["mail.mime.charset"] = "UTF-8"
        val msg: Message = MimeMessage(Session.getDefaultInstance(props, email.auth))
        msg.setFrom(email.from)
        msg.sentDate = Calendar.getInstance().time
        msg.setRecipients(Message.RecipientType.TO, email.toList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.CC, email.ccList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.BCC, email.bccList.toTypedArray())
        msg.replyTo = arrayOf(email.from)

        msg.addHeader("X-Mailer", CLIENT_NAME)
        msg.addHeader("Precedence", "bulk")
        msg.subject = email.subject

        msg.setContent(MimeMultipart().apply {
            addBodyPart(MimeBodyPart().apply {
                setText(email.body, "iso-8859-1")
                //setContent(email.htmlBody, "text/html; charset=UTF-8")
            })
        })
        Transport.send(msg)
    }

    companion object {
        const val CLIENT_NAME = "Android StackOverflow programmatic email"
    }
}

Gradle:

dependencies {
    implementation 'com.sun.mail:android-mail:1.6.4'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
}

AndroidManifest:

<uses-permission android:name="android.permission.INTERNET" />
ar36el
  • 543
  • 1
  • 4
  • 11
Blundell
  • 69,653
  • 29
  • 191
  • 215
0

For those who want to use JavaMail with Kotlin in 2020:

First: Add these dependencies to your build.gradle file (official JavaMail Maven Dependencies)

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

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

implementation "org.bouncycastle:bcmail-jdk15on:1.65"

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7"

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7"

BouncyCastle is for security reasons.

Second: Add these permissions to your AndroidManifest.xml

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

Third: When using SMTP, create a Config file

object Config {
    const val EMAIL_FROM = "You_Sender_Email@email.com"
    const val PASS_FROM = "Your_Sender_Password"

    const val EMAIL_TO = "Your_Destination_Email@email.com"
}

Fourth: Create your Mailer Object

object Mailer {

init {
    Security.addProvider(BouncyCastleProvider())
}

private fun props(): Properties = Properties().also {
        // Smtp server
        it["mail.smtp.host"] = "smtp.gmail.com"
        // Change when necessary
        it["mail.smtp.auth"] = "true"
        it["mail.smtp.port"] = "465"
        // Easy and fast way to enable ssl in JavaMail
        it["mail.smtp.ssl.enable"] = true
    }

// Dont ever use "getDefaultInstance" like other examples do!
private fun session(emailFrom: String, emailPass: String): Session = Session.getInstance(props(), object : Authenticator() {
    override fun getPasswordAuthentication(): PasswordAuthentication {
        return PasswordAuthentication(emailFrom, emailPass)
    }
})

private fun builtMessage(firstName: String, surName: String): String {
    return """
            <b>Name:</b> $firstName  <br/>
            <b>Surname:</b> $surName <br/>
        """.trimIndent()
}

private fun builtSubject(issue: String, firstName: String, surName: String):String {
    return """
            $issue | $firstName, $surName
        """.trimIndent()
}

private fun sendMessageTo(emailFrom: String, session: Session, message: String, subject: String) {
    try {
        MimeMessage(session).let { mime ->
            mime.setFrom(InternetAddress(emailFrom))
            // Adding receiver
            mime.addRecipient(Message.RecipientType.TO, InternetAddress(Config.EMAIL_TO))
            // Adding subject
            mime.subject = subject
            // Adding message
            mime.setText(message)
            // Set Content of Message to Html if needed
            mime.setContent(message, "text/html")
            // send mail
            Transport.send(mime)
        }

    } catch (e: MessagingException) {
        Log.e("","") // Or use timber, it really doesn't matter
    }
}

fun sendMail(firstName: String, surName: String) {
        // Open a session
        val session = session(Config.EMAIL_FROM, Config.PASSWORD_FROM)

        // Create a message
        val message = builtMessage(firstName, surName)

        // Create subject
        val subject = builtSubject(firstName, surName)

        // Send Email
        CoroutineScope(Dispatchers.IO).launch { sendMessageTo(Config.EMAIL_FROM, session, message, subject) }
}

Note

Andrew
  • 1,453
  • 3
  • 18
-3

To add attachment, don't forget to add.

MailcapCommandMap mc = (MailcapCommandMap) CommandMap
            .getDefaultCommandMap();
    mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
    mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
    mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
    mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
    CommandMap.setDefaultCommandMap(mc);
Joe Taras
  • 14,133
  • 7
  • 36
  • 51