JavaMail - getMessageCount changes after opening imap folder? - java

I'm writing a program that connects to gmail and checks the number of messages in the inbox. If I call getMessageCount() on the unopened Folder, it returns 554, but after opening it, it returns 541. Why the difference?
By the way, I'm ultimately trying to check for deleted messages (that have not been expunged) and recover them if possible.
Edit: some example code:
Session session = Session.getDefaultInstance(System.getProperties());
Store store = session.getStore("imaps");
store.connect("imap.googlemail.com", 993, email, password);
Folder inbox = store.getFolder("INBOX");
System.out.println(inbox.getMessageCount());
inbox.open(Folder.READ_ONLY);
System.out.println(inbox.getMessageCount());
Edit: protocol trace:
(In the meantime I got some more emails so the numbers are different from above)
DEBUG: setDebug: JavaMail version 1.5.2
DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle]
DEBUG IMAPS: mail.imap.fetchsize: 16384
DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
DEBUG IMAPS: mail.imap.appendbuffersize: -1
DEBUG IMAPS: mail.imap.minidletime: 10
DEBUG IMAPS: trying to connect to host "imap.googlemail.com", port 993, isSSL true
* OK Gimap ready for requests from <ip> vt17mb17567619iec
A0 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH AUTH=XOAUTH2 AUTH=PLAIN AUTH=PLAIN-CLIENTTOKEN
A0 OK Thats all she wrote! vt17mb17567619iec
DEBUG IMAPS: AUTH: XOAUTH
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: AUTH: PLAIN
DEBUG IMAPS: AUTH: PLAIN-CLIENTTOKEN
DEBUG IMAPS: protocolConnect login, host=imap.googlemail.com, user=<email>, password=<non-null>
DEBUG IMAPS: AUTHENTICATE PLAIN command trace suppressed
DEBUG IMAPS: AUTHENTICATE PLAIN command result: A1 OK <email> authenticated (Success)
A2 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE ENABLE MOVE CONDSTORE ESEARCH UTF8=ACCEPT
A2 OK Success
A3 LIST "" INBOX
* LIST (\HasChildren) "/" "INBOX"
A3 OK Success
A4 STATUS INBOX (MESSAGES RECENT UNSEEN UIDNEXT UIDVALIDITY)
* STATUS "INBOX" (MESSAGES 585 RECENT 0 UIDNEXT 3389 UIDVALIDITY 2 UNSEEN 0)
A4 OK Success
585
DEBUG IMAPS: connection available -- size: 1
A5 EXAMINE INBOX
* FLAGS (\Answered \Flagged \Draft \Deleted \Seen $Phishing $Forwarded NonJunk $NotPhishing Junk)
* OK [PERMANENTFLAGS ()] Flags permitted.
* OK [UIDVALIDITY 2] UIDs valid.
* 548 EXISTS
* 0 RECENT
* OK [UIDNEXT 3389] Predicted next UID.
* OK [HIGHESTMODSEQ 687472]
A5 OK [READ-ONLY] INBOX selected. (Success)
548

Related

Cannot read emails office365 using javaMail & IMAPS

I'm facing an error using javaMail & IMAPS to read emails on email account of my company hosted in office 365.
I'm using this test class:
public class TestMail {
public static void main(String[] args) {
// TODO Auto-generated method stub
Properties props = System.getProperties();
props.put("mail.imaps.auth.plain.disable","true");
props.setProperty("mail.imaps.timeout", "100000");
props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.ssl.enable", "true");
try {
Session session = Session.getInstance(props, null);
session.setDebug(true);
Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, "my-name#mycompagny.com", "MY_PASSWORD");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
}
I'm getting the following error:
DEBUG: setDebug: JavaMail version 1.4.7
DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle]
DEBUG IMAPS: mail.imap.fetchsize: 16384
DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
DEBUG IMAPS: mail.imap.appendbuffersize: -1
DEBUG IMAPS: mail.imap.minidletime: 10
DEBUG IMAPS: disable AUTH=PLAIN
DEBUG IMAPS: trying to connect to host "outlook.office365.com", port 993, isSSL true
* OK The Microsoft Exchange IMAP4 service is ready. [UABSADIAUAAyADYANABDAEEAMAAwADAANAAuAEYAUgBBAFAAMgA2ADQALgBQAFIATwBEAC4ATwBVAFQATABPAE8ASwAuAEMATwBNAA==]
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
A0 OK CAPABILITY completed.
DEBUG IMAPS: AUTH: PLAIN
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: protocolConnect login, host=outlook.office365.com, user=my-name#mycompagny.com, password=<non-null>
DEBUG IMAPS: LOGIN command trace suppressed
DEBUG IMAPS: LOGIN command result: A1 NO LOGIN failed.
javax.mail.AuthenticationFailedException: LOGIN failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:661)
at javax.mail.Service.connect(Service.java:295)
at com.afklm.bagdss.task.TestMail.main(TestMail.java:25)

