Skip to main content

Mail Sending In Background

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

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

 Button btn = (Button) findViewById(R.id.button1);
  btn.setOnClickListener(new View.OnClickListener() {
   public void onClick(View view) {

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

Mail m = new Mail("sender@gmail.com", "sender password");

String[] toArr = {"to1@gmail.com", "to2@hotmail.com"};
m.setTo(toArr);
m.setFrom("sender@gmail.com");
m.setSubject("email sent using my Mail JavaMail wrapper from an Android device.");
m.setBody("Email body.");

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

       if(m.send()) {
Toast.makeText(MainActivity.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
       } else {
Toast.makeText(MainActivity.this, "Email was not sent.", Toast.LENGTH_LONG).show();
       }
    } catch(Exception e) {
Toast.makeText(MailApp.this, "problem in sending  email.", Toast.LENGTH_LONG).show();
       Log.e("Mail", "Could not send email", e);
     }
   }
 });
}

}

Mail.java

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();


   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 …..
}

Manifest file

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.mm.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


ADD 3 jars found in the following link to your Android Project

How to add jar  :
 copy the jar files paste it in lib files in project then right click jar files then build path then add to build path
Reference:
http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-built-in-a/2033124#2033124

Comments

  1. not working , Execption Could not connect to SMTP host: smtp.gmail.com, port: 465;

    ReplyDelete

Post a Comment

Popular posts from this blog

Bluetooth Chat Example

Manifest File <manifest xmlns:android="http://schemas.android.com/apk/res/android"       package="com.example.android.BluetoothChat"       android:versionCode="1"       android:versionName="1.0">     <uses-sdk minSdkVersion="7" />     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />     <uses-permission android:name="android.permission.BLUETOOTH" />     <application android:label="@string/app_name"                  android:icon="@drawable/app_icon" >         <activity android:name=".BluetoothChat"                   android:label="@string/app_name"                   android:configChanges="orientation|keyboardHidden">             <intent-filter> ...

Google Map v2 signed map isssue fixed

Hi Step 1: Develop Map Application  using android studio Step 2: For Map viewing we need to have google api key .in order to get api key we need to register application in google api console  https://console.developers.google.com/apis/ Step 3; For getting SHA1 Key please follow the steps            1) Go the java installed folder location , open cmd                 Eg: C:\Program Files\Java\jdk1.7.0_04\bin            2)  Type                   Windows keytool -list -v -keystore "CHANGE WITH OUR KEYSTORE LOC" -alias ALIASNAME -storepass PASSWORD -keypass PASSWORD                   Mac & Linux  keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android Ref:  http://www.truiton.com/2015/04/obtaining-sha1...

Store Image to Google Cloud Store using Google App engine java

Here is sample code for uploading image files to cloud storage bucket in google cloud platform Step 1 Create a google cloud project in cloud (https://console.cloud.google.com/)  enable cloud storage Step 2: Create a new web application project I am using Eclipse with Java for App engine Project Step 3: create a POST web service method the below code for upload image to the existing bucket in google cloud and the uploaded image url will be returned Code   @Path("/addres")  @POST       @Consumes(MediaType.MULTIPART_FORM_DATA)    public String addRestaurant( @FormDataParam("imgname")  String imagename,            @FormDataParam("file") InputStream uploadedInputStream,         @FormDataParam("file") FormDataContentDisposition restImages     ) throws IOException  {   try { // Create your service object Storage storage = St...