I'm currently using the following code to access my Outlook inbox.
public void readAllMsgsFromOutlook() throws FileNotFoundException, IOException, MessagingException
{
//String host = "smtp-mail.outlook.com";
String emailID = props.getEmail();
String password = props.getPassword();
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap-mail.outlook.com", emailID, password);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] msgs = inbox.getMessages();
System.out.println("Number of New Emails: " + msgs.length);
for (int msgCounter = 0; msgCounter < msgs.length; msgCounter++)
{
Message msg = msgs[msgCounter];
Address[] sender = msg.getFrom();
Multipart mp = (Multipart) msg.getContent(); // Throws null pointer exception
BodyPart bp = mp.getBodyPart(0);
Date sentdate = msg.getSentDate();
String subject = msg.getSubject();
String content = bp.getContent().toString();
System.out.println("SENDER: " + sender);
System.out.println("SENT DATE: " + sentdate.getDate());
System.out.println("SUBJECT: " + subject);
System.out.println("CONTENT: " + content);
}
} catch (Exception mex) {
// TODO Auto-generated catch block
mex.printStackTrace();
}
}
However I get a NullPointer exception using this code.
This is the result I get in console:
Number of New Emails: 2
java.lang.NullPointerException
at javax.mail.internet.ParameterList.set(ParameterList.java:561)
at com.sun.mail.imap.protocol.BODYSTRUCTURE.parseParameters(BODYSTRUCTURE.java:404)
at com.sun.mail.imap.protocol.BODYSTRUCTURE.<init>(BODYSTRUCTURE.java:224)
at com.sun.mail.imap.protocol.FetchResponse.parse(FetchResponse.java:158)
at com.sun.mail.imap.protocol.FetchResponse.<init>(FetchResponse.java:67)
at com.sun.mail.imap.protocol.IMAPResponse.readResponse(IMAPResponse.java:136)
at com.sun.mail.imap.protocol.IMAPProtocol.readResponse(IMAPProtocol.java:270)
at com.sun.mail.iap.Protocol.command(Protocol.java:313)
at com.sun.mail.imap.protocol.IMAPProtocol.fetch(IMAPProtocol.java:1529)
at com.sun.mail.imap.protocol.IMAPProtocol.fetch(IMAPProtocol.java:1521)
at com.sun.mail.imap.protocol.IMAPProtocol.fetchBodyStructure(IMAPProtocol.java:1221)
at com.sun.mail.imap.IMAPMessage.loadBODYSTRUCTURE(IMAPMessage.java:1307)
at com.sun.mail.imap.IMAPMessage.getDataHandler(IMAPMessage.java:623)
at javax.mail.internet.MimeMessage.getContent(MimeMessage.java:1454)
at JavaMailAPI.readAllMsgsFromOutlook(JavaMailAPI.java:65)
at Main.main(Main.java:163)
I'm not sure why I get NullPointer exception if there are two emails in my inbox..?