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

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

Related

Java maill SSL peer shut down incorrectly

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.

sending e-mails automatically

I'm trying to setup a program which can automatically send e-mails. However, the first step doesn't even work for me and it gives this error:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: 127.0.0.1, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2209)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at server.main(server.java:46)
Caused by: java.net.ConnectException: Connection refused: connect
at java.base/java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.base/java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:400)
at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:243)
at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:225)
at java.base/java.net.PlainSocketImpl.connect(PlainSocketImpl.java:148)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:402)
at java.base/java.net.Socket.connect(Socket.java:591)
at java.base/java.net.Socket.connect(Socket.java:540)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:353)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:239)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2175)
... 7 more
This is the code:
// File Name SendEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class server {
public static void main(String [] args) {
// Recipient's email ID needs to be mentioned.
String to = "my other email properly written";
// Sender's email ID needs to be mentioned
String from = "my email properly written";
// Assuming you are sending email from localhost
String host = "127.0.0.1";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Does anyone have any idea why this happens and how to solve this? My e-mail is actually open etc. And because it's localhost I have no idea why it wouldn't work.
Access to a SMTP server would require the smtp host port and the security settings if applicable.
Properties props = new java.util.Properties();
props.put("mail.smtp.host", "hostname") #
props.put("mail.smtp.port", "portnumber") #25
props.put("mail.smtp.starttls.enable", "boolean value true or false")
props.put("mail.smtp.auth", "boolean value true or false")
Usually a session need to be created (a Java mail session using the username and password and the properties), that is missing in the code above. For demonstration purpose,
Session session = javax.mail.Session.getInstance( props,
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication("username", "password"); //username and password
}
});

can't connect with pop3 server

i want to check my mails with an app. my code so far:
my provider uses SSL, see
here.
my code so far:
try {
//1) get the session object
Properties properties = new Properties();
properties.put("mail.pop3s.host", "pop.1und1.de");
properties.put("mail.pop3s.port", "995");
Session emailSession = Session.getDefaultInstance(properties);
//2) create the POP3 store object and connect with the pop server
POP3Store emailStore = (POP3Store) emailSession.getStore("pop3s");
emailStore.connect(<myMailAdress>, <password>);
//3) create the folder object and open it
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
//4) retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
for(Message message:messages) {
String from = message.getFrom()[0].toString().toLowerCase();
Log.e("XXXXXX",from);
}
emailFolder.close(false);
emailStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
catch (MessagingException e) {
e.printStackTrace();
}
the code runs until emailStore.connect(). There i get the Exception
javax.mail.MessagingException: Connect failed; nested exception is: javax.net.ssl.SSLHandshakeException: Connection closed by peer.

Failed to send Mail with Javax.mail

I'm trying to send an email on Windows 8.1 with java 1.8 using javax.mail API but I keep getting an error.
Here is the method I wrote:
public void sendAlertMail(String from, String to, String header, String msgBody){
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", smptHost);
props.put("mail.smtp.port", smptPort);
props.put("mail.smtp.starttls","true");
Session mailSession;
if (authenticate) {
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
mailSession = Session.getInstance(props, auth);
}
else{
mailSession = Session.getInstance(props);
}
// uncomment for debugging infos to stdout
// mailSession.setDebug(true);
Transport transport = null;
try {
transport = mailSession.getTransport();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
MimeMessage message = new MimeMessage(mailSession);
try {
message.addHeaderLine(header);
message.setContent(msgBody, "text/plain");
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
} catch (MessagingException e) {
}
try {
transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
And the error I receive is:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 587; timeout -1;
nested exception is:
java.net.SocketException: Permission denied: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2100)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:699)
at javax.mail.Service.connect(Service.java:388)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at tapperSolution.mail.MailSender.sendAlertMail(MailSender.java:64)
at tapperSolution.mail.MailSender.sendAlertMail(MailSender.java:74)
at tapperSolution.mail.MailSender.main(MailSender.java:88)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.net.SocketException: Permission denied: connect\at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:331)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2066)
... 12 more
I turned off my firewall and anti virus and I tried to set the VM option in my code using:
System.setProperty("java.net.preferIPv4Stack", "true");
Also tried to set it in the run command with:
-Djava.net.preferIPv4stack=true
I was able to send mail using Python, but I want to do it using Java.
Tried to capture traffic using Wireshark, but there is no even a TCP handshake with the server.
Any other ideas?
Thanks
It looks like your SMTP server may be rejecting your connection, perhaps due to authentication issues. To test this, try a manual SMTP session from the same machine, and see what the result is.

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