How to set timeout for IMAPFolder.idle - selenium-webdriver

I'm implementing Webdriver test with java including checking email from Gmail. My code is here:
public static void checkNewEmail(String user, String password, String sender, String subject, ArrayList<String> errorList) throws MessagingException {
boolean result = false;
Store store = null;
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
props.setProperty("mail.imaps.ssl.enable", "true");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.timeout", "10000");
props.setProperty("mail.imaps.connectiontimeout", "10000");
try {
Session session = Session.getInstance(props, null);
store = session.getStore();
store.connect("imap.gmail.com", user, password);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
//add listener
System.out.println("Listening for New message");
final Message[] email = new Message[1];
inbox.addMessageCountListener(new MessageCountAdapter() {
#Override
public void messagesAdded(MessageCountEvent ev) {
Message[] messages = ev.getMessages();
for (Message msg : messages) {
//process emails here
System.out.println("New message");
email[0] = msg;
}
}
});
((IMAPFolder) inbox).idle(true);
if(email[0] != null) {
if (email[0].getFrom()[0].toString().contains(sender) && email[0].getSubject().contains(subject)) {
gm.printSuccessMsg("===PASSED: Correct email arrived.");
result = true;
} else {
System.out.println("Incorrect email arrived.");
System.out.println(email[0].getFrom()[0].toString());
System.out.println(email[0].getSubject());
if (store != null) {
store.close();
}
checkNewEmail(user, password, sender, subject, errorList);
}
}
} catch (FolderClosedException e) {
e.printStackTrace();
if (store != null) {
store.close();
}
} finally {
if(!result)
errorList.add("Store email");
if (store != null) {
store.close();
System.out.println("Done");
}
}
}
}
Debug output:
DEBUG: setDebug: JavaMail version 1.6.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: closeFoldersOnStoreFailure
DEBUG IMAPS: trying to connect to host "imap.gmail.com", port 993, isSSL true
* OK Gimap ready for requests from 103.248.166.14 y22mb380918775jaq
A0 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH2 AUTH=PLAIN AUTH=PLAIN-CLIENTTOKEN AUTH=OAUTHBEARER AUTH=XOAUTH
A0 OK Thats all she wrote! y22mb380918775jaq
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: AUTH: PLAIN
DEBUG IMAPS: AUTH: PLAIN-CLIENTTOKEN
DEBUG IMAPS: AUTH: OAUTHBEARER
DEBUG IMAPS: AUTH: XOAUTH
DEBUG IMAPS: protocolConnect login, host=imap.gmail.com, user=nobia.bada.sigdal#gmail.com, password=<non-null>
DEBUG IMAPS: AUTHENTICATE PLAIN command trace suppressed
DEBUG IMAPS: AUTHENTICATE PLAIN command result: A1 OK nobia.bada.sigdal#gmail.com authenticated (Success)
A2 ENABLE UTF8=ACCEPT
* ENABLED UTF8=ACCEPT
A2 OK Success
DEBUG IMAPS: connection available -- size: 1
A3 EXAMINE INBOX
* FLAGS (\Answered \Flagged \Draft \Deleted \Seen $NotPhishing $Phishing)
* OK [PERMANENTFLAGS ()] Flags permitted.
* OK [UIDVALIDITY 1] UIDs valid.
* 618 EXISTS
* 0 RECENT
* OK [UIDNEXT 817] Predicted next UID.
* OK [HIGHESTMODSEQ 69350]
A3 OK [READ-ONLY] INBOX selected. (Success)
Listening for New message
A4 IDLE
+ idling
DEBUG IMAP: startIdle: set to IDLE
DEBUG IMAP: startIdle: return true
DEBUG IMAP: handleIdle: ignoring socket timeout
DEBUG IMAP: handleIdle: ignoring socket timeout
DEBUG IMAP: handleIdle: ignoring socket timeout
DEBUG IMAP: handleIdle: ignoring socket timeout
DEBUG IMAP: handleIdle: ignoring socket timeout
DEBUG IMAP: handleIdle: ignoring socket timeout
DEBUG IMAP: handleIdle: ignoring socket timeout
DEBUG IMAP: handleIdle: ignoring socket timeout
DEBUG IMAP: handleIdle: ignoring socket timeout
DEBUG IMAP: handleIdle: ignoring socket timeout
DEBUG IMAP: handleIdle: ignoring socket timeout
DEBUG IMAP: handleIdle: ignoring socket timeout
DEBUG IMAP: handleIdle: ignoring socket timeout
....
When there is a correct email arriving, it can check and terminate the listener properly. But when there is no incoming email, it keeps waiting forever, and the timeout does not seem to work and it's hanging in DEBUG IMAP: handleIdle: ignoring socket timeout. Is anyone having the same issue ? I've tried changing from "setProperty" to "put" (using int instead of string) but it's still the same.

From the IMAPFolder source:
/*
* If it was a timeout and no bytes were transferred
* we ignore it and go back and read again.
* If the I/O was otherwise interrupted, and no
* bytes were transferred, we take it as a request
* to abort the IDLE.
*/
So setting the timeout doesn't cause IDLE to abort. If you want IDLE to abort create another thread to wait for a deadline and call close when the deadline has expired.

Related

HTTP4 component is ignoring my protocol, hostname and port numbber

I am trying to call an https service. The URL is
https4://httpbin.org/get?connectTimeout=800
but it is trying to connect to
http://localhost:8080/api/v1/raw?connectTimeout=800
restConfiguration()
.component("restlet").port(8080)
.bindingMode(RestBindingMode.off)
.apiContextPath("api-doc")
.apiProperty("api.title", "Unified Item API")
.apiProperty("api.version", "v1");
rest().path("/api/v1/raw")
.get().to("direct:agg");
from("direct:agg")
.validate(authorizationPredicate)
.to("https4://httpbin.org/get?connectTimeout=800");
This is the relevant portion of the log:
12:56:12.522 [Restlet-1916062307] DEBUG o.a.camel.processor.SendProcessor - >>>> direct://agg Exchange[ID-C02VNC5EHTD5MBP-1569603368539-0-2]
12:56:12.736 [Restlet-1916062307] DEBUG o.a.c.p.v.PredicateValidatingProcessor - Validation succeed for Exchange[ID-C02VNC5EHTD5MBP-1569603368539-0-2] with Predicate[com.homedepot.merch.unifiedItemApi.predicates.AuthorizationPredicate#198c8572]
12:56:12.737 [Restlet-1916062307] DEBUG o.a.camel.processor.SendProcessor - >>>> https4://httpbin.org/get?connectTimeout=800 Exchange[ID-C02VNC5EHTD5MBP-1569603368539-0-2]
12:56:12.747 [Restlet-1916062307] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean 'org.apache.camel.component.jackson.converter.JacksonTypeConverters'
12:56:12.757 [Restlet-1916062307] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'org.apache.camel.component.jackson.converter.JacksonTypeConverters'
12:56:12.759 [Restlet-1916062307] DEBUG o.a.c.component.http4.HttpProducer - Executing http GET method: http://localhost:8080/api/v1/raw?connectTimeout=800
12:56:12.773 [Restlet-1916062307] DEBUG o.a.h.c.protocol.RequestAddCookies - CookieSpec selected: default
12:56:12.780 [Restlet-1916062307] DEBUG o.a.h.c.protocol.RequestAuthCache - Auth cache not set in the context
12:56:12.781 [Restlet-1916062307] DEBUG o.a.h.i.c.BasicHttpClientConnectionManager - Get connection for route {}->http://localhost:8080
12:56:12.790 [Restlet-1916062307] DEBUG o.a.h.i.c.DefaultManagedHttpClientConnection - http-outgoing-0: set socket timeout to 0
12:56:12.791 [Restlet-1916062307] DEBUG o.a.h.impl.execchain.MainClientExec - Opening connection {}->http://localhost:8080
12:56:12.792 [Restlet-1916062307] DEBUG o.a.h.i.c.DefaultManagedHttpClientConnection - http-outgoing-0: Shutdown connection
12:56:12.792 [Restlet-1916062307] DEBUG o.a.h.impl.execchain.MainClientExec - Connection discarded
12:56:12.792 [Restlet-1916062307] DEBUG o.a.h.i.c.BasicHttpClientConnectionManager - Releasing connection [Not bound]
12:56:12.793 [Restlet-1916062307] INFO o.a.http.impl.execchain.RetryExec - I/O exception (org.apache.http.conn.UnsupportedSchemeException) caught when processing request to {}->http://localhost:8080: http protocol is not supported
12:56:12.794 [Restlet-1916062307] DEBUG o.a.http.impl.execchain.RetryExec - http protocol is not supported
org.apache.http.conn.UnsupportedSchemeException: http protocol is not supported
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:109)
at org.apache.http.impl.conn.BasicHttpClientConnectionManager.connect(BasicHttpClientConnectionManager.java:325)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:381)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at org.apache.camel.component.http4.HttpProducer.executeMethod(HttpProducer.java:334)
It turns out that the REST consumer sets the header Exchange.HTTP_URI to the URL it received. The HTTP4 producer uses this header to override what is in the URL it is given. The solution was to remove the header like this:
from("direct:agg")
.validate(authorizationPredicate)
.removeHeader("Exchange.HTTP_URI")

Apache Camel Mail component receiver example not working

I am trying to write apache Camel Mail component receiver using spring boot. Here is the code that I have written :
#Component
public class MyEmailRouter extends RouteBuilder {
#Override
public void configure() throws Exception {
from("imaps://imap.gmail.com?username=XXX&password=XXX&consumer.delay=60000&delete=false&unseen=true&debugMode=false&searchTerm.fromSentDate=now-24h&searchTerm.unseen=true")
.to("log:newmail");
}
}
I am trying to fetch all unseen emails from last 24 hours. However, this is not logging anything.
When I add debugMode=true in the url, I get following logs:
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: closeFoldersOnStoreFailure
DEBUG IMAPS: trying to connect to host "imap.gmail.com", port 993, isSSL true
* OK Gimap ready for requests from 111.122.212.118 b2mb183242253ioa
A0 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH2 AUTH=PLAIN AUTH=PLAIN-CLIENTTOKEN AUTH=OAUTHBEARER AUTH=XOAUTH
A0 OK Thats all she wrote! b2mb183242253io
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: AUTH: PLAIN
DEBUG IMAPS: AUTH: PLAIN-CLIENTTOKEN
DEBUG IMAPS: AUTH: OAUTHBEARER
DEBUG IMAPS: AUTH: XOAUTH
DEBUG IMAPS: protocolConnect login, host=imap.gmail.com, user=<non-null>, password=<non-null>
DEBUG IMAPS: AUTHENTICATE PLAIN command trace suppressed
DEBUG IMAPS: AUTHENTICATE PLAIN command result: A1 OK USERNAME authenticated (Success)
A2 ENABLE UTF8=ACCEPT
* ENABLED UTF8=ACCEPT
A2 OK Success
A3 LIST "" INBOX
* LIST (\HasNoChildren) "/" "INBOX"
A3 OK Success
DEBUG IMAPS: connection available -- size: 1
A4 SELECT INBOX
* FLAGS (\Answered \Flagged \Draft \Deleted \Seen $NotPhishing $Phishing)
* OK [PERMANENTFLAGS (\Answered \Flagged \Draft \Deleted \Seen $NotPhishing $Phishing \*)] Flags permitted.
* OK [UIDVALIDITY 1] UIDs valid.
* 2804 EXISTS
* 0 RECENT
* OK [UIDNEXT 2811] Predicted next UID.
* OK [HIGHESTMODSEQ 310772]
A4 OK [READ-WRITE] INBOX selected. (Success)
A5 FETCH 1 (FLAGS)
* 1 FETCH (FLAGS ())
A5 OK Success
A6 FETCH 1 (ENVELOPE INTERNALDATE RFC822.SIZE)
2019-05-01 11:20:56.451 INFO 3100 --- [ Thread-2] o.a.camel.spring.SpringCamelContext : Apache Camel 2.23.2 (CamelContext: MyCamel) is shutting down
2019-05-01 11:20:56.452 INFO 3100 --- [ Thread-2] o.a.camel.impl.DefaultShutdownStrategy : Starting to graceful shutdown 1 routes (timeout 300 seconds)
2019-05-01 11:20:56.455 INFO 3100 --- [ - ShutdownTask] o.a.camel.impl.DefaultShutdownStrategy : Waiting as there are still 1 inflight and pending exchanges to complete, timeout in 300 seconds. Inflights per route: [route1 = 1]
* 1 FETCH (RFC822.SIZE 4844 INTERNALDATE "31-Oct-2017 12:57:31 +0000" ENVELOPE ("Tue, 31 Oct 2017 05:57:31 -0700" "The best of Gmail, wherever you are" (("Gmail Team" NIL "mail-noreply" "google.com")) (("Gmail Team" NIL "mail-noreply" "google.com")) (("Gmail Team" NIL "mail-noreply" "google.com")) (("Aks" NIL "aks" "xyz.com")) NIL NIL NIL "<CAEDUrjNBDqUCUMGHVZ2x=gZ0Se5=e2jjp8hpkBECdDwqt_rfmw#mail.gmail.com>"))
A6 OK Success
A7 FETCH 2 (FLAGS)
* 2 FETCH (FLAGS ())

GreenMail integration test sent email not being relayed to recipient

I'm using greenmail for mail integration test, and came out with below code. The intention is to create 2 fake email servers that act as sender and recipient.
However when I ran the code, the test failed because the recipient doesn't receive the email. I've read some sample and faq from 'greenmail' site but can't find the explainations for this behavior. I hope someone could shed some light here.
Below is the test code:
#Before
public void setUp() {
// Setup fake smtp server.
ServerSetup smtpServer = new ServerSetup(Integer.parseInt(smtpPort), smtpHost, smtpProtocol);
serverA = new GreenMail(smtpServer);
serverA.start();
// Setup fake pop3 server.
ServerSetup pop3Server = new ServerSetup(Integer.parseInt(pop3Port), pop3Host, pop3Protocol);
serverB = new GreenMail(pop3Server);
serverB.start();
}
#Test
public void testSendEmailToAvailableMailboxReturnEmail() {
String senderMail = "sender.1#testmail.com";
String senderUsername = "sender1";
String senderPassword = "password123";
String receiverMail = "receiver.1#testmail.com";
String receiverUsername = "receiver1";
String receiverPassword = "pass567";
// Set mailbox for sender and receiver
serverA.setUser(senderMail, senderUsername, senderPassword);
serverB.setUser(receiverMail, receiverUsername, receiverPassword);
// Send email from serverA
String subject = "This is a test subject.";
String msg = "This is a plain test message.";
EmailModel emailModel = new EmailModel();
emailModel.setFrom(senderMail);
emailModel.setTo(receiverMail);
emailModel.setSubject(subject);
emailModel.setBody(msg);
emailModel.setSentDate(LocalDateTime.now());
emailModel.setBodyType(EmailModel.EMAIL_TYPE_TEXT);
// Using javamailsenderimpl to send the mail.
mailServiceImpl.send(emailModel);
// Retrieve email from ServerB
Session session = Session.getDefaultInstance(new Properties(), null);
try {
Store store = session.getStore(pop3Protocol);
store.connect(pop3Host, receiverUsername, receiverPassword);
Folder inbox = store.getFolder(BatchConstant.MAIL_INBOX);
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
Assert.assertNotNull(messages);
Assert.assertEquals(1, messages.length);
Assert.assertEquals(subject, messages[0].getSubject());
Assert.assertEquals(msg, String.valueOf(messages[0].getContent()).contains(msg));
} catch (MessagingException | IOException e) {
Assert.fail("Should be able to retrive sent mail.");
}
}
#After
public void tearDown() {
serverA.stop();
serverB.stop();
}
It fails at this line:
Assert.assertEquals(1, messages.length);
The log:
23:42:57.998 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.boot.test.mock.mockito.MockitoBeans'
23:42:58.014 [main] DEBUG com.icegreen.greenmail.util.GreenMail - Started services, performing check if all up
23:42:58.014 [smtp:127.111.44.233:25] DEBUG com.icegreen.greenmail.smtp.SmtpServer - Started smtp:127.111.44.233:25
23:42:58.029 [main] DEBUG com.icegreen.greenmail.util.GreenMail - Started services, performing check if all up
23:42:58.029 [pop3:127.124.244.10:110] DEBUG com.icegreen.greenmail.pop3.Pop3Server - Started pop3:127.124.244.10:110
23:42:58.061 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'getJavaMailSender'
DEBUG: JavaMail version 1.5.6
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "127.111.44.233", port 25, isSSL false
23:42:58.170 [smtp:127.111.44.233:25] DEBUG com.icegreen.greenmail.smtp.SmtpServer - Handling new client connection smtp:127.111.44.233:25<-/127.0.0.1:55846
220 /127.111.44.233 GreenMail SMTP Service v1.5.7 ready
DEBUG SMTP: connected to host "127.111.44.233", port: 25
EHLO MXXXXXXXXX
250 /127.111.44.233
DEBUG SMTP: use8bit false
MAIL FROM:<sender.1#testmail.com>
250 OK
RCPT TO:<receiver.1#testmail.com>
250 OK
DEBUG SMTP: Verified Addresses
DEBUG SMTP: receiver.1#testmail.com
DATA
354 Start mail input; end with <CRLF>.<CRLF>
Date: Tue, 12 Jun 2018 23:42:58 +0800 (SGT)
From: sender.1#testmail.com
To: receiver.1#testmail.com
Message-ID: <2074658615.2.1528818178201#MXXXXXXXXX>
Subject: This is a test subject.
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="----=_Part_0_52514534.1528818178108"
------=_Part_0_52514534.1528818178108
Content-Type: multipart/related;
boundary="----=_Part_1_1046665075.1528818178123"
------=_Part_1_1046665075.1528818178123
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 7bit
This is a plain test message.
------=_Part_1_1046665075.1528818178123--
------=_Part_0_52514534.1528818178108--
.
23:42:58.217 [smtp:127.111.44.233:25<-/127.0.0.1:55846] INFO com.icegreen.greenmail.smtp.SmtpManager - Created user login receiver.1#testmail.com for address receiver.1#testmail.com with password receiver.1#testmail.com because it didn't exist before.
250 OK
DEBUG SMTP: message successfully delivered to mail server
QUIT
221 /127.111.44.233 Service closing transmission channel
23:42:58.264 [pop3:127.124.244.10:110] DEBUG com.icegreen.greenmail.pop3.Pop3Server - Handling new client connection pop3:127.124.244.10:110<-/127.0.0.1:55847
23:42:58.264 [pop3:127.124.244.10:110<-/127.0.0.1:55847] DEBUG com.icegreen.greenmail.pop3.Pop3Connection - S: +OK POP3 GreenMail Server v1.5.7 ready
23:42:58.279 [pop3:127.124.244.10:110<-/127.0.0.1:55847] DEBUG com.icegreen.greenmail.pop3.Pop3Connection - C: CAPA
23:42:58.279 [pop3:127.124.244.10:110<-/127.0.0.1:55847] DEBUG com.icegreen.greenmail.pop3.Pop3Connection - S: +OK
23:42:58.279 [pop3:127.124.244.10:110<-/127.0.0.1:55847] DEBUG com.icegreen.greenmail.pop3.Pop3Connection - S: UIDL
23:42:58.279 [pop3:127.124.244.10:110<-/127.0.0.1:55847] DEBUG com.icegreen.greenmail.pop3.Pop3Connection - S: .
23:42:58.279 [pop3:127.124.244.10:110<-/127.0.0.1:55847] DEBUG com.icegreen.greenmail.pop3.Pop3Connection - C: USER receiver1
23:42:58.279 [pop3:127.124.244.10:110<-/127.0.0.1:55847] DEBUG com.icegreen.greenmail.pop3.Pop3Connection - S: +OK
23:42:58.279 [pop3:127.124.244.10:110<-/127.0.0.1:55847] DEBUG com.icegreen.greenmail.pop3.Pop3Connection - C: PASS pass567
23:42:58.279 [pop3:127.124.244.10:110<-/127.0.0.1:55847] DEBUG com.icegreen.greenmail.pop3.Pop3Connection - S: +OK
23:42:58.279 [pop3:127.124.244.10:110<-/127.0.0.1:55847] DEBUG com.icegreen.greenmail.pop3.Pop3Connection - C: STAT
23:42:58.279 [pop3:127.124.244.10:110<-/127.0.0.1:55847] DEBUG com.icegreen.greenmail.pop3.Pop3Connection - S: +OK 0 0
23:42:58.279 [pop3:127.124.244.10:110<-/127.0.0.1:55847] DEBUG com.icegreen.greenmail.pop3.Pop3Connection - C: NOOP
23:42:58.279 [pop3:127.124.244.10:110<-/127.0.0.1:55847] DEBUG com.icegreen.greenmail.pop3.Pop3Connection - S: +OK noop rimes with poop
23:42:58.279 [main] DEBUG com.icegreen.greenmail.util.GreenMail - Stopping GreenMail ...
23:42:58.279 [main] DEBUG com.icegreen.greenmail.util.GreenMail - Stopping service smtp:127.111.44.233:25
23:42:58.295 [main] DEBUG com.icegreen.greenmail.smtp.SmtpServer - Stopping smtp:127.111.44.233:25
23:42:58.295 [main] DEBUG com.icegreen.greenmail.smtp.SmtpServer - Stopped smtp:127.111.44.233:25
23:42:58.295 [main] DEBUG com.icegreen.greenmail.util.GreenMail - Stopping GreenMail ...
23:42:58.295 [main] DEBUG com.icegreen.greenmail.util.GreenMail - Stopping service pop3:127.124.244.10:110
23:42:58.295 [main] DEBUG com.icegreen.greenmail.pop3.Pop3Server - Stopping pop3:127.124.244.10:110
23:42:58.295 [main] DEBUG com.icegreen.greenmail.pop3.Pop3Server - Stopped pop3:127.124.244.10:110
23:42:58.295 [main] DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate - Retrieved ApplicationContext from cache with key [[MergedContextConfiguration#4e7dc304 testClass = MailServiceImplTest, locations = '{}', classes = '{class com.xxx.xoxoxo.mail.service.impl.MailServiceImpl, class com.xxx.xoxoxo.config.MailServiceConfig, class com.xxx.xoxoxo.batch.encryption.AesEncryptor, class com.xxx.xoxoxo.config.ApplicationProperties}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{enote.mail.host=127.111.44.233, enote.mail.port=25, enote.mail.protocol=smtp, enote.mail.encoding=UTF-8, enote.mail.auth=false, enote.mail.username=, enote.mail.password=}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#59f99ea, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#47c62251, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#589838eb], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
23:42:58.295 [main] DEBUG org.springframework.test.context.cache - Spring test ApplicationContext cache statistics: [DefaultContextCache#645aa696 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 2, missCount = 1]
GreenMail is a sandbox server. It will never route mail to another server.
What you want to do is create a single instance of GreenMail,
configured for both SMTP and POP3:
ServerSetup smtpServerSetup = ...
ServerSetup pop3ServerSetup = ...
GreenMail greenMail = new GreenMail(new ServerSetup[]{smtpServerSetup, pop3ServerSetup});
greenMail.start(); // Starts both smtp and pop3

Java Mail Api, delete mails from gmail

For testing reasons, I want an email account to be empty every day, I have this code but isn't deleting the emails.
public class EmailService {
private String HOST = "imap.gmail.com";
private String USERNAME = "mail#gmail.com";
private String PASSWORD = "pass";
private Properties properties;
private Store store;
private Folder inbox;
public EmailService() throws MessagingException {
this.properties = new Properties();
this.properties.put("mail.imap.host", HOST);
this.properties.put("mail.imap.port", "993");
this.properties.put("mail.imap.starttls.enable", "true");
}
public void openEmailSession() throws MessagingException, InterruptedException {
Session emailSession = Session.getInstance(this.properties);
emailSession.setDebug(true);
this.store = emailSession.getStore("imaps");
this.store.connect(HOST, USERNAME, PASSWORD);
this.inbox = this.store.getFolder("INBOX");
this.inbox.open(Folder.READ_WRITE);
}
public void closeEmailSession() throws MessagingException, IOException {
this.inbox.close(true);
this.store.close();
}
public Message[] getUserMessages() throws MessagingException, IOException {
Message[] messages = this.inbox.getMessages();
return messages;
}
public void cleanInbox() throws IOException, MessagingException {
Message[] messages = this.getUserMessages();
for (Message message :messages) {
message.setFlag(Flags.Flag.DELETED, true);
}
}
}
When I execute:
emailService.openEmailSession();
emailService.cleanInbox();
emailService.closeEmailSession();
The emails disappear from inbox, but then I click on All Mail and the emails still there and the trash is empty. I don't understand what is happening.
On the gmail settings in "Forwarding and POP/IMAP" I already tried autoexpunge on/off and the three options in "When a message is marked as deleted and expunged from the last visible IMAP folder"
But nothing changes... What I'm missing?
Edit: Debug output for [Gmail]/All mail
DEBUG: setDebug: JavaMail version 1.5.6
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.gmail.com", port 993, isSSL true
* OK Gimap ready for requests from 46.25.184.193 f20mb151859057edc
A0 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH2 AUTH=PLAIN AUTH=PLAIN-CLIENTTOKEN AUTH=OAUTHBEARER AUTH=XOAUTH
A0 OK Thats all she wrote! f20mb151859057edc
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: AUTH: PLAIN
DEBUG IMAPS: AUTH: PLAIN-CLIENTTOKEN
DEBUG IMAPS: AUTH: OAUTHBEARER
DEBUG IMAPS: AUTH: XOAUTH
DEBUG IMAPS: protocolConnect login, host=imap.gmail.com, user=mail#gmail.com, password=<non-null>
DEBUG IMAPS: AUTHENTICATE PLAIN command trace suppressed
DEBUG IMAPS: AUTHENTICATE PLAIN command result: A1 OK mail#gmail.com 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 LIST-EXTENDED LIST-STATUS LITERAL- APPENDLIMIT=35651584
A2 OK Success
DEBUG IMAPS: connection available -- size: 1
A3 SELECT "[Gmail]/All Mail"
* FLAGS (\Answered \Flagged \Draft \Deleted \Seen $NotPhishing $Phishing)
* OK [PERMANENTFLAGS (\Answered \Flagged \Draft \Deleted \Seen $NotPhishing $Phishing \*)] Flags permitted.
* OK [UIDVALIDITY 11] UIDs valid.
* 10 EXISTS
* 0 RECENT
* OK [UIDNEXT 3903] Predicted next UID.
* OK [HIGHESTMODSEQ 101809]
A3 OK [READ-WRITE] [Gmail]/All Mail selected. (Success)
A4 STORE 1 +FLAGS (\Deleted)
* 1 FETCH (FLAGS (\Seen \Deleted))
A4 OK Success
A5 STORE 2 +FLAGS (\Deleted)
* 2 FETCH (FLAGS (\Deleted))
A5 OK Success
A6 STORE 3 +FLAGS (\Deleted)
* 3 FETCH (FLAGS (\Seen \Deleted))
A6 OK Success
A13 OK Success
A14 CLOSE
A14 OK Returned to authenticated state. (Success)
DEBUG IMAPS: added an Authenticated connection -- size: 1
A15 LOGOUT
* BYE LOGOUT Requested
A15 OK 73 good day (Success)
DEBUG IMAPS: IMAPStore connection dead
DEBUG IMAPS: IMAPStore cleanup, force false
DEBUG IMAPS: IMAPStore cleanup done
You have to first copy the message to the folder [Gmail]/Trash, which will cause it to be immediately expunged from the current folder. Then you have to open [Gmail]/Trash and delete the message. That will make the message go away for good.
I added this information to the JavaMail FAQ.
I found an alternative solution, is not the best for my purpose (jenkins integration) but it works for now.
Is a really simple function in google script, you can select your email and schedule the function as you want.
https://www.google.com/script/start/
function cleanInbox() {
var threads = GmailApp.search('label:inbox');
for (var i = 0; i < threads.length; i++) {
threads[i].moveToTrash();
}
}

FloderClosedException while retrieving from dummy green mail imap server

I have created a dummy green mail server to simulate a mailbox for my application.
My application basically connects to a mail server and retrieves new mails based on some criteria. So i have created a dummy mail server for my application using green mail.
Now when I start my green mail and afterwards when try to connect to the mailbox created by green mail by my original application(application under test) then the application is able to connect to it and able to read list of new mails from the green mail server but when i try to read parameters of the fetched then it says-:
javax.mail.FolderClosedException: * BYE JavaMail Exception: java.io.IOException: Connection dropped by server?
at com.sun.mail.imap.IMAPMessage.loadEnvelope(IMAPMessage.java:1428)
at com.sun.mail.imap.IMAPMessage.getSubject(IMAPMessage.java:427)
at greenmailtest.ImapIT.getMails(ImapIT.java:79)
at greenmailtest.ImapIT.main(ImapIT.java:94)
I am attaching my test code here:-
public void setUp() {
mailServer = new GreenMail(ServerSetupTest.IMAP);
mailServer.start();
}
public void tearDown() {
mailServer.stop();
}
public void getMails() throws IOException, MessagingException,
UserException, InterruptedException {
// create user on mail server
GreenMailUser user = mailServer.setUser(EMAIL_USER_ADDRESS, USER_NAME,
USER_PASSWORD);
// create an e-mail message using javax.mail ..
File file=new File("/home/sameepsinghania/Desktop/HDFC/Addcalbackfailure.png");
// byte[] byteArray=TestMailUtil.readContentIntoByteArray(file);
MimeMultipart multipart=TestMailUtil.createMultipartWithAttachment(EMAIL_TEXT,file, "sameep.png");
MimeMessage message = new MimeMessage((Session) null);
message.setFrom(new InternetAddress(EMAIL_TO));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
EMAIL_USER_ADDRESS));
message.setSubject(EMAIL_SUBJECT);
message.setContent(multipart);
// use greenmail to store the message
user.deliver(message);
Properties props = new Properties();
Session session = Session.getInstance(props);
URLName urlName = new URLName("imaps", "127.0.0.1",
ServerSetupTest.IMAP.getPort(), null, user.getLogin(),
user.getPassword());
Store store = session.getStore(urlName);
store.connect();
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message[] messages = folder.getMessages();
for(Message message1: messages){
System.out.println("subject "+message1.getSubject());//**this is the line where I get the exception**
}
}
JavaMail Debug logs-:
DEBUG: setDebug: JavaMail version 1.5.3
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 "127.0.0.1", port 3143, isSSL false
* OK IMAP4rev1 Server GreenMail ready
A0 CAPABILITY
* CAPABILITY IMAP4rev1 LITERAL+ QUOTA
A0 OK CAPABILITY completed.
DEBUG IMAP: protocolConnect login, host=127.0.0.1, user=hascode, password=<non-null>
DEBUG IMAP: LOGIN command trace suppressed
DEBUG IMAP: LOGIN command result: A1 OK LOGIN completed.
A2 CAPABILITY
* CAPABILITY IMAP4rev1 LITERAL+ QUOTA
A2 OK CAPABILITY completed.
DEBUG IMAP: connection available -- size: 1
A3 EXAMINE INBOX
* FLAGS (\Answered \Deleted \Draft \Flagged \Seen)
* 1 EXISTS
* 1 RECENT
* OK [UIDVALIDITY 1461648432354]
* OK [UNSEEN 1] Message 1 is the first unseen
* OK [PERMANENTFLAGS (\Answered \Deleted \Draft \Flagged \Seen)]
A3 OK [READ-ONLY] EXAMINE completed.
A4 FETCH 1 (ENVELOPE INTERNALDATE RFC822.SIZE)
javax.mail.FolderClosedException: * BYE JavaMail Exception: java.io.IOException: Connection dropped by server?
at com.sun.mail.imap.IMAPMessage.loadEnvelope(IMAPMessage.java:1428)
at com.sun.mail.imap.IMAPMessage.getSubject(IMAPMessage.java:427)
at greenmailtest.ImapIT.getMails(ImapIT.java:78)

Resources