Java maill SSL peer shut down incorrectly - java

I'm working on an old Java 1.8 application which needs TLS to be configured for the mail sending part using java.mail-api of the javax-mail version 1.6.2. I added these properties to the properties map (pls notice the comment):
Properties smtpProps = System.getProperties();
smtpProps.put("mail.smtp.auth", config.getProperty("mail.smtpauth"));
smtpProps.put("mail.smtp.host", config.getProperty("mail.smtpserver"));
smtpProps.put("mail.smtp.port", config.getProperty("mail.smtpport"));
smtpProps.put("mail.transport.protocol", "smtp");
smtpProps.put("mail.smtp.connectiontimeout", config.getProperty("mail.timeout"));
smtpProps.put("mail.debug", config.getProperty("mail.debug"));
// Following block is new
smtpProps.put("mail.smtp.starttls.enable", config.getProperty("mail.starttls"));
smtpProps.put("mail.smtp.ssl.trust", config.getProperty("mail.ssltrust"));
smtpProps.put("mail.smtp.ssl.protocols", config.getProperty("mail.sslprotocols"));
smtpProps.put("mail.smtp.ssl.enable", config.getProperty("mail.ssl"));
Which will added to the session by overriding the PasswordAuthentication like this:
session = Session.getDefaultInstance(smtpProps,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pwd);
}
});
At last, there are some couple of lines with the message itself and following block to send the mail:
Transport t = session.getTransport();
try {
if (!user.equals(""))
t.connect(user, pwd);
else
t.connect();
msg.saveChanges();
t.sendMessage(msg, msg.getAllRecipients());
} catch (MessagingException e) {
log.error("Error while sending the mail: " + e.getMessage());
throw e;
} finally {
t.close();
t = null;
}
Unfortunately, this doesn't work. I'm getting an error which looks like this:
Caused by: java.io.EOFException: SSL peer shut down incorrectly
This exception points to the t.connect(user,pwd); line but not with authentication failed or so.

Related

LDAP Java print debug output

When one configure application settings it always useful to show debug/output of the process.
E.g. javax.mail.Session has debug and debugOutput. Is it something similar in parameters/API for InitialDirContext/InitialLdapContext/LdapCtxFactory Java classes?
My goal is to give a user debug info if something is going wrong with LDAP connection.
P.S. Java code is trivial:
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.put(Context.PROVIDER_URL, domainController);
properties.put(Context.SECURITY_AUTHENTICATION, "simple");
properties.put(Context.SECURITY_PRINCIPAL, login);
properties.put(Context.SECURITY_CREDENTIALS, password);
//initializing active directory LDAP connection
InitialDirContext dirContext = null;
try {
dirContext = new InitialDirContext(properties);
System.out.println("OK!");
} catch (NamingException e) {
//ignore auth. exception
System.out.println("Failed!!!");
e.printStackTrace();
}finally{
if(dirContext != null)
try {
dirContext.close();
} catch (NamingException e) {}
}
}
You can set the com.sun.jndi.ldap.connect.pool.debug system property to all and it should provide the information that you need.
https://docs.oracle.com/javase/jndi/tutorial/ldap/connect/config.html

javax.mail work on PC but not on server

I've search but can't seem to find a similar problem, never mind an answer. I have a web app running on my laptop (windows 8), tomcat7 and it works fine. It sends out the email as expected. I have the same code running on my linux server, also tomcat7 and I get javax.mail.AuthenticationFailedException.
I've done the Authenticator thing from the start:
...
Authenticator mailAuthenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(properties.getProperty("mail.smtp.user"),
properties.getProperty("mail.smtp.password"));
}
};
try {
// Get the default Session object.
Session session = Session.getInstance(properties, mailAuthenticator);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setSubject("Subject, whoot whoot!");
mimeMessage.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from")));
//This is an overkill
List<String> emailList = new LinkedList<>();
emailList.add("email#example.com");
for(String item : emailList) {
mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(item));
}
//The body ).(
StringBuilder sbMsg = new StringBuilder("Some text, etc.\n");
sbMsg.append("more text");
Multipart multipart = new MimeMultipart("alternative");
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setContent(sbMsg.toString(), "text/plain");
multipart.addBodyPart(messageBodyPart1);
mimeMessage.setContent(multipart);
Transport transport = session.getTransport(properties.getProperty("mail.transport"));
int port = Integer.parseInt(properties.getProperty("mail.smtp.port"));
//Exception happens on the line below
transport.connect(properties.getProperty("mail.smtp.host"),
port,
properties.getProperty("mail.smtp.user"),
properties.getProperty("mail.smtp.password"));
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
return true;
} catch (Exception e) {
//Pokemon exception handling :(
LOG.log(Level.SEVERE, "Error while sending email", e);
}
The exception happens on transport.connect, and there is no description with the exception :(
I've checked the mail.smtp.user and mail.smtp.password and it is exactly the same :s
Any clues where I can start looking?
Just got an emails and text from Google. GMail thought I was trying to hack my account. I'm glad there is a logical answer to this problem :-)

Connecting to IMAP javax.net.ssl.SSLException: Unrecognized SSL message

I am trying to connect to my company IMAP server using following program but I am getting SSLException.
import javax.mail.*;
import java.util.Properties;
/**
* Created by SDuraisamy on 6/18/2014.
*/
public class Test {
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getInstance(props, null);
Store store = null;
try {
store = session.getStore();
// store.connect("imap.gmail.com","mygmailaccount#gmail.com","password");
store.connect("exchange_server", "account2", "password");
Folder inbox = store.getFolder("INBOX");
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
I am getting following Exception
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at Test.main(Test.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at com.sun.net.ssl.internal.ssl.InputRecord.handleUnknownRecord(InputRecord.java:523)
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:355)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:789)
How can I resolve this error?
The same code works when I connect to my gmail account(source commented above), I am able to connect and read messages through my program.
Any setting required at exchange server end to download messages through IMAP? I already have IMAP enabled on my exchange server.
Changing
props.setProperty("mail.store.protocol", "imaps");
to
props.setProperty("mail.store.protocol", "imap");
resolved the issue

vysper server login fail

I'm making a vysper xmpp server.
Here's my code:
public static void main(String[] args) throws Exception {
XMPPServer server = new XMPPServer("myserver.org");
StorageProviderRegistry providerRegistry = new MemoryStorageProviderRegistry();
AccountManagement accountManagement = (AccountManagement) providerRegistry.retrieve(AccountManagement.class);
Entity user = EntityImpl.parseUnchecked("user#myserver.org");
accountManagement.addUser(user, "password");
server.setStorageProviderRegistry(providerRegistry);
server.addEndpoint(new TCPEndpoint())
server.setTLSCertificateInfo(new File("keystore.jks"), "boguspw");
//server.setTLSCertificateInfo(new File("bogus_mina_tls.cert"), "boguspw");
server.start();
System.out.println("Vysper server is running...");
server.addModule(new EntityTimeModule());
server.addModule(new VcardTempModule());
server.addModule(new XmppPingModule());
server.addModule(new PrivateDataModule());
}
I've tried both certificate files. (keystore.jks,bogus_mina_tls.cert)
After I start the server, it connects to it, and tries to login but it can't login.
SmackConfiguration.setPacketReplyTimeout(5000);
config = new ConnectionConfiguration("myserver.org", port, "localhost");
config.setSelfSignedCertificateEnabled(true);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
config.setSASLAuthenticationEnabled(true);
// config.setKeystorePath("keystore.jks");
// config.setTruststorePath("keystore.jks");
config.setKeystorePath("bogus_mina_tls.cert");
config.setTruststorePath("bogus_mina_tls.cert");
config.setTruststorePassword("boguspw");
XMPPConnection.DEBUG_ENABLED = true;
connection = new XMPPConnection(config);
try {
connection.connect();
} catch (XMPPException e) {
System.out.println("Error connect");
e.printStackTrace();
}
System.out.println("Connected: " + connection.isConnected());
try {
System.out.println(connection.isAuthenticated());
connection.login("user", "password");
} catch (XMPPException e) {
System.out.println("Error login");
e.printStackTrace();
}
I catch this exception:
SASL authentication PLAIN failed: incorrect-encoding: at
org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:337)
at
org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:203)
at org.jivesoftware.smack.Connection.login(Connection.java:348) at
com.protocol7.vysper.intro.WorkingClient.init(WorkingClient.java:57)
at
com.protocol7.vysper.intro.WorkingClient.(WorkingClient.java:27)
at com.protocol7.vysper.intro.Runclient.main(Runclient.java:11)
I've seen these examples (1st, 2nd) but they don't work.
At first please note that the server certificate is not used for user authentication, it is used to provide secure communication channel between client and server.
From the log you can see that your authentication method is "SASL PLAIN", using a user and password.
On the server, you are setting username/password as:
accountManagement.addUser("user#myserver.org", "password");
but on the client you're using
connection.login("user", "password");
This doesn't fit with the error message you are posting, but I'd suggest you try again with correct user/password.

Unable to read the Gmail INBOX from the java code using POP API .. giving an error java.net.ConnectException: Connection timed out: connect error

props.put("mail.pop3.host", "pop.gmail.com");
props.put("mail.pop3.user", "xxx#gmail.com");
props.put("mail.pop3.socketFactory", 995);
props.put("mail.pop3.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.pop3.port", 995);
Session session = Session.getDefaultInstance(props,
new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxx",
"xxx");
}
});
try {
Store store = session.getStore("pop3");
store.connect("pop.gmail.com", "xxxxx", "xxx");
Folder fldr = store.getFolder("INBOX");
fldr.open(Folder.HOLDS_MESSAGES);
int count = fldr.getMessageCount();
System.out.println(count);
} catch (Exception exc) {
System.out.println(exc + " error");
}
// TODO Auto-generated method stub
}
Error:
javax.mail.MessagingException: Connect failed; nested exception is: java.net.ConnectException: Connection timed out: connect error
As I have added Proxy setting in this application
And set firewalls off. Still its is giving the above error.
The JavaMail FAQ has simpler code for connecting to Gmail, as well as tips for debugging connection problems and instructions for using proxy servers.

Categories