. f Android send emails | Android send emails w/t built-in mailing app | Android send emails from the background ~ Android Developers Blog

Sunday, 15 June 2014

Android send emails | Android send emails w/t built-in mailing app | Android send emails from the background

Hello Friends,
                Today, I am sharing another important tutorial. While doing development
some times we came across to this requirement, "Sending emails to users" without
using any built-in mailing app(like: Gmail,Yahoo etc). In that time we normally depends
on web-service, we write a service in PHP or JAVA or .Net and the communicate b/w them.

But, know now no need to depends on web-service we can send the mail directly through
our java code.

This tutorial going to covers following features :

1. Sending email without using any built-in mailing app
2. Sending emails without User Intervention
3. Sending  emails to multiple users
4. Sending emails with attachment
5. Sending emails silently without any mail composer


Here are my code:

1. Download java mil.jar, activation.jar and additionnal.jar from below link :
        http://code.google.com/p/javamail-android/downloads/list          

2. Add this jar files in your project libs folder

3. MainActivity.java

  1. package com.androiddeveloper.solutions.sendemail;  
  2.   
  3. import java.io.File;  
  4.   
  5. import android.app.Activity;  
  6. import android.app.ProgressDialog;  
  7. import android.os.AsyncTask;  
  8. import android.os.Bundle;  
  9. import android.os.Environment;  
  10. import android.util.Log;  
  11. import android.view.View;  
  12. import android.widget.ImageButton;  
  13. import android.widget.Toast;  
  14.   
  15. /** 
  16.  * @author: Mukesh Y 
  17.  * @link: http://www.androiddevelopersolutions.com/ 
  18.  */  
  19. public class MainActivity extends Activity {  
  20.   
  21.  @Override  
  22.  protected void onCreate(Bundle savedInstanceState) {  
  23.   super.onCreate(savedInstanceState);  
  24.   setContentView(R.layout.activity_main);  
  25.   
  26.   ImageButton addImage = (ImageButton) findViewById(R.id.action_send_email);  
  27.   addImage.setOnClickListener(new View.OnClickListener() {  
  28.    public void onClick(View view) {  
  29.     new BackGroundAsyncTask().execute();  
  30.    }  
  31.   });  
  32.   
  33.  }  
  34.   
  35.  public class BackGroundAsyncTask extends AsyncTask<string string="" void=""> {  
  36.   
  37.   ProgressDialog prog_synprocess = new ProgressDialog(MainActivity.this);  
  38.   
  39.   String statusMessage = "";  
  40.   
  41.   @Override  
  42.   protected void onPostExecute(String status) {  
  43.    prog_synprocess.hide();  
  44.    Toast.makeText(MainActivity.this, status, Toast.LENGTH_LONG).show();  
  45.   
  46.   }  
  47.   
  48.   @Override  
  49.   protected void onPreExecute() {  
  50.    prog_synprocess.setCancelable(false);  
  51.    prog_synprocess.setProgressStyle(ProgressDialog.STYLE_SPINNER);  
  52.    prog_synprocess.setMessage("Sending...");  
  53.    prog_synprocess.show();  
  54.   }  
  55.   
  56.   @Override  
  57.   protected String doInBackground(String... arg0) {  
  58.   
  59.    try {  
  60.     statusMessage = sendLogFile();  
  61.    } catch (Exception e) {  
  62.     Log.e("Error", e.getMessage());  
  63.     statusMessage = "Error in updation";  
  64.    }  
  65.    return statusMessage;  
  66.   
  67.   }  
  68.  }  
  69.   
  70.  private String sendLogFile() {  
  71.   String statusMessage = "";  
  72.   Mail m = new Mail("dataworld.dw@gmail.com""testtest");  
  73.   
  74.   String[] toArr = { "mukesh421985@gmail.com" };  
  75.   m.setTo(toArr);  
  76.   m.setFrom("dataworld.dw@gmail.com");  
  77.   String email_subject = "Testing Send mail";  
  78.   m.setSubject(email_subject);  
  79.   m.setBody("PFA");  
  80.   
  81.   try {  
  82.    String pathToMyAttachedFile = Environment  
  83.      .getExternalStorageDirectory()  
  84.      + File.separator  
  85.      + "Project.log";  
  86.    File file = new File(pathToMyAttachedFile);  
  87.    if (!file.exists() || !file.canRead()) {  
  88.     statusMessage = "File not found";  
  89.     return statusMessage;  
  90.    } else {  
  91.     m.addAttachment(file.getAbsolutePath());  
  92.    }  
  93.    if (m.send()) {  
  94.     statusMessage = "Email was sent successfully.";  
  95.    } else {  
  96.     statusMessage = "Email was not sent.";  
  97.    }  
  98.   } catch (Exception e) {  
  99.    // Toast.makeText(MailApp.this,  
  100.    // "There was a problem sending the email.",  
  101.    // Toast.LENGTH_LONG).show();  
  102.    Log.e("Send Mail", e.getMessage());  
  103.    statusMessage = "There was a problem sending the email.";  
  104.   }  
  105.   
  106.   return statusMessage;  
  107.  }  
  108.   
  109. }  
  110. </string>  

2. Mail.java 

  1. package com.androiddeveloper.solutions.sendemail;  
  2.   
  3. import java.util.Date;  
  4. import java.util.Properties;  
  5.   
  6. import javax.activation.CommandMap;  
  7. import javax.activation.DataHandler;  
  8. import javax.activation.FileDataSource;  
  9. import javax.activation.MailcapCommandMap;  
  10. import javax.mail.BodyPart;  
  11. import javax.mail.Multipart;  
  12. import javax.mail.PasswordAuthentication;  
  13. import javax.mail.Session;  
  14. import javax.mail.Transport;  
  15. import javax.mail.internet.InternetAddress;  
  16. import javax.mail.internet.MimeBodyPart;  
  17. import javax.mail.internet.MimeMessage;  
  18. import javax.mail.internet.MimeMultipart;  
  19.   
  20. /** 
  21.  * @author: Mukesh Y 
  22.  * @link: http://www.androiddevelopersolutions.com/ 
  23.  */  
  24. public class Mail extends javax.mail.Authenticator {  
  25.  private String userName;  
  26.  private String password;  
  27.   
  28.  private String[] to;  
  29.  private String from;  
  30.   
  31.  private String portNumber;  
  32.  private String socketPortNumber;  
  33.   
  34.  private String host;  
  35.   
  36.  private String emailSubject;  
  37.  private String emailBody;  
  38.   
  39.  private boolean auth;  
  40.   
  41.  private boolean debuggable;  
  42.   
  43.  private Multipart multipart;  
  44.   
  45.  public Mail() {  
  46.   // default smtp server  
  47.   host = "smtp.gmail.com";  
  48.     
  49.   // default smtp port  
  50.   portNumber = "465";   
  51.   // default socketfactory port  
  52.   socketPortNumber = "465";  
  53.     
  54.   // username  
  55.   userName = "";   
  56.   password = "";   
  57.     
  58.   // email sent from  
  59.   from = "";   
  60.     
  61.   // email subject  
  62.   emailSubject = "";  
  63.     
  64.   // email body  
  65.   emailBody = "";   
  66.   
  67.   // debug mode on or off - default off  
  68.   debuggable = false;   
  69.     
  70.   // smtp authentication - default on  
  71.   auth = true;   
  72.   
  73.   multipart = new MimeMultipart();  
  74.   
  75.   // There is something wrong with MailCap, javamail can not find a  
  76.   // handler for the multipart/mixed part, so this bit needs to be added.  
  77.   MailcapCommandMap mc = (MailcapCommandMap) CommandMap  
  78.     .getDefaultCommandMap();  
  79.   mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");  
  80.   mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");  
  81.   mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");  
  82.   mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");  
  83.   mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");  
  84.   CommandMap.setDefaultCommandMap(mc);  
  85.  }  
  86.   
  87.  public Mail(String user, String pass) {  
  88.   this();  
  89.   
  90.   userName = user;  
  91.   password = pass;  
  92.  }  
  93.   
  94.  public boolean send() throws Exception {  
  95.   Properties props = _setProperties();  
  96.   
  97.   if (!userName.equals("") && !password.equals("") && to.length > 0  
  98.     && !from.equals("") && !emailSubject.equals("")  
  99.     && !emailBody.equals("")) {  
  100.    Session session = Session.getInstance(props, this);  
  101.   
  102.    MimeMessage msg = new MimeMessage(session);  
  103.   
  104.    msg.setFrom(new InternetAddress(from));  
  105.   
  106.    InternetAddress[] addressTo = new InternetAddress[to.length];  
  107.    for (int i = 0; i < to.length; i++) {  
  108.     addressTo[i] = new InternetAddress(to[i]);  
  109.    }  
  110.    msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);  
  111.   
  112.    msg.setSubject(emailSubject);  
  113.    msg.setSentDate(new Date());  
  114.   
  115.    // setup message body  
  116.    BodyPart messageBodyPart = new MimeBodyPart();  
  117.    messageBodyPart.setText(emailBody);  
  118.    multipart.addBodyPart(messageBodyPart);  
  119.   
  120.    // Put parts in message  
  121.    msg.setContent(multipart);  
  122.   
  123.    // send email  
  124.    Transport.send(msg);  
  125.   
  126.    return true;  
  127.   } else {  
  128.    return false;  
  129.   }  
  130.  }  
  131.   
  132.  public void addAttachment(String filename) throws Exception {  
  133.   BodyPart messageBodyPart = new MimeBodyPart();  
  134.   FileDataSource source = new FileDataSource(filename);  
  135.   messageBodyPart.setDataHandler(new DataHandler(source));  
  136.   messageBodyPart.setFileName(filename);  
  137.   
  138.   multipart.addBodyPart(messageBodyPart);  
  139.  }  
  140.   
  141.  @Override  
  142.  public PasswordAuthentication getPasswordAuthentication() {  
  143.   return new PasswordAuthentication(userName, password);  
  144.  }  
  145.   
  146.  private Properties _setProperties() {  
  147.   Properties props = new Properties();  
  148.   
  149.   props.put("mail.smtp.host", host);  
  150.   
  151.   if (debuggable) {  
  152.    props.put("mail.debug""true");  
  153.   }  
  154.   
  155.   if (auth) {  
  156.    props.put("mail.smtp.auth""true");  
  157.   }  
  158.   
  159.   props.put("mail.smtp.port", portNumber);  
  160.   props.put("mail.smtp.socketFactory.port", socketPortNumber);  
  161.   props.put("mail.smtp.socketFactory.class",  
  162.     "javax.net.ssl.SSLSocketFactory");  
  163.   props.put("mail.smtp.socketFactory.fallback""false");  
  164.   
  165.   return props;  
  166.  }  
  167.   
  168.  // the getters and setters  
  169.  public String getBody() {  
  170.   return emailBody;  
  171.  }  
  172.   
  173.  public void setBody(String _body) {  
  174.   this.emailBody = _body;  
  175.  }  
  176.   
  177.  // more of the getters and setters …..  
  178.  public void setTo(String[] toArr) {  
  179.   this.to = toArr;  
  180.  }  
  181.   
  182.  public void setFrom(String string) {  
  183.   this.from = string;  
  184.  }  
  185.   
  186.  public void setSubject(String string) {  
  187.   this.emailSubject = string;  
  188.  }  
  189. }  


Hope this will helps some one.
Enjoy coding... cheers :)

Mukesh Kumar

Hi Guys I am from Delhi working as Web/Mobile Application Developer(Android Developer), also have knowledge of Roboelctric and Mockito ,android test driven development... Blogging has been my passion and I think blogging is one of the powerful medium to share knowledge and ideas....

0 comments:

Post a Comment

 

Copyright @ 2013 Android Developers Blog.