How to read MS Outlook inbox mail using Java code?
10,865
This is how I have done.
/**
* Connects to email server with credentials provided to read from a given
* folder of the email application
*
* @param username Email username (e.g. [email protected])
* @param password Email password
* @param server Email server (e.g. smtp.email.com)
* @param INBOX Folder in email application to interact with
* @throws Exception
*/
public OutlookEmail() throws Exception {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imap.ssl.enable", "true");
props.setProperty("mail.imaps.partialfetch", "false");
props.put("mail.mime.base64.ignoreerrors", "true");
Session mailSession = Session.getInstance(props);
mailSession.setDebug(true);
Store store = mailSession.getStore("imap");
store.connect("outlook.office365.com", "YOUREMAILADDRESS", "YOUR PASSWORD");
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
System.out.println("Total Message:" + folder.getMessageCount());
System.out.println("Unread Message:" + folder.getUnreadMessageCount());
messages = folder.getMessages();
for (Message mail : messages) {
System.out.println("*********************************");
System.out.println("MESSAGE : \n");
System.out.println("Subject: " + mail.getSubject());
System.out.println("From: " + mail.getFrom()[0]);
System.out.println("To: " + mail.getAllRecipients()[0]);
System.out.println("Date: " + mail.getReceivedDate());
System.out.println("Size: " + mail.getSize());
System.out.println("Flags: " + mail.getFlags());
System.out.println("ContentType: " + mail.getContentType());
System.out.println("Body: \n" + getEmailBody(mail));
System.out.println("*******************************");
}
}
**Read from config and Pass credentials, uname, pwd as arguments and masked.
Author by
Admin
Updated on June 05, 2022Comments
-
Admin almost 2 years
I need to read the subject,message from the inbox of Outlook, using java code. Is any sample code/Idea for the same, please help to get the same.
I search with StackOverflow, it gives the code in C#.
Also i check with Javamail, But i didnt found anything about Outlook.