Sunday, July 7, 2013

Android Sending and Recieving Mail Through a your SMTP Port using AsyncTask

In this tutorial i will describe how to send a mail through your smtp port in your application 
  1) For sending or receiving mail you need three jar files i will mention the link for download at the end of tutorial 
2)create xml layout for send mail it can contain to address filed from address field and subject as well as details field
mail.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:background="@drawable/background" >

      

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="100px"
            android:text="To" />

        <EditText
            android:id="@+id/to"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            
             />

        <TextView
            android:id="@+id/Tex"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Subject" />

        <EditText
            android:id="@+id/subject"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Deseas" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="fill_parent"
            android:layout_height="30dp"
            android:text="body" />

        <EditText
            android:id="@+id/body"
            android:layout_width="fill_parent"
            android:layout_height="100dp"
            android:inputType="textMultiLine"
            android:hint="Enter the details about deseas" />

        <Button
            android:id="@+id/send"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Send" />
    </LinearLayout>


3) Create Package name called com.provider in that package create class JSSEProvider.java it extends provider 

package com.provider;

import java.security.Provider;

import java.security.AccessController;
import java.security.Provider;

public 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;
            }
        });
    }


4) Create Class GSender in this class add your SMTP domain and 
import javax.activation.DataHandler;

import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;

public class GSender extends javax.mail.Authenticator {
private String mailhost = "mail.yourhost(please give your host name here).com";
private String user;
private String password;
private Session session;

static {
Security.addProvider(new com.provider.JSSEProvider());
}

public GSender(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", "587");     //Give in the  place of 587 your port number 
props.put("mail.smtp.socketFactory.port", "587");
//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 {
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);
}

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");
}
}


5) Create class SendMail.java 

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SendMail extends Activity{
EditText to,subject,body;
Button send;
String userid = "example@yourdomain.com";
    String password = "your password";    
String from = "example@yourdomain.com";
@Override   
     public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.mail);
             final EditText to = (EditText) this.findViewById(R.id.to);
             final EditText subject = (EditText) this.findViewById(R.id.subject);
             final EditText body = (EditText) this.findViewById(R.id.body);
             send = (Button)findViewById(R.id.send);
             send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
 final GSender sender = new GSender(userid, password);
  new AsyncTask<Void, Void, Void>() {
       @Override public Void doInBackground(Void... arg) {
           try {   
            sender.sendMail(subject.getText().toString(), body
                                            .getText().toString(), from.toString(),
                                            to.getText().toString());  
           } catch (Exception e) {   
               Log.e("SendMail", e.getMessage(), e);   
           }
return null;
 
       }
   }.execute();
   }
});
          
         
            
}
}

I have mention the link for download jar files to send mail please find the below link and dowload the files and import into project 


https://code.google.com/p/javamail-android/downloads/list


If you find any difficulty please give a comment  or send me the mail 

No comments:

Post a Comment