using javaMail to read shared mailbox - java

I am creating an interface capable of reading e-mails from a shared mailbox. I have already tried several different approaches I could find in stack over, but none worked. Examples:
Properties props = System.getProperties();
// Set manual Properties
props.setProperty("mail.imaps.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.socketFactory.port", "993");
props.put("mail.imaps.host", "outlook.office365.com");
try {
/* Create the session and get the store for read the mail. */
Session session = Session.getDefaultInstance(System.getProperties(), null);
Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, "eduardo.david#hpe.com/APSDataExtract", "-myPassword-");
gives me the following result:
Exception while connecting to server: AUTHENTICATE failed.
javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:661)
at javax.mail.Service.connect(Service.java:295)
at t2.OutLookReader_imaps.<init>(OutLookReader_imaps.java:39)
at t2.OutLookReader_imaps.main(OutLookReader_imaps.java:121)
If I try other codes, the result is the same:
store.connect("outlook.office365.com", 993, "hpe\\eduardo.david#hpe.com\\APSDataExtract", "-myPassword-");
Result:
Exception while connecting to server: * BYE Connection is closed. 13
javax.mail.MessagingException: * BYE Connection is closed. 13;
nested exception is:
com.sun.mail.iap.ConnectionException: * BYE Connection is closed. 13
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:668)
at javax.mail.Service.connect(Service.java:295)
at t2.OutLookReader_imaps.<init>(OutLookReader_imaps.java:39)
at t2.OutLookReader_imaps.main(OutLookReader_imaps.java:121)
Caused by: com.sun.mail.iap.ConnectionException: * BYE Connection is closed. 13
at com.sun.mail.iap.Protocol.handleResult(Protocol.java:356)
at com.sun.mail.imap.protocol.IMAPProtocol.authplain(IMAPProtocol.java:603)
at com.sun.mail.imap.IMAPStore.login(IMAPStore.java:736)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:642)
... 3 more
store.connect("outlook.office365.com", 993, "hpe\\eduardo.david\\APSDataExtract", "-myPassword-");
Result:
Inside MailReader()...
Exception while connecting to server: * BYE Connection is closed. 13
javax.mail.MessagingException: * BYE Connection is closed. 13;
nested exception is:
com.sun.mail.iap.ConnectionException: * BYE Connection is closed. 13
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:668)
at javax.mail.Service.connect(Service.java:295)
at t2.OutLookReader_imaps.<init>(OutLookReader_imaps.java:39)
at t2.OutLookReader_imaps.main(OutLookReader_imaps.java:121)
Caused by: com.sun.mail.iap.ConnectionException: * BYE Connection is closed. 13
at com.sun.mail.iap.Protocol.handleResult(Protocol.java:356)
at com.sun.mail.imap.protocol.IMAPProtocol.authplain(IMAPProtocol.java:603)
at com.sun.mail.imap.IMAPStore.login(IMAPStore.java:736)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:642)
... 3 more
store.connect("outlook.office365.com", 993, "hpe\\davidedu\\APSDataExtract", "-myPassword-");
Result:
Inside MailReader()...
Exception while connecting to server: * BYE Connection is closed. 13
javax.mail.MessagingException: * BYE Connection is closed. 13;
nested exception is:
com.sun.mail.iap.ConnectionException: * BYE Connection is closed. 13
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:668)
at javax.mail.Service.connect(Service.java:295)
at t2.OutLookReader_imaps.<init>(OutLookReader_imaps.java:39)
at t2.OutLookReader_imaps.main(OutLookReader_imaps.java:121)
Caused by: com.sun.mail.iap.ConnectionException: * BYE Connection is closed. 13
at com.sun.mail.iap.Protocol.handleResult(Protocol.java:356)
at com.sun.mail.imap.protocol.IMAPProtocol.authplain(IMAPProtocol.java:603)
at com.sun.mail.imap.IMAPStore.login(IMAPStore.java:736)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:642)
... 3 more
To access my own inbox, code works perfectly:
store.connect("outlook.office365.com", 993, "eduardo.david#hpe.com", "-myPassword-");
Inside MailReader()...
No. of Unread Messages : 580
No. of Messages : 849
No. of Deleted Messages : 2
Can anybody give to this java new programmer a simple solution in order to read a shared mailbox?

I solved it adding this parameters:
sysProps.setProperty("mail.imaps.auth.plain.disable", "true");
sysProps.setProperty("mail.imaps.auth.ntlm.disable", "true");
I connected using:
store.connect("outlook.office365.com", "name#abc.com\\sharedmailAlias", "password");
My email: name#abc.com
My shared email address:
sharedmailAlias#abc.com

Related

JavaMail always uses localhost in Liferay

I am facing a strange problem and I can't figure out the problem. I have a web application/portlet deployed in Liferay portal which should be sending an email. I have the configuration correct and the code looks like this:
Session mailSession = mailSender.getSession();
Transport transport = mailSession.getTransport("smtp");
Message message = buildMessage(); // placeholder for building the message
try {
transport.sendMessage(msg, msg.getAllRecipients());
} finaly {
transport.close();
}
This, however, always tries to connecto to localhost:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
liferay_1 | nested exception is:
liferay_1 | java.net.ConnectException: Connection refused (Connection refused)
Now, I though that the connection settings are not correct, so I decided to log them:
LOG.debug("Host:" + mailSender.getHost() + " --- Port: " + mailSender.getPort());
LOG.debug("Password:" + mailSender.getPassword() + " --- User: " + mailSender.getUsername());
mailSession.getProperties().entrySet().forEach(p -> LOG.debug("---" + p.getKey() + "-" + p.getValue()));
And they are indeed correct in the session:
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:92) - Host:test-host --- Port: 5678
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:93) - Password:$test --- User: test
liferay_1 | DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:97) - ---mail.transport.protocol-smtp
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:97) - ---mail.debug-true
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:97) - ---mail.smtp.auth-test
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:97) - ---mail.smtp.starttls.enable-true
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:99) - Transport:smtp://liferay#
I can't figure out what else I can do and I don't know from where does the transport get localhost and port 25.
After further investigation, I discovered that there is a method for connecting to a specified host.
/**
* Similar to connect(host, user, password) except a specific port
* can be specified.
*
* #param host the host to connect to
* #param port the port to connect to (-1 means the default port)
* #param user the user name
* #param password this user's password
* #exception AuthenticationFailedException for authentication failures
* #exception MessagingException for other failures
* #exception IllegalStateException if the service is already connected
* #see #connect(java.lang.String, java.lang.String, java.lang.String)
* #see javax.mail.event.ConnectionEvent
*/
public synchronized void connect(String host, int port,
String user, String password) throws MessagingException
Using this one, you can specify the exact host, port and credentials. Why the Session does not contain this information and why it is not being used, even though the Transport and Session are obtained fro the original JavaMailSenderImpl is still a mystery to me.
What version of Liferay are you on?
First thing first, you will need to check if your credentials are correctly set up in Control Panel > Server Administration > Mail.
Check your:
Outgoing SMTP Server and
Outgoing Port
if they are still pointing to localhost and 25 respectively.
Second, the implementation looks unfamiliar to me. Can you try this way?
import com.liferay.mail.kernel.service.MailServiceUtil;
...
Message message = buildMessage();
MailServiceUtil.sendEmail(message);
or if you want to get a session
MailServiceUtil.getSession()

Creating an ssl connection to oracle db with Java

I'm trying to connect to an Oracle DB using Java and SSL. For now I have the Java program on the server with the database.
I'm getting this error when I try to run it (full error in comment):
java.sql.SQLRecoverableException: IO Error: Inbound closed before receiving peer's close_notify: possible truncation attack?, connect lapse 15 ms., Authentication lapse 0 ms.
This is my java code:
public static void main(String[] args) {
Security.addProvider(new oracle.security.pki.OraclePKIProvider());
String url = "jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=localhost)(PORT=2484))(CONNECT_DATA=(SERVICE_NAME=ORCL)))";
Properties props = new Properties();
props.setProperty("javax.net.ssl.trustStore",
"C:\\app\\Administrator\\virtual\\product\\12.2.0\\dbhome_1\\bin\\wallets\\Administrator\\cwallet.sso");
props.setProperty("javax.net.ssl.trustStoreType","SSO");
props.setProperty("javax.net.ssl.keyStore",
"C:\\app\\Administrator\\virtual\\product\\12.2.0\\dbhome_1\\bin\\wallets\\Administrator\\cwallet.sso");
props.setProperty("javax.net.ssl.keyStoreType","SSO");
try {
Connection conn = DriverManager.getConnection(url, props);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I added this to listener.ora and tnsnames.ora (I also tried with the sso file and just linking to the directory)
WALLET_LOCATION=(SOURCE=(METHOD=FILE) (METHOD_DATA=(DIRECTORY=C:\app\Administrator\virtual\product\12.2.0\dbhome_1\bin\wallets\Administrator\ewallet.p12 ))
SSL_CLIENT_AUTHENTICATION=TRUE
I also added this to java.security:
security.provider.11=oracle.security.pki.OraclePKIProvider
edit: I didn't realize the length limit on comments was so short. Here's the full error:
Caused by: java.io.IOException: Inbound closed before receiving peer's close_notify: possible truncation attack?, connect lapse 11 ms., Authentication lapse 0 ms.
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:790)
... 6 more
Caused by: java.io.IOException: Inbound closed before receiving peer's close_notify: possible truncation attack?, connect lapse 11 ms.
at oracle.net.ns.NSProtocolNIO.negotiateConnection(NSProtocolNIO.java:138)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:317)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1438)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:518)
... 6 more
Caused by: javax.net.ssl.SSLException: Inbound closed before receiving peer's close_notify: possible truncation attack?
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLEngineImpl.fatal(Unknown Source)
at sun.security.ssl.SSLEngineImpl.fatal(Unknown Source)
at sun.security.ssl.SSLEngineImpl.closeInbound(Unknown Source)
at oracle.net.nt.SSLSocketChannel.fill(SSLSocketChannel.java:534)
at oracle.net.nt.SSLSocketChannel.unwrap(SSLSocketChannel.java:434)
at oracle.net.nt.SSLSocketChannel.handshake(SSLSocketChannel.java:350)
at oracle.net.nt.SSLSocketChannel.write(SSLSocketChannel.java:238)
at oracle.net.ns.NIOPacket.writeToSocketChannel(NIOPacket.java:211)
at oracle.net.ns.NIOConnectPacket.writeToSocketChannel(NIOConnectPacket.java:232)
at oracle.net.ns.NSProtocolNIO.negotiateConnection(NSProtocolNIO.java:108)
... 9 more
Can you make sure to have oraclepki.jar, osdt_core.jar and osdt_cert.jar in the classpath? You don't need to use keystore and truststore properties. Use oracle.net.wallet_location and oracle.net.ssl_server_dn_match=true. Check out the blog for more details.

MailConnectException: Couldn't connect to host, port: smtp.sendgrid.net

I have created API key for sendGrid:
I have following spring mail configuration:
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.sendgrid.net
spring.mail.username=apikey
spring.mail.password=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
spring.mail.port=25
spring.mail.protocol=smtp
spring.mail.test-connection=true
And I have following code:
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
Template template = freemarkerConfig.getTemplate(templateFileName);
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, props);
helper.setTo("myEmail#gmail.com");
helper.setText(html, true);
helper.setSubject(subject);
helper.setFrom(from);
sender.send(message);
logger.debug("Send email to {} with subject: [{}]", Arrays.toString(to), subject);
Then I try to start application and experience following error:
27.01.18 20:07:20.460 [main] WARN c.d.m.s.c.MailSenderValidatorAutoConfiguration - Mail server is not available
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.sendgrid.net, 25; timeout -1
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2118)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:712)
at javax.mail.Service.connect(Service.java:366)
at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:501)
at org.springframework.mail.javamail.JavaMailSenderImpl.testConnection(JavaMailSenderImpl.java:382)
How can I fix this?
P.S.
Everything correct for port 587
But I want to use ssl and set port=465
spring.mail.port=465
And at this case my application freezes on startup.and after 5 min prints:
27.01.18 21:06:05.960 [main] WARN c.d.m.s.c.MailSenderValidatorAutoConfiguration - Mail server is not available
javax.mail.MessagingException: Could not connect to SMTP host: smtp.sendgrid.net, port: 465, response: -1
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2106)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:712)
at javax.mail.Service.connect(Service.java:366)
at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:501)
at org.springframework.mail.javamail.JavaMailSenderImpl.testConnection(JavaMailSenderImpl.java:382)
How can I avoid this?
I used the port 2525 (Non-privileged) instead of 578 (privileged) to solve the problem locally. I can still use the privileged one on the cloud. That solved my problem.
You may need add something like this to your configuration.
spring.mail.smtp.ssl.enable=true
There is a probability that SendGrid SMTP servers are not discoverable in your country. try a proxy or VPN.

Partner not reached error in JCO.destination

I'm Having a problem establishing a connection to SAP in my java program.
I'm following the examples that come in the JCO download but i always get this error:
com.sap.conn.jco.JCoException: (102) RFC_ERROR_COMMUNICATION: Connect to SAP gateway failed
Connection parameters: TYPE=A DEST=ABAP_AS_WITHOUT_POOL ASHOST=xx.xx.x.xx SYSNR=00 PCS=1
LOCATION CPIC (TCP/IP) on local host with Unicode
ERROR partner 'xx.xx.x.xx:3300' not reached
TIME Wed Jul 08 08:18:28 2015
RELEASE 711
COMPONENT NI (network interface)
VERSION 39
RC -10
MODULE nixxi.cpp
LINE 3147
DETAIL NiPConnect2: xx.xx.x.xx:3300
SYSTEM CALL connect
ERRNO 10060
ERRNO TEXT WSAETIMEDOUT: Connection timed out
COUNTER 2
I don't know what it can be, i'm writing down the correct connection properties (ashost,user,passwd,sysnr,etc).
Has anybody else has had a problem like this?
This is my connection code:
Properties connectProperties = new Properties();
connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "xx.xx.x.xx");
connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, "00");
connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, "020");
connectProperties.setProperty(DestinationDataProvider.JCO_USER, "xxxxxx");
connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, "xxxxxxx");
connectProperties.setProperty(DestinationDataProvider.JCO_LANG, "en");
createDataFile(ABAP_AS, "jcoDestination", connectProperties);
After that i just instantiate the object with those properties and call the method connect that is written like this:
JCoDestination destination = JCoDestinationManager.getDestination(ABAP_AS);
System.out.println("Attributes:");
System.out.println(destination.getAttributes());
System.out.println();
I'm working on Java, using netbeans, the sapjco3.jar is added to my libraries.
Do i have to do anything with the dll file that comes?

Java email - Exception Server is not trusted

I'm using apache commons mail to send emails. Unfortunately I'm getting following Exception:
org.apache.commons.mail.EmailException: Sending the email to the following server failed : mail.xxx.com:25
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1242)
at org.apache.commons.mail.Email.send(Email.java:1267)
at com.xxx.UserBean.sendMail(UserBean.java:92)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
.
.
.
Caused by: javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
java.io.IOException: Server is not trusted: mail.xxx.com
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1880)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:648)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1232)
... 85 more
Caused by: java.io.IOException: Server is not trusted: mail.xxx.com
at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:443)
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1875)
... 92 more
And here is my java code:
public void sendMail(){
try {
SimpleEmail mail = new SimpleEmail();
mail.setTLS(true);
mail.setAuthenticator(new DefaultAuthenticator("user","xyxyxyxy"));
mail.setHostName("mail.xxx.com");
mail.getMailSession().getProperties().put("mail.smtps.auth", true);
mail.getMailSession().getProperties().put("mail.debug", true);
mail.getMailSession().getProperties().put("mail.smtps.port", "587");
mail.getMailSession().getProperties().put("mail.smtp.starttls.enable", true);
mail.getMailSession().getProperties().put("mail.smtp.ssl.trust", "smtpserver");
mail.addTo("user#server.com", "user");
mail.setFrom("info#xxx.com");
mail.setSubject("Bla Bla");
mail.setMsg("Bla Bla again");
mail.send();
} catch (Exception ex) {
logger.info("Senden der Email ist gescheitert!", ex);
}
}
I've already read many threads and tried many hints. I'm stuck here!
I should mention that I'm able to send emails with another method using "javax.mail". But I'd like to move to apache.
I'm thankful for any help.
setTLS (Transport layer security) to false. If you are not using. When it is true its expected to be mail.xxx.com trusted server.
mail.setTLS(false);
Finally Solved. I tried everything to get authenticated at my exchange server.
use the code below:
Properties props = (Properties)System.getProperties().clone();
props.put("mail.smtp.host", host);
props.setProperty("mail.smtp.port", "587");
props.put("mail.smtp.auth", true);
//Bypass the SSL authentication
props.put("mail.smtp.ssl.enable", false);
props.put("mail.smtp.starttls.enable", false);
If you're using Spring-Boot-Mail, try adding this line to you .properties file:
spring.mail.properties.mail.smtp.ssl.trust=smtp.mandrillapp.com

Categories

Resources