Sometimes login sometimes not to Exchange by JavaMail

I have problem with randomly login failed. By one hour is happening 2-4 times, and similar time, for example: about 14:26, 14:48, 15:26, 15:49, etc.
I use JavaMail(ver. 1.5.6) to email processing. Mailbox is Microsoft Exchange.
Application run every 5 minute to connect to mailbox.
Pseudocode for email processing:
estabilishConncetion()
prepareMailbox()
downloadEmails()
moveEmailsToSOmething()
closeConnection()
Code connection is like this:
public void establishConnection() throws ConnectionException {
logger.info("Establish connection... ");
props = new Properties();
props.setProperty("mail.imaps.ssl.enable", "true");
props.setProperty("mail.imaps.port", 993);
props.setProperty("mail.imaps.timeout", 60000);
props.setProperty("mail.imaps.connectiontimeout",60000 );
props.put("mail.imaps.auth.plain.disable", "true");
props.put("mail.imaps.auth.ntlm.disable", "true");
props.put("mail.imaps.auth.gssapi.disable", "true");
props.setProperty("mail.debug", "true"); // only for test
Session session = Session.getInstance(props, new Authenticator(){
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(somename, somepassword);
}
});
try {
store = session.getStore("imaps");
store.connect(EmailServerAddress, EmailAddress,Password);
} catch (MessagingException e) {
throw new ConnectionException(" Problem occured when try connect to host: " + ServerAddress + " on address: " +EmailAddress);
}
logger.info("Connected to mailbox.");
}
Logging when connected:
DEBUG IMAPS: trying to connect to host "somehost", port 993, isSSL true]]
* OK The Microsoft Exchange IMAP4 service is ready.]]
A0 CAPABILITY]]
* CAPABILITY IMAP4 IMAP4rev1 AUTH=NTLM AUTH=GSSAPI AUTH=PLAIN
STARTTLS UIDPLUS CHILDREN IDLE NAMESPACE LITERAL+]]
A0 OK CAPABILITY completed.]]
DEBUG IMAPS: protocolConnect login, host=somehost,
user=someuser, password=]]
DEBUG IMAPS: mechanism LOGIN not supported by server]] DEBUG IMAPS:
LOGIN command trace suppressed]] DEBUG IMAPS: LOGIN command result: A1
OK LOGIN completed.]]
A2 CAPABILITY]] * CAPABILITY IMAP4 IMAP4rev1 AUTH=NTLM AUTH=GSSAPI
AUTH=PLAIN STARTTLS UIDPLUS CHILDREN IDLE NAMESPACE LITERAL+]]
A2 OK CAPABILITY completed.]]
DEBUG IMAPS: AUTH: NTLM]] Connected to mailbox.]]
Logging when not connected:
DEBUG IMAPS: trying to connect to host "somehost", port 993, isSSL
true]]
* OK The Microsoft Exchange IMAP4 service is ready.]]
A0 CAPABILITY]]
* CAPABILITY IMAP4 IMAP4rev1 AUTH=NTLM AUTH=GSSAPI AUTH=PLAIN
STARTTLS UIDPLUS CHILDREN IDLE NAMESPACE LITERAL+]]
A0 OK CAPABILITY completed.]]
DEBUG IMAPS: protocolConnect login, host=somehost, user=someuser,
password=]]
DEBUG IMAPS: mechanism LOGIN not supported by server]] DEBUG
IMAPS: LOGIN command trace suppressed]] DEBUG IMAPS: LOGIN command
result: A1 NO LOGIN failed.]] //trying to login one more time with
failure
I checked this and its ok in my code:
1. Using JavaMail to connect to IMAP getting "A1 NO LOGIN failed" exception
2. https://javaee.github.io/javamail/FAQ#Exchange-login
3. I have unit test realted with connection and they always passed
Any sollution, clues, how to better debug this? :)

Imap search with messageid

I have a email processor java application which connects outlooks and lists folder messages and then if it decide it downloads email. I have the following problem with some emails.
Listing with following code:
Session session = Session.getInstance(props, new myAuthenticator());
store = session.getStore(PROTOCOL);
store.connect(HOST, USERNAME, PASSWORD);
inbox_unknown = store.getDefaultFolder().getFolder("INBOX_UNKNOWN");
inbox_unknown.open(Folder.READ_ONLY);
messages = inbox_unknown.getMessages();
for(Message m : messages){
Enumeration headers = m.getAllHeaders();
while(headers.hasMoreElements()){
Header element = (Header)headers.nextElement();
if ("Message-ID".equals(element.getName()))
System.err.println(element.getValue());
}
}
and the result is :
<CAFSBYLHvG9d=MkE2Gf+q_EgoaAN8yRVHHsg5emO0w92GV6-7LA#mail.gmail.com>
<CAFSBYLGs-w4=JrgrYh_6kpiEc9NhjCsc76gXVvLWyW-=QN+kMw#mail.gmail.com>
However When I search with these message id with following code :
messages = inbox_unknown.search(new MessageIDTerm("<CAFSBYLGs-w4=JrgrYh_6kpiEc9NhjCsc76gXVvLWyW-=QN+kMw#mail.gmail.com>"));//not found
messages = inbox_unknown.search(new MessageIDTerm("<CAFSBYLHvG9d=MkE2Gf+q_EgoaAN8yRVHHsg5emO0w92GV6-7LA#mail.gmail.com>"));//found
Although message with id <CAFSBYLHvG9d=MkE2Gf+q_EgoaAN8yRVHHsg5emO0w92GV6-7LA#mail.gmail.com> is listed, when i search this single item i get empty return array. For other message id it returns the message object as expected. Do you have any idea what can be the problem ?
PS:This mails from same person, and this is just for example, there are many similar mails which are not found although they can be listed.
Note: using java7, java.mail-1.4 api, ms outlook server,IMAP4 as protocol.
Note2: Added java debug output
DEBUG: setDebug: JavaMail version 1.5.5
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle]
DEBUG IMAP: mail.imap.fetchsize: 16384
DEBUG IMAP: mail.imap.ignorebodystructuresize: false
DEBUG IMAP: mail.imap.statuscachetimeout: 1000
DEBUG IMAP: mail.imap.appendbuffersize: -1
DEBUG IMAP: mail.imap.minidletime: 10
DEBUG IMAP: closeFoldersOnStoreFailure
DEBUG IMAP: trying to connect to host "outlook.abck.com.tr", port 143, isSSL false
* OK The Microsoft Exchange IMAP4 service is ready.
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=NTLM AUTH=GSSAPI AUTH=PLAIN UIDPLUS CHILDREN IDLE NAMESPACE LITERAL+
A0 OK CAPABILITY completed.
DEBUG IMAP: AUTH: NTLM
DEBUG IMAP: AUTH: GSSAPI
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: protocolConnect login, host=outlook.abck.com.tr, user=usera, password=<non-null>
DEBUG IMAP: AUTHENTICATE PLAIN command trace suppressed
DEBUG IMAP: AUTHENTICATE PLAIN command result: A1 OK AUTHENTICATE completed.
A2 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=NTLM AUTH=GSSAPI AUTH=PLAIN UIDPLUS CHILDREN IDLE NAMESPACE LITERAL+
A2 OK CAPABILITY completed.
DEBUG IMAP: AUTH: NTLM
DEBUG IMAP: AUTH: GSSAPI
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: connection available -- size: 1
A3 EXAMINE Test
* 2 EXISTS
* 2 RECENT
* FLAGS (\Seen \Answered \Flagged \Deleted \Draft $MDNSent)
* OK [PERMANENTFLAGS ()] Permanent flags
* OK [UIDVALIDITY 268114] UIDVALIDITY value
* OK [UIDNEXT 4] The next unique identifier value
A3 OK [READ-ONLY] EXAMINE completed.
A4 SEARCH HEADER Message-ID <CAFSBYLGs-w4=JrgrYh_6kpiEc9NhjCsc76gXVvLWyW-=QN+kMw#mail.gmail.com> ALL
* SEARCH
A4 OK SEARCH completed.
A5 SEARCH HEADER Message-ID <CAFSBYLHvG9d=MkE2Gf+q_EgoaAN8yRVHHsg5emO0w92GV6-7LA#mail.gmail.com> ALL
* SEARCH 2
A5 OK SEARCH completed.
A6 FETCH 1 (BODY.PEEK[HEADER])
* 1 FETCH (BODY[HEADER] {1403}
MIME-Version: 1.0
Received: from mail01.abck.com.tr (62.108.64.49) by
EXCPRDHCS02.abck.abc (10.81.42.19) with Microsoft SMTP Server
(TLS) id 14.3.195.1; Tue, 17 May 2016 14:31:39 +0300
Received: from mail-yw0-f170.google.com ([209.85.161.170]) by
mail01.abck.com.tr with ESMTP/TLS/AES128-GCM-SHA256; 17 May 2016
14:31:31 +0300
Received: by mail-yw0-f170.google.com with SMTP id x189so11988152ywe.3;
Tue, 17 May 2016 04:31:31 -0700 (PDT)
Received: by 10.37.14.212 with HTTP; Tue, 17 May 2016 04:31:30 -0700 (PDT)
Subject: =?utf-8?B?VEFMxLBNQVQ=?=
Thread-Topic: =?utf-8?B?VEFMxLBNQVQ=?=
Thread-Index: AQHRsC+uNbCd970/KU2ZmbAy2JPC2w==
Date: Tue, 17 May 2016 14:31:30 +0300
Message-ID:
<CAFSBYLGs-w4=JrgrYh_6kpiEc9NhjCsc76gXVvLWyW-=QN+kMw#mail.gmail.com>
Content-Language: en-US
X-MS-Exchange-Organization-AuthAs: Anonymous
X-MS-Exchange-Organization-AuthSource: EXCPRDHCS02.abck.abc
X-MS-Has-Attach: yes
X-MS-Exchange-Organization-SCL: 0
X-MS-TNEF-Correlator:
Content-Type: multipart/mixed;
boundary="_003_CAFSBYLGsw4JrgrYh6kpiEc9NhjCsc76gXVvLWyWQNkMwmailgmailc_"
)
A6 OK FETCH completed.
A7 FETCH 2 (BODY.PEEK[HEADER])
* 2 FETCH (BODY[HEADER] {4900}
MIME-Version: 1.0
Received: from mail01.abck.com.tr (62.108.64.49) by
EXCPRDHCS01.abck.abc (10.81.42.18) with Microsoft SMTP Server
(TLS) id 14.3.279.2; Wed, 25 May 2016 10:30:08 +0300
IronPort-PHdr: =?us-ascii?q?9a23=3AVhJs6B+zz3F7Iv9uRHKM819IXTAuvvDOBiVQ1KB7?=
=?us-ascii?q?0eIcTK2v8tzYMVDF4r011RmSDdSdt6gP0rCN+4nbGkU+or+5+EgYd5JNUxJXwe?=
=?us-ascii?q?43pCcHRPC/NEvgMfTxZDY7FskRHHVs/nW8LFQHUJ2mPw6anHS+4HYoFwnlMkIt?=
=?us-ascii?q?f6KuSt+U0578jrrps7ToICx2xxOFKYtoKxu3qQiD/uI3uqBFbpgL9x3Sv3FTcP?=
=?us-ascii?q?5Xz247bXianhL7+9vitMU7q3cYk7sb+sVBSaT3ebgjBfwdVWx+cjN92Mq+/zTH?=
=?us-ascii?q?TAXH3nYcVmQImxwAQy3I4xiydZr3ribg/tFg0iSBPIjVSro1ER6r6aRiQx7siS?=
=?us-ascii?q?gGdnRxpGzTi8I2lK9bpBO/rhpXzY/SaYeOPvN4feXWetZcWXAXGo4beiBISqqg?=
=?us-ascii?q?ZpBHT9EcN+sQl4DvrkEKpB63TSmtFubi1ndti2X10L87kq5pRQzK1UopA9sVmH?=
=?us-ascii?q?rVqtzzL60bV+Pzx67NiynZObcexT756Y3BbjgvoPeFW6l6eMzSj0IoEkXZlAa+?=
=?us-ascii?q?s4vgag248sVFnEW9QKI0Tv+jhmAqsQRsqyKHycIli42PjYUQnAOXvR5lyZo4cI?=
=?us-ascii?q?XrAHVwZsSpRd4J73mX?=
X-Cloudmark-SP-Filtered: true
X-Cloudmark-SP-Result: =?us-ascii?q?v=3D2=2E1_cv=3DF5f3DvVN_c=3D1_sm=3D1_tr?=
=?us-ascii?q?=3D0_a=3Dyrkiwgmsf1kA=3A10_a=3DxWK-KtZqUfIA=3A10?=
=?us-ascii?q?_a=3De186Yzns-9f1=5FKZu-cIA=3A9_a=3DQEXdDO2ut3YA=3A10_a=3DOKp-?=
=?us-ascii?q?Gz0vqPG3m8aTRrIA=3A9?=
=?us-ascii?q?_a=3DKQqxNPgzF0kA=3A10?=
X-IronPort-Anti-Spam-Filtered: true
X-IronPort-Anti-Spam-Result: =?us-ascii?q?A0HiAwB/U0VXf7OhVdFbhQoGpn6HY4NNg?=
=?us-ascii?q?xSCJYQTBCRxB4YkBzwQAQEBAQEBAQECDwEBCQsLCSEbFIIuCjkQVQIrTA0RHQE?=
=?us-ascii?q?bHgMSAwUBAgUSAQELGAIEFQEKAREBBQEREQEYHIdyAQMXlVGPQoExPjGKBoE1g?=
=?us-ascii?q?WqCWAWIKwoZJw1Sg1cMFwYCBhCSI4JZBY5VhwWCXYMrgWmJDIFTAY1Ijg0SHoE?=
=?us-ascii?q?PN4QbOTKKBwEBAQ?=
X-IPAS-Result: =?us-ascii?q?A0HiAwB/U0VXf7OhVdFbhQoGpn6HY4NNgxSCJYQTBCRxB4Y?=
=?us-ascii?q?kBzwQAQEBAQEBAQECDwEBCQsLCSEbFIIuCjkQVQIrTA0RHQEbHgMSAwUBAgUSA?=
=?us-ascii?q?QELGAIEFQEKAREBBQEREQEYHIdyAQMXlVGPQoExPjGKBoE1gWqCWAWIKwoZJw1?=
=?us-ascii?q?Sg1cMFwYCBhCSI4JZBY5VhwWCXYMrgWmJDIFTAY1Ijg0SHoEPN4QbOTKKBwEBA?=
=?us-ascii?q?Q?=
Received: from mail-yw0-f179.google.com ([209.85.161.179]) by
mail01.abck.com.tr with ESMTP/TLS/AES128-GCM-SHA256; 25 May 2016
10:29:57 +0300
Received: by mail-yw0-f179.google.com with SMTP id o16so39498708ywd.2;
Wed, 25 May 2016 00:29:57 -0700 (PDT)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=gmail.com; s=20120113;
h=mime-version:date:message-id:subject:from:to;
bh=w8xSZyobRcFMKx+IrtarhnHXAm9n7xJEYfaDMmptcKI=;
b=WN8u7uLAyNhcAoB+oQ5xbsKdpV4z4BGWD6CrryDyJqq7tosj82QH3d3MQWHaqf2mBa
AqlmCBq5w3ntokCoKrQlzdQNGecJ7AvIrc/CPFkYLeT3MK1kcY8gzDANJC/Pm5NO75td
S/mBW9goEL1gKFwpd/DahOzIwKbT5UEz9hthcTU5JIPwJR305/boxMIP3zcu1M+WPVPY
RhnojBbe41iCfqemB11IIvFeyRMqck6x7dDnWnejriEP2Gp8x4s2FYLz5rysEloNe0wU
qKmmNXtsIStwJhdk8jjByMW/UsK+94t3+jr+rzbTyYndh/Hs3SbZsmDQipBG8+SHxRQu
e/TQ==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=1e100.net; s=20130820;
h=x-gm-message-state:mime-version:date:message-id:subject:from:to;
bh=w8xSZyobRcFMKx+IrtarhnHXAm9n7xJEYfaDMmptcKI=;
b=iXyugXgd1ER8sfK9PJXcq88MO8z2/VKl31XNf/Bp2E1BvC42ZxLsAGjeHKL6KqqzFb
CNdHhBLnyfAnGoaa9pIK+qoC2HT69e323Rmym3w6HxQr1ot396xThXXxL22ZManrpICu
RAPegTlsmXQ1VBqhYQjgX8NwX6FtoqtzBW9tSOnl+HTfdyv3CNNf0mAysA7jyCHwQy6j
Nc+JK/uUZjccYkic672MiDSUa4FfwJSx0L3nyWI/CZMVDaNVW3mtp04cpgvtshLkloLn
61bz3dlGNL1g3gIVwNFiY8SLGxFdPzRc7xJ9VJEgXoA1h2OO2QVqyEUUyivhzehbgvL5
Bhtw==
X-Gm-Message-State: ALyK8tLPd9mwwszKuBwk9ndltkf3tyZ91virPLkoGP8PigQLffqE7vB7NVGiauqhPC9vcXsZnsU/mzB4zSTZbg==
X-Received: by 10.13.217.151 with SMTP id b145mr1363469ywe.53.1464161395972;
Wed, 25 May 2016 00:29:55 -0700 (PDT)
Received: by 10.37.14.212 with HTTP; Wed, 25 May 2016 00:29:55 -0700 (PDT)
Date: Wed, 25 May 2016 10:29:55 +0300
Message-ID: <CAFSBYLHvG9d=MkE2Gf+q_EgoaAN8yRVHHsg5emO0w92GV6-7LA#mail.gmail.com>
Subject: =?UTF-8?B?QsOcxZ5SQSBFVMSwIE1VU1RBRkEgRVTEsCBLSURFTSBUQVpNxLBOQVRJIMOWREVNRSBUQQ==?=
=?UTF-8?B?TMSwTUFUSQ==?=
Content-Type: multipart/mixed; boundary="001a114fa43ee6ce4a0533a5a3c5"
Return-Path: abc#gmail.com
X-MS-Exchange-Organization-AuthSource: EXCPRDHCS01.abck.abc
X-MS-Exchange-Organization-AuthAs: Anonymous
X-MS-Exchange-Organization-AVStamp-Mailbox: SMEXw]nP;1254500;0;This mail has
been scanned by Trend Micro ScanMail for Microsoft Exchange;
X-MS-Exchange-Organization-SCL: 0
X-PP-Proceessed: 162a0e36-1ac8-484f-b83f-d5c2dc8a3c0b
)
A7 OK FETCH completed.
A8 CLOSE
A8 OK CLOSE completed.
DEBUG IMAP: added an Authenticated connection -- size: 1
A9 LOGOUT
* BYE Microsoft Exchange Server 2010 IMAP4 server signing off.
A9 OK LOGOUT completed.
DEBUG IMAP: IMAPStore connection dead
DEBUG IMAP: IMAPStore cleanup, force false
DEBUG IMAP: IMAPStore cleanup done

How to receive email from hotmail via IMAP and OAuth?

I want to receive Email from Hotmail by IMAP, but I have to authenticate by OAuth. From the Microsoft documentation, it supports that, http://msdn.microsoft.com/en-us/library/dn440163.aspx;
But I have to idea how to use it in java (by Javamail). I tried to use google code sample (correct email and access_toket), but failed.
String email = "stony#hotmail.com";
String oauthToken = "XXXXXXXX";
initialize();
IMAPStore imapStore = connectToImap("imap-mail.outlook.com",
993,
email,
oauthToken,
true);
System.out.println("Successfully authenticated to IMAP.\n");
Folder folder = imapStore.getDefaultFolder();
folder.open(Folder.READ_ONLY); //****The linke throw exception****
for (Message msg : folder.getMessages()) {
String subject = msg.getSubject();
System.out.println(":" + subject);
}
The log printed on system console is,
DEBUG: setDebug: JavaMail version 1.4
DEBUG: mail.imap.fetchsize: 16384
DEBUG: enable SASL
DEBUG: SASL mechanisms allowed: XOAUTH2
* OK Outlook.com IMAP4rev1 server version 17.4.0.0 ready (DUB451-IMAP183)
A0 CAPABILITY
* CAPABILITY IMAP4rev1 CHILDREN ID NAMESPACE UIDPLUS UNSELECT AUTH=PLAIN AUTH=XOAUTH2 SASL-IR
A0 OK CAPABILITY completed
IMAP DEBUG: AUTH: PLAIN
IMAP DEBUG: AUTH: XOAUTH2
DEBUG: protocolConnect login, host=imap-mail.outlook.com, user=mebeautyful#hotmail.com, password=<non-null>
IMAP SASL DEBUG: Mechanisms: XOAUTH2
IMAP SASL DEBUG: SASL client XOAUTH2
A1 AUTHENTICATE XOAUTH2
+
IMAP SASL DEBUG: challenge: :
IMAP SASL DEBUG: callback length: 1
IMAP SASL DEBUG: callback 0: javax.security.auth.callback.NameCallback#61ead9ba
IMAP SASL DEBUG: response: user=mebeautyful#hotmail.comauth=Bearer
DEBUG: connection available -- size: 1
A2 EXAMINE ""
A1 NO [AUTHENTICATIONFAILED] OAuth authentication failed.
A2 BAD Examine Command is not permitted in current state (NotAuthenticated)
A3 LOGOUT
* BYE Logout requested
Exception in thread "main" javax.mail.MessagingException: A2 BAD Examine Command is not permitted in current state (NotAuthenticated);
nested exception is:
com.sun.mail.iap.BadCommandException: A2 BAD Examine Command is not permitted in current state (NotAuthenticated)
at com.sun.mail.imap.IMAPFolder.open(IMAPFolder.java:829)
at com.google.code.samples.oauth2.OAuth2Authenticator.main(OAuth2Authenticator.java:155)
Caused by: com.sun.mail.iap.BadCommandException: A2 BAD Examine Command is not permitted in current state (NotAuthenticated)
at com.sun.mail.iap.Protocol.handleResult(Protocol.java:296)
at com.sun.mail.imap.protocol.IMAPProtocol.examine(IMAPProtocol.java:636)
at com.sun.mail.imap.IMAPFolder.open(IMAPFolder.java:811)
... 1 more
I tested successfully! I verified 3 things,
We can use google code sample to collection to outlook's IMAP. The sample code link is https://code.google.com/p/google-mail-oauth2-tools/wiki/JavaSampleCode
Must use the scope wl.imap and wl.offline_access
In my hotmail acccount doesn't work, I can't even get a access_token; but after I use my another live account, it works.
You're using an older version of JavaMail. If you use the latest version, OAuth2 support is built in.

Invalid credentials (Failure) for oauth while using token generated through JAVA code

I am trying to use oauth to access my inbox, I always get invalid credential error when I use token generated using my JAVA code. I am using IMAP and passing oauth token to get authenticated. But when I generate token using python and use the same in my code, it works fine and fetch emails from my Inbox.
Here is the code snippet using IMAP:
public static IMAPSSLStore connectToImap(String host,
int port,
String userEmail,
String oauthToken,
String oauthTokenSecret,
OAuthConsumer consumer,
boolean debug) throws Exception {
Properties props = new Properties();
props.put("mail.imaps.sasl.enable", "true");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH");
props.put(XoauthSaslClientFactory.OAUTH_TOKEN_PROP,
oauthToken);
props.put(XoauthSaslClientFactory.OAUTH_TOKEN_SECRET_PROP,
oauthTokenSecret);
props.put(XoauthSaslClientFactory.CONSUMER_KEY_PROP,
consumer.consumerKey);
props.put(XoauthSaslClientFactory.CONSUMER_SECRET_PROP,
consumer.consumerSecret);
Session session = Session.getInstance(props);
session.setDebug(debug);
final URLName unusedUrlName = null;
IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
final String emptyPassword = "anonymous";
store.connect(host, port, userEmail, emptyPassword);
return store;
}
Here is the error log -
DEBUG: setDebug: JavaMail version 1.3.3
1
2
DEBUG: mail.imap.fetchsize: 16384
DEBUG: enable SASL
DEBUG: SASL mechanisms allowed: XOAUTH
3
4
* OK Gimap ready for requests from 122.179.85.133 kn10if6680532igc.14
A0 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH
A0 OK Thats all she wrote! kn10if6680532igc.14
IMAP DEBUG: AUTH: XOAUTH
DEBUG: protocolConnect login, host=imap.googlemail.com, user=me#mydomain.com, password=<non-null>
IMAP SASL DEBUG: Mechanisms: XOAUTH
IMAP SASL DEBUG: SASL client XOAUTH
A1 AUTHENTICATE XOAUTH
+
IMAP SASL DEBUG: challenge: :
IMAP SASL DEBUG: callback length: 1
IMAP SASL DEBUG: callback 0: javax.security.auth.callback.NameCallback#d1e832
IMAP SASL DEBUG: response: GET https://mail.google.com/mail/b/me#mydomain.com/imap/ oauth_signature_method="HMAC-SHA1",oauth_token="1%2Furn42qGc5mpD3BwVvJMzeVkHl_9iVRCZvaSOYmKNH5A",oauth_consumer_key="mydomain.com",oauth_timestamp="1329301212",oauth_nonce="629121335212995",oauth_version="1.0",oauth_signature="7O1YHXywiqOX8XzSAd%2BzbmDoBVw%3D" :
R0VUIGh0dHBzOi8vbWFpbC5nb29nbGUuY29tL21haWwvYi9wZXRlckBhMm9tb2JpbGUuY29tL2ltYXAvIG9hdXRoX3NpZ25hdHVyZV9tZXRob2Q9IkhNQUMtU0hBMSIsb2F1dGhfdG9rZW49IjElMkZ1cm40MnFHYzVtcEQzQndWdkpNemVWa0hsXzlpVlJDWnZhU09ZbUtOSDVBIixvYXV0aF9jb25zdW1lcl9rZXk9ImEyb21vYmlsZS5jb20iLG9hdXRoX3RpbWVzdGFtcD0iMTMyOTMwMTIxMiIsb2F1dGhfbm9uY2U9IjYyOTEyMTMzNTIxMjk5NSIsb2F1dGhfdmVyc2lvbj0iMS4wIixvYXV0aF9zaWduYXR1cmU9IjdPMVlIWHl3aXFPWDhYelNBZCUyQnpibURvQlZ3JTNEIg==
5
DEBUG: connection available -- size: 1
A2 EXAMINE INBOX
A1 NO [ALERT] Invalid credentials (Failure)
A2 BAD Unknown command r5if6689112igo.50
A3 LOGOUT
* BYE Logout Requested r5if6689112igo.50
A3 OK Quoth the raven, nevermore... r5if6689112igo.50
Exception in thread "main" javax.mail.MessagingException: A2 BAD Unknown command r5if6689112igo.50;
nested exception is:
com.sun.mail.iap.BadCommandException: A2 BAD Unknown command r5if6689112igo.50
at com.sun.mail.imap.IMAPFolder.open(IMAPFolder.java:820)
at com.a2o.service.collaboration.common.XoauthAuthenticator.getMessages(XoauthAuthenticator.java:238)
at com.a2o.service.collaboration.common.XoauthAuthenticator.main(XoauthAuthenticator.java:205)
Is there any way to generate token properly from JAVA code. My actual requirement is to generate token using my iPad client and fetch emails using that token in my server. Any help is highly appriciated.
we have used http://pastebin.com/kwcZQcvj to create token and secret.

Categories