GreenMail integration test sent email not being relayed to recipient - jakarta-mail

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

Related

Apache Camel AS2 component cannot not process application/xml message

I tested to send a message with content-type set to application/xml to a Camel/AS2 server connection. However, I got 500 response. Does Camel/AS2 support application/xml content-typed messages?
Here comes the stack trace:
2022-01-16 11:44:23,725 [AS2Hdlr-6405] INFO .AS2ServerConnection [] - Processing new AS2 request
2022-01-16 11:44:23,725 [AS2Hdlr-6405] WARN nent.as2.AS2Consumer [] - Failed to process AS2 message
org.apache.http.HttpException: Failed to extract EDI message: invalid content type 'application/xml' for AS2 request message
at org.apache.camel.component.as2.api.util.HttpMessageUtils.extractEdiPayload(HttpMessageUtils.java:169) ~[camel-as2-api-3.13.0.jar!/:3.13.0]
at org.apache.camel.component.as2.AS2Consumer.handle(AS2Consumer.java:124) [camel-as2-3.13.0.jar!/:3.13.0]
at org.apache.http.protocol.HttpService.doService(HttpService.java:437) [wildfly-elytron-1.18.1.Final.jar!/:1.18.1.Final]
at org.apache.http.protocol.HttpService.handleRequest(HttpService.java:342) [wildfly-elytron-1.18.1.Final.jar!/:1.18.1.Final]
at org.apache.camel.component.as2.api.AS2ServerConnection$RequestHandlerThread.run(AS2ServerConnection.java:147) [camel-as2-api-3.13.0.jar!/:3.13.0]
2022-01-16 11:44:23,725 [AS2Hdlr-6405] INFO .AS2ServerConnection [] - Client closed connection

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")

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)

Java mail: Could not connect to SMTP host: ..., port: ..., java.net.ConnectException: Operation timed out

Thanks in advance to any help with this. Java Mail always worked for me but now it's throwing this annoying Exception:
//Exception:
run:
DEBUG: setDebug: JavaMail version 1.4.6
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "xxxxxx", port 25, isSSL false
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: xxxxxx, port: 25;
nested exception is:
java.net.ConnectException: Operation timed out
at vesso.mail.TestMail.sendMail(TestMail.java:79)
at vesso.mail.TestMail.main(TestMail.java:26)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: mail.mentorlicitacao.com.br, port: 25;
nested exception is:
java.net.ConnectException: Operation timed out
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1962)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:295)
at vesso.mail.TestMail.sendMail(TestMail.java:71)
... 1 more
Caused by: java.net.ConnectException: Operation timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1928)
... 4 more
Java Result: 1
BUILD SUCCESSFUL (total time: 1 minute 19 seconds)
I've tried to connect with Mail.app (using MacOS), and it worked fine.
//Code:
final String host = "xxxx";
final int port = 25;
final String username = "xxxx";
final String password = "xxxx";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(username));
message.setSubject("Teste");
message.setText("Bla, Bla, Bla!");
Transport transport = session.getTransport("smtp");
transport.connect (host, port, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
Thanks!
Problem solved by changing the port from 25 to 587. The conclusion I have reached is that my ISP blocks this port.
Thanks everyone.

JAXRS / CXF why is this simple post example not working

I know my client works as I post to another website and it all works. I changed the client to post to url http://localhost:9000/enrollment/enroll and ran the following server...
#Path("/enrollment")
public class MockHpsRestApi {
private static final Logger log = LoggerFactory.getLogger(MockHpsRestApi.class);
public static void main(final String[] args) throws InterruptedException,
IOException, MuleException {
log.info("starting the server");
JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setResourceClasses(MockHpsRestApi.class);
sf.setResourceProvider(MockHpsRestApi.class, new SingletonResourceProvider(new MockHpsRestApi()));
sf.setAddress("http://0.0.0.0:9000/");
sf.create();
}
#POST
#Path("/enroll")
#Consumes("application/xml")
public String enrollment(MultipartBody body) throws IOException {
log.info("received request="+body);
Attachment att = body.getRootAttachment();
ByteArrayOutputStream str = new ByteArrayOutputStream(100);
InputStream in = att.getDataHandler().getInputStream();
try {
IOUtils.copy(in, str);
log.info("body payload received="+str);
String xml = "success";
return xml;
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(str);
}
}
}
My logs though say this when it receives the request...
2012-03-16 09:30:30,295 INFO 300 [main] c.i.e.s.i.MockHpsRestApi - starting the server
Mar 16, 2012 9:30:30 AM org.apache.cxf.endpoint.ServerImpl initDestination
INFO: Setting the server's publish address to be http://0.0.0.0:9000/
2012-03-16 09:30:30,769 INFO 774 [main] org.eclipse.jetty.server.Server - jetty-7.5.4.v20111024
2012-03-16 09:30:30,801 INFO 806 [main] o.e.jetty.server.AbstractConnector - Started SelectChannelConnector#0.0.0.0:9000 STARTING
2012-03-16 09:30:30,824 INFO 829 [main] o.e.j.server.handler.ContextHandler - started o.e.j.s.h.ContextHandler{,null}
Mar 16, 2012 9:30:37 AM org.apache.cxf.jaxrs.utils.JAXRSUtils readFromMessageBody
WARNING: No message body reader has been found for request class MultipartBody, ContentType : application/xml.
Mar 16, 2012 9:30:37 AM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse
WARNING: WebApplicationException has been caught : no cause is available
Why isn't this working?
hmmm, turning up the log levels, is this some kind of bug in CXF, though that would mean no one is really doing basic posts, so that doesn't seem right....(again, my client posts fine to another service today).
2012-03-16 09:51:01,414 DEBUG 10916 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.JAXRSInInterceptor - Request path is: /enrollment/enroll
2012-03-16 09:51:01,414 DEBUG 10916 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.JAXRSInInterceptor - Request HTTP method is: POST
2012-03-16 09:51:01,414 DEBUG 10916 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.JAXRSInInterceptor - Request contentType is: application/xml
2012-03-16 09:51:01,415 DEBUG 10917 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.JAXRSInInterceptor - Accept contentType is: */*
2012-03-16 09:51:01,415 DEBUG 10917 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.JAXRSInInterceptor - Found operation: enrollment
2012-03-16 09:51:01,420 WARN 10922 [qtp669588045-18 - /enrollment/enroll] o.apache.cxf.jaxrs.utils.JAXRSUtils - No message body reader has been found for request class MultipartBody, ContentType : application/xml.
2012-03-16 09:51:01,423 WARN 10925 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.WebApplicationExceptionMapper - WebApplicationException has been caught : no cause is available
2012-03-16 09:51:01,428 DEBUG 10930 [qtp669588045-18 - /enrollment/enroll] o.a.c.j.i.WebApplicationExceptionMapper - no cause is available
javax.ws.rs.WebApplicationException: null
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBody(JAXRSUtils.java:1052) ~[cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameter(JAXRSUtils.java:616) ~[cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameters(JAXRSUtils.java:580) ~[cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:238) ~[cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:89) ~[cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263) [cxf-api-2.5.2.jar:2.5.2]
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:123) [cxf-rt-core-2.5.2.jar:2.5.2]
at org.apache.cxf.transport.http_jetty.JettyHTTPDestination.serviceRequest(JettyHTTPDestination.java:323) [cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.transport.http_jetty.JettyHTTPDestination.doService(JettyHTTPDestination.java:289) [cxf-bundle-2.5.2.jar:2.5.2]
at org.apache.cxf.transport.http_jetty.JettyHTTPHandler.handle(JettyHTTPHandler.java:72) [cxf-bundle-2.5.2.jar:2.5.2]
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:943) [jetty-server-7.5.4.v20111024.jar:7.5.4.v20111024]
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:879) [jetty-server-7.5.4.v20111024.jar:7.5.4.v20111024]
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117) [jetty-server-7.5.4.v20111024.jar:7.5.4.v20111024]
When using #POST and #Consumes("application/xml"), it's normal for the (single un-annotated) argument type on the method to be a JAXB-annotated class that CXF will deserialize the XML into before handing it to you. Is there a particular reason for not going that well-travelled route?
After debugging the code, it turns out you can use the following types as parameters to the method above.
Source
XMLSource
Document
byte[]
InputStream
I ended up using InputStream.

Resources