Tuesday, 30 July 2013

Send Email Via Gmail with Java Mail API in Android

Hi Guys!

Today I am sharing the code to send the email via gmail to any gmail user without interfere of any application with help of java mail API.
The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications.
In our application we are going to use following things from JavaMail API:
  • Multipart class: - it allow to device message into multipart so that long message can be sent easily.
  • Session: - in order to send mail we need to create session between hosts.
  • InternetAddress : it contains address , simply maid ID (example: abc@gmail.com).
For use of this you need to download the some jar file from Here.
1.  additional.jar
2. mail.jar
3. activation.jar

Download these jar file and make a java build path with your project.

Lets Start the coding to make a android project.

activity_main.xml



    

    

    

        
    

    

    

MainActivity.java

package com.sunil.sendmail;

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;

import com.sunil.sendmail.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity  implements OnClickListener{

 Session session=null;
 ProgressDialog pdialog=null;
 Context context=null;
 EditText reciept=null;
 EditText sub=null;
 EditText msg=null;
 String recpient=null;
 String subject=null;
 String textmessage=null;
 
   @Override
   protected void onCreate(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
      context=this;
   Button login = (Button) findViewById(R.id.mBtnSubmit);
   reciept=(EditText)findViewById(R.id.editText_to);
   sub = (EditText) findViewById(R.id.editText_sub);
   msg = (EditText) findViewById(R.id.editText_text);
   
   
   login.setOnClickListener(this); 

   
   }
   
  @Override
  public void onClick(View v) {
   
   recpient= reciept.getText().toString();
      subject= sub.getText().toString();
      textmessage= msg.getText().toString();
   
    Properties props = new Properties();
     props.put("mail.smtp.host", "smtp.gmail.com");
     props.put("mail.smtp.socketFactory.port", "465");
     props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
     props.put("mail.smtp.auth", "true");
     props.put("mail.smtp.port", "465");

     session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
                       protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication("Your Gmail-ID", "Your Gmail_password");
     }
     });
     pdialog = ProgressDialog.show(context, "", "Sending Mail...",true);
     RetreiveFeedTask task= new RetreiveFeedTask();
     task.execute();
  }
  
   
   class RetreiveFeedTask extends AsyncTask {

     
    protected String doInBackground(String... urls) {
          try {
              
             Message message = new MimeMessage(session);
             message.setFrom(new InternetAddress("Your Gmail-ID"));
             message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recpient));
             message.setSubject(subject);
             message.setContent(textmessage, "text/html; charset=utf-8");

             Transport.send(message);
             
           
          } 
          catch (MessagingException e) {
            e.printStackTrace();
             }
          catch (Exception e) {
             e.printStackTrace();
            
          }
          return null;
      }

      protected void onPostExecute(String feed) {
       pdialog.dismiss();
       reciept.setText("");
       msg.setText("");
       sub.setText("");
       Toast.makeText(getApplicationContext(), "Message sent", Toast.LENGTH_LONG).show();
          
      }
   }


 }

Add the INTERNET permission in the AndroidManifest file .
  <uses-permission android:name="android.permission.INTERNET"/>

You can download the source code Send Mail.

Cheers Guys!

36 comments:

  1. Very informative, Thank you very much. Just read about a new android email API by the name of Aspose.Email for Android.. Here is the link: http://www.aspose.com/android/email-component.aspx.
    It provides tools to create, read & convert Outlook MSG, PST, EML, EMLX, OST & MHT file formats. Could you please share any code article about it? Thanks

    ReplyDelete
  2. Thank you very much sherazam.
    I will try to implement this new features and share your article. Thanks

    ReplyDelete
  3. hello sunil,thanks for the code,but when I executed this code with out enabling internet on my phone,it did not notify that internet is not enabled.and showed "msg sent..".

    ReplyDelete
    Replies
    1. For this you need to add the code to check the internet before the processing the send the mail and it will show the message when it complete the process. Thanks

      Delete
  4. Hi Sunil, Its a great app thanks alot....
    Sunil.. I tried to download source code but i cant because i have to download each file..

    Can you please Mail ZIP folder Brother...

    Thanks
    brarsukh89all@gmail.com

    ReplyDelete
    Replies
    1. you can download the zip file with password is "android"

      Delete
  5. Great tutorial..is it works only for gmail user? is there anyway to support all mail providers?

    thanks

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. when i download your zip file and execute then application is stop error is
    10-08 12:59:27.650: E/AndroidRuntime(664): java.lang.NoClassDefFoundError: com.example.sendmailtogmail.MainActivity

    ReplyDelete
    Replies
    1. Add all jar files in java build path and if paste all inside the libs folder or checked all in order and export tab then make clean and build then it will remove error

      Delete
  8. dear sir it shows message sent but mail doesn't show in inbox.then how will i know the mail id sent successfully to recipent or not...

    ReplyDelete
    Replies
    1. Refresh you mail or check in span also. If your mail is correct then definitely sent

      Delete
    2. sir i will check the message which sent through app is not available in in box.wat i can do

      Delete
  9. Bonjour j'ai exécuté le code mais, me donne 'erreur : "Unknown permission android.permission.ACCESS_INTERNET in package" alors que j'ai mis cette permission dans mon Manifest. qu'est ce que je doit faire pour ne plus avoir cette erreur. j'ai ecexuté ce code sur mon émulateur. Merci

    ReplyDelete
  10. does it send mail only to gmail ids? If yes, how can I send mail to other than gmail accounts?

    ReplyDelete
    Replies
    1. yes only gmail id if you want to send to other send via Intent Action

      Delete
    2. any other way to send mail to other servers like yahoo, hotmail? I don't want to use Intent Action

      Delete
  11. Hi sunil, how can i attach the image from gallery which is selected in imageview and send through mail

    ReplyDelete
  12. Hi Sunil, I am trying to encrypt gmail message using advanced encryption standard (AES) and use the Diffie Hellman algorithm as key exchange, can I do that? and can you explain it? thank you .. Etqo

    ReplyDelete
  13. sir i am downloading this code but it is giving an error while i am downloading the jar also pls send me the zip file of this.....

    ReplyDelete
  14. my email id is naveen220887@gmail.com

    ReplyDelete
  15. Your source code is password protected...what is the password?

    ReplyDelete
  16. muchisisisimas gracias me sirvió de mucho, por mas que intentara hacer esto siempre me salian errores
    se te agradece por tu ayuda
    saludos cordiales

    ReplyDelete
  17. hi,
    It's work in android 2.3.6 (galaxy ace) , but in android 4.2.1 not work( i have message message sent ) but i don"t receiving e mail

    why?

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. hi,
      It's work in android 2.3.6 (galaxy ace) , but in android 4.2.1(galaxy tab 7) not work( i have message message sent ) but i don"t receiving e mail

      Delete
  18. I got a job by saying this answer in my last interview. thanks for awesome help.
    I got more idea about Java from Besant Technologies. If anyone wants to get Java Training in Chennai visit Besant Technologies.

    ReplyDelete
  19. session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("id@gmail.com", "pass");
    }
    First thank so much for sharing your code with us...
    Sorry, but can you let me know the reason why I can't connet to Gmail server to authenticate...When I run your code, there is an error in Authentication.
    I have checked again...the jar libs, INTERNET permission in the AndroidManifest. But it still appeared error, and can't connect to Gmail. Could you please let me know the possible reasons? Thanks a gain. Have a nice day, too.

    ReplyDelete
  20. only subject come but message is not come these error given....


    Technical details of permanent failure:
    DNS Error: Domain name not found

    ----- Original message -----

    DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
    d=gmail.com; s=20120113;
    h=date:from:to:message-id:subject:mime-version:content-type
    :content-transfer-encoding;
    bh=HrZav2kKCU/uL83dR8JlJGWE88dLiDN37e+0gL+tFXc=;
    b=MZ6TbDVwH+GjDmzHCJDr7H7abfCZTaF4oBi8wtqZnEwCan6zHGxNHzzD47uLdMht7g
    lZVqjlDzUHTwQz8clfTvhFCznHtBq4cV+gHDqrBhhDowy2LjUw60V8VHMrKIrMA9p0vX
    EnyO0w/SOGGhFKP6E7KOpT+8ewW54m0jiXQgAwlzA7ay/tP08qr7S3Ro1YH7A3i65Mzf
    iV2OuwKWlgk91ucjUymfTVNyV0Q9DI4HcaurAAa66oGo04QyREmvhnQe62qw7xuvHuS0
    KDwhJBGcnyk90tx3c3uoAnHApqYBalmORNbOsaaXRu/U06pS06hecX5ZNu58+sEO2xUf
    85dw==
    X-Received: by 10.68.134.198 with SMTP id pm6mr5878655pbb.9.1403279681645;
    Fri, 20 Jun 2014 08:54:41 -0700 (PDT)
    Return-Path:
    Received: from localhost ([14.140.163.250])
    by mx.google.com with ESMTPSA id ja8sm14142444pbd.3.2014.06.20.08.54.39
    for
    (version=TLSv1 cipher=RC4-SHA bits=128/128);
    Fri, 20 Jun 2014 08:54:40 -0700 (PDT)
    Date: Fri, 20 Jun 2014 08:54:40 -0700 (PDT)
    From: loveanjum141@gmail.com
    To: nawead.anjum@gmail
    Message-ID: <1140370304.2.1403279675150.JavaMail.javamailuser@localhost>
    Subject: test
    MIME-Version: 1.0
    Content-Type: text/html; charset=utf-8
    Content-Transfer-Encoding: 7bit

    ReplyDelete
  21. I have tried so many mail sending api codes in android including above given code but always gets java.lang.NoClassDefFoundError: javax.activation.DataHandler exception.
    please help
    Thanks;

    ReplyDelete
    Replies
    1. Add the jar files in libs folder or build the java path

      Delete