Receive Emails by java mail API Android
We can get email through IMAP (Internet Message Access Protocol) Protocol that makes a copy of all mails from your email id and you can get mail using it. Here is a little source code by which we can get email from any gmail id.
package com.example.reademaildemo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
public class EmailAttachmentReceiverActivity extends Activity {
Properties properties = null;
private Session session = null;
private Store store = null;
private Folder inbox = null;
private String userName = "";// provide user name
private String password = "";// provide password
String downloadDirectory = Environment.getExternalStorageState() + "/downloads/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_email_attachment_receiver);
readMails();
/* Properties props = new Properties();
//IMAPS protocol
props.setProperty("mail.store.protocol", "imaps");
//Set host address
props.setProperty("mail.imaps.host", "imap.gmail.com");
//Set specified port
props.setProperty("mail.imaps.port", "993");
//Using SSL
props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imaps.socketFactory.fallback", "false");
//Setting IMAP session
Session imapSession = Session.getInstance(props);
try {
Store store = imapSession.getStore("imaps");
//Connect to server by sending username and password.
//Example mailServer = imap.gmail.com, username = abc, password = abc
store.connect("imap.gmail.com", "email", "pass"); // put email and password here.........
//Get all mails in Inbox Forlder
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
//Return result to array of message
Message[] result = inbox.getMessages();
Log.d("EMAILBYSHIVANG","here...");
Log.d("EMAILBYSHIVANG", "result.................."+result[0].getSubject());
Log.d("EMAILBYSHIVANG", "result.................."+result[0].getMessageNumber());
Log.d("EMAILBYSHIVANG", "result.................."+result[0].getDescription());
Log.d("EMAILBYSHIVANG", "result.................."+result[0].getReceivedDate());
Log.d("EMAILBYSHIVANG", "result.................."+result[0].getFileName());
Log.d("EMAILBYSHIVANG", "result.................."+result[result.length-1].getSubject());
Multipart mp = (Multipart) result[0].getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("SENT DATE:" + result[0].getSentDate());
System.out.println("SUBJECT:" + result[0].getSubject());
System.out.println("CONTENT:" + bp.getContent());
} catch (Exception e) {
Log.d("EMAILBYSHIVANG","Exception........................");
e.printStackTrace();
}
*/ }
public void readMails() {
properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "995");
properties.setProperty("mail.transport.protocol", "imaps");
session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
store = session.getStore("imaps");
store.connect();
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
// Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
Message messages[] = inbox.getMessages();
System.out.println("Shivang........Number of mails = ......................" + messages.length);
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
Address[] from = message.getFrom();
System.out.println("Shivang-------------------------------");
System.out.println("Date : " + message.getSentDate());
System.out.println("From : " + from[0]);
System.out.println("Subject: " + message.getSubject());
System.out.println("Content :");
processMessageBody(message);
System.out.println("--------------------------------");
}
inbox.close(true);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void processMessageBody(Message message) {
try {
Object content = message.getContent();
// check for string
// then check for multipart
if (content instanceof String) {
System.out.println("String Content:....................."+content);
} else if (content instanceof Multipart) {
System.out.println("Multipart content...........................");
Multipart multiPart = (Multipart) content;
procesMultiPart(multiPart);
} else if (content instanceof InputStream) {
System.out.println("Input stream.................................");
InputStream inStream = (InputStream) content;
int ch;
while ((ch = inStream.read()) != -1) {
System.out.write(ch);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
/* public void procesMultiPart(Multipart content) {
try {
int multiPartCount = content.getCount();
for (int i = 0; i < multiPartCount; i++) {
BodyPart bodyPart = content.getBodyPart(i);
Object o;
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println(o);
} else if (o instanceof Multipart) {
procesMultiPart((Multipart) o);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}*/
public void procesMultiPart(Multipart content) {
System.out.println("Here to get attchment,.................................");
try {
for (int i = 0; i < content.getCount(); i++) {
BodyPart bodyPart = content.getBodyPart(i);
Object o;
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println("Text............................... = " + o);
} else if (null != bodyPart.getDisposition()
&& bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
System.out.println("Saving Attached Doc.............................................");
String fileName = bodyPart.getFileName();
System.out.println("fileName = " + fileName);
InputStream inStream = bodyPart.getInputStream();
System.out.println("Saving Attached Doc.............................................");
// String root = getFilesDir().getAbsolutePath();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/EmailTestFolder");
myDir.mkdirs();
File file = new File (myDir, fileName);
if (file.exists ()) file.delete ();
/*try {
FileOutputStream out = new FileOutputStream(file);
// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
// CommonsObjects.logger.log("Exception when save Bitmap to Sd Card", e);
}
}*/
FileOutputStream outStream = new FileOutputStream(file);
// FileOutputStream outStream = new FileOutputStream(new File(
// downloadDirectory + fileName));
byte[] tempBuffer = new byte[4096];// 4 KB
int numRead;
while ((numRead = inStream.read(tempBuffer)) != -1) {
outStream.write(tempBuffer);
}
inStream.close();
outStream.close();
}
// else?
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void closeSession() {
if (null != inbox && null != store) {
try {
inbox.close(true);
store.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
public void deleteMessage(Message message) {
try {
message.setFlag(Flags.Flag.DELETED, true);
System.out.println("deleted mail");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Android Permissions Required:
<uses-permission android:name="com.google.android.gm.permission.READ_GMAIL"/>
<uses-permission android:name="com.google.android.gm.permission.WRITE_GMAIL"/>
<uses-permission android:name="com.google.android.gm.permission.MailProvider"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Download complete demo project from here.
Reference: Googling.
No comments:
Post a Comment