Read GMAIL Email and save attachment in JAVA.
set class path of these jara files mail.jar and activation.jar
and run these piece of code.
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class GmailMailAttach {
public static void main (String args[]) throws Exception {
String host = "pop.gmail.com";
String username = "amitt800"; //Put here Gmail Username without @ sign
String password = "123456"; // put here Gmail password
Session session = Session.getInstance(new Properties(), null);
Store store = session.getStore("pop3s");
store.connect(host, username, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Message message[] = folder.getMessages();
Enumeration headers = message[i].getAllHeaders();
while (headers.hasMoreElements()) {
Header h = (Header) headers.nextElement();
System.out.println(h.getName() + ": " + h.getValue());
}
for(int i=0, n=message.length; i++) {
System.out.println(i + ": " + message[i].getFrom()[0]+ "\t" + message[i].getSubject());
System.out.println("Want to get the content? [Y to read/Q to end]");
String ans = reader.readLine();
ans=ans.toLowerCase();
if ("y".equals(ans)) {
Object content = message[i].getContent();
if (content instanceof Multipart) {
handleMultipart((Multipart)content);
}
else {
handlePart(message[i]);
}
}
else if ("q".equals(ans)) {
break;
}
}
folder.close(false);
store.close();
}
public static void handleMultipart(Multipart multipart) throws MessagingException, IOException {
for (int i=0, n=multipart.getCount(); i
handlePart(multipart.getBodyPart(i));
}
}
public static void handlePart(Part part) throws MessagingException, IOException {
String dposition = part.getDisposition();
String cType = part.getContentType();
if (dposition == null) {
System.out.println("Null: " + cType);
if ((cType.length() >= 10) && (cType.toLowerCase().substring(0, 10).equals("text/plain"))) {
part.writeTo(System.out);
}
else {
System.out.println("Other body: " + cType);
part.writeTo(System.out);
}
}
else if (dposition.equalsIgnoreCase(Part.ATTACHMENT)) {
System.out.println("Attachment: " + part.getFileName() + " : " + cType);
saveFile(part.getFileName(), part.getInputStream());
}
else if (dposition.equalsIgnoreCase(Part.INLINE)) {
System.out.println("Inline: " + part.getFileName() + " : " + cType);
saveFile(part.getFileName(), part.getInputStream());
}
else {
System.out.println("Other: " + dposition);
}
}
public static void saveFile(String filename,InputStream input) throws IOException {
if (filename == null) {
filename = File.createTempFile("MailAttacheFile", ".out").getName();
}
System.out.println("downloading attachment...");
File file = new File(filename);
for (int i=0; file.exists(); i++) {
file = new File(filename+i);
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(input);
int fByte;
while ((fByte = bis.read()) != -1) {
bos.write(fByte);
}
bos.flush();
bos.close();
bis.close();
System.out.println("done attachment...");
}
}
set class path of these jara files mail.jar and activation.jar
and run these piece of code.
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class GmailMailAttach {
public static void main (String args[]) throws Exception {
String host = "pop.gmail.com";
String username = "amitt800"; //Put here Gmail Username without @ sign
String password = "123456"; // put here Gmail password
Session session = Session.getInstance(new Properties(), null);
Store store = session.getStore("pop3s");
store.connect(host, username, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Message message[] = folder.getMessages();
Enumeration headers = message[i].getAllHeaders();
while (headers.hasMoreElements()) {
Header h = (Header) headers.nextElement();
System.out.println(h.getName() + ": " + h.getValue());
}
for(int i=0, n=message.length; i++) {
System.out.println(i + ": " + message[i].getFrom()[0]+ "\t" + message[i].getSubject());
System.out.println("Want to get the content? [Y to read/Q to end]");
String ans = reader.readLine();
ans=ans.toLowerCase();
if ("y".equals(ans)) {
Object content = message[i].getContent();
if (content instanceof Multipart) {
handleMultipart((Multipart)content);
}
else {
handlePart(message[i]);
}
}
else if ("q".equals(ans)) {
break;
}
}
folder.close(false);
store.close();
}
public static void handleMultipart(Multipart multipart) throws MessagingException, IOException {
for (int i=0, n=multipart.getCount(); i
handlePart(multipart.getBodyPart(i));
}
}
public static void handlePart(Part part) throws MessagingException, IOException {
String dposition = part.getDisposition();
String cType = part.getContentType();
if (dposition == null) {
System.out.println("Null: " + cType);
if ((cType.length() >= 10) && (cType.toLowerCase().substring(0, 10).equals("text/plain"))) {
part.writeTo(System.out);
}
else {
System.out.println("Other body: " + cType);
part.writeTo(System.out);
}
}
else if (dposition.equalsIgnoreCase(Part.ATTACHMENT)) {
System.out.println("Attachment: " + part.getFileName() + " : " + cType);
saveFile(part.getFileName(), part.getInputStream());
}
else if (dposition.equalsIgnoreCase(Part.INLINE)) {
System.out.println("Inline: " + part.getFileName() + " : " + cType);
saveFile(part.getFileName(), part.getInputStream());
}
else {
System.out.println("Other: " + dposition);
}
}
public static void saveFile(String filename,InputStream input) throws IOException {
if (filename == null) {
filename = File.createTempFile("MailAttacheFile", ".out").getName();
}
System.out.println("downloading attachment...");
File file = new File(filename);
for (int i=0; file.exists(); i++) {
file = new File(filename+i);
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(input);
int fByte;
while ((fByte = bis.read()) != -1) {
bos.write(fByte);
}
bos.flush();
bos.close();
bis.close();
System.out.println("done attachment...");
}
}
Please I cannot understand your code
ReplyDeleteIf you have knowledge of Java in middle level?
ReplyDeleteThen you can only understand my code.
-Amit
hi Amit,
ReplyDeleteYou code is simply superb may i know after downloading where the email attachment files are stored.
Arun,
ReplyDeleteYou can find all the attachments in the current directory of your java file.
Please amit check on the line of the first for loop-not complete. Could you please send the full code on my email address?
ReplyDeleteAmit I'm making a project that should receive mail and save attachment-for users and am really stuck. Please help me
ReplyDeleteAmit
ReplyDeletei got the attachment thank you very much. But while reading the body of the content from mail i am getting HTML encoding characters and all can u tell me how to remove that.
Arun,
ReplyDeleteJust create a method. In that method you should write a code for remove HTML encoding character.
Kings,
ReplyDeleteJust copy and paste listed below article's code.
http://amitkgaur.blogspot.com/2011/03/read-gmail-email-and-save-attachement.html
Hi Amit,
ReplyDeleteI'm trying to not only save the attachments as files instead of saving the whole message as msg-file. I don't mean something like editing it and save it back one the mail-server with saveChanges() or something like that. What I mean is to write a new file .msg on my desktop for example.
I tryied using:
OutputStream out = new FileOutputStream(new File(strFilePath));
msg.writeTo(out);
...but this always causes an error when opening the file. I think the format is not set correctly while writing it but I don't really know a solution for this problem or if this really is the problem. Do you?
Mondlotus, your answer is here
ReplyDeleteApache POI http://poi.apache.org/
and
http://www.independentsoft.de/jmsg/index.html
hey can u tell me how to save the attachment in any folder in any location
ReplyDeletePritam deb, just use the full directory path as listed below:
DeletesaveFile("c:\\temp\\"+part.getFileName(), part.getInputStream());
Hey can you provide java code for creating labels and assign a particular label to that mail for gmail
ReplyDeleteNaresh,
ReplyDeleteyou can find more about java mail from
http://www.oracle.com/technetwork/java/javamail/index.html
im getting errors in your code with the integer i in your for loops some saying it doesnt exist and some saying cannot convert from boolean to int.
ReplyDeleteTest1, can you send me the code with your email and password?
Deletei am getting errors with the integer i used in the for loops it says cannot convert from boolean to integer.
ReplyDeletest1, can you send me the code with your email and password?
Deletethis code is very much error . . .
ReplyDeleteThough millions of people logging Gmail every day, but some may find the Gmail account tricky and tough to handle and at that moment they need Gmail tech support, so to use an error free Gmail account a user can contact on Gmail Support Number at any stretch of the day.
ReplyDeletehow to recover gmail deleted emails