Thursday 21 July 2011

Gmail Client

Hi Guys, I am sharing the code to create your Gmail client. Hope you guys will love it.

Here is the class to fetch email from Gmail Server:
HandleEmail.java

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;

import android.content.Context;
import android.content.SharedPreferences;

public class HandleEmail{
    private static String mailHost="imap.gmail.com";
    private static Session session;
    public static void getMail(Context context, final String user, final String password, int which) throws Exception{
        Properties props=new Properties();
        props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.imap.socketFactory.fallback", "false");
        props.setProperty("mail.imap.port", "993");
        props.setProperty("mail.imap.socketFactory.port", "993");

        session=Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        });
        Store store=session.getStore("imap");
        store.connect(mailHost,user, password);

        Folder folder=store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        Message[] message = folder.getMessages();
        int n = message.length;
   
       GMailSender sender = new GMailSender(user, password);
        Address[] from = message[n-1].getFrom();  //Fetch latest email....
        String sub = message[n-i].getSubject();
        String recipients = from[0].toString();
        int start = recipients.trim().indexOf("<");
        int end = recipients.trim().lastIndexOf(">");
        if(end == -1)
              end = recipients.trim().length();
        String add = recipients.substring(start+1, end);
        String text ="message to send"
        sender.sendMail("subject, text, user, add);
        folder.close(false);
        store.close();
    }

}


The class to send email from Gmail Account:
GMailSender.java

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

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;

public class GMailSender extends javax.mail.Authenticator {
    private String mailhost = "smtp.gmail.com";
    private String user;
    private String password;
    private Session session;

    public GMailSender(String user, String password) throws Exception {
        super();
        this.user = user;
        this.password = password;

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

        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.put("mail.smtp.user", user);
        props.put("mail.smtp.password", password);
        props.setProperty("mail.smtp.quitwait", "false");

        session = Session.getInstance(props,this);
        Transport transport = session.getTransport("smtp");
        transport.connect(mailhost, 465, user, password);
        transport.close();
     
    }

    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);
        if(body==null || body.trim().length()==0)
            return;
        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");
        }
    }
}


Note: You can use GMailSender constructor to verify the Gmail Account is valid or not.

Adding attachment to email
 
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);
 

Note: You will need to add these jar files in your app:


4 comments:

  1. How's the licensing of the 3 .JARs you provided? Can I use them in a non-open-source product?

    ReplyDelete
  2. As far as I know It is available on the net as a free source. You can use it without any hindrance..

    ReplyDelete
  3. This looks promising. I am looking for a way to fetch only new messages that are unread. Is there anything special that I would need in order to do this or is the code above sufficient? Thanks.

    ReplyDelete
  4. If you are continuosly fetching emails then you can maintain count and diffrence with current count will give you the unread mails.

    ReplyDelete