JavaMail SocketException: Connection reset - java

I'm trying to send emails through JavaMail API but I end up receiving the SocketException: Connection reset.
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMailSSL {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Authenticator auth = new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("userName#gmail.com","gmailPassword");
}
};
Session session = Session.getDefaultInstance(props,auth);
try {
Message message = new MimeMessage(session);
Address sender = new InternetAddress("any#...");
message.setFrom(sender);
String recipients = "email1#...,email2#...,email2#...";
String[] toList = recipients.split(",");
System.out.println(toList.length);
Address[] addressTo = new InternetAddress[toList.length];
for(int i = 0; i < toList.length; i++){
addressTo[i] = new InternetAddress(toList[i]);
}
for( int i=0; i < addressTo.length; i++) { // changed from a while loop
message.addRecipient(Message.RecipientType.TO, addressTo[i]);
}
message.setSubject("Testing Subject 5");
message.setText("Dear Message ," +
"\n\n HELLO, please! \n https://192.168.192.120:8181/centralWeb");
System.out.println("SENDING MAIL......... " + new Date().toString());
message.setHeader("Content-type", "text/html; charset=UTF-8");
Transport.send(message);
System.out.println("Done " + new Date().toString());
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
NetBeans Output:
1
SENDING MAIL......... Sun Apr 28 01:30:18 IST 2013
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.SocketException: Connection reset
at sendmailssl.SendMailSSL.main(SendMailSSL.java:65)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at javax.mail.Service.connect(Service.java:313)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at sendmailssl.SendMailSSL.main(SendMailSSL.java:60)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:312)
at sun.security.ssl.InputRecord.read(InputRecord.java:350)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1328)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:503)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:234)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
... 7 more
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
I've tried disabling IPv6 and turning off my firewall too, but the problem persists. I am using Windows 7 x64, if that matters.
Thanks to anyone who can help me fix this issue.

Try these debugging tips from the JavaMail FAQ:
How do I debug my application that uses JavaMail APIs?
How do I debug problems connecting to my mail server?
Also, you might want to correct these common mistakes, although I don't think they're related to your problem.

Related

Unable to connect hive through JDBC java

I am trying to connect hive through java(eclipse). Hive is working on the linux server, where I have installed it.
I have imported all the jar files.
I am using this code
BasicConfigurator.configure();
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
final String keyPath = "Here is the keypath";
final String user = "myuser/FQDN#REALM.COM";
Configuration conf = new Configuration();
conf.set("hadoop.security.authentication", "kerberos");
System.setProperty("java.security.krb5.conf", "PATH:/krb5.conf");
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
UserGroupInformation ugi;
UserGroupInformation.setConfiguration(conf);
ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(user, keyPath);
UserGroupInformation.setLoginUser(ugi);
System.out.println("TRYING TO CONNECT");
Connection cnct = null;
cnct = DriverManager.getConnection(
"jdbc:hive2://FQDN:10000/default;principal=ADDED PRINCIPAL HERE",
"user", "pass");
System.out.println("Connected");
cnct.close();
}
The error I am getting is:
Exception in thread "main" java.sql.SQLException: Could not open connection to jdbc:hive2://FQDN:10000/default;principal=PRINCIPAL HERE: Peer indicated failure: GSS initiate failed
at org.apache.hive.jdbc.HiveConnection.openTransport(HiveConnection.java:146)
at org.apache.hive.jdbc.HiveConnection.<init>(HiveConnection.java:123)
at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:105)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at TestHiveJdbc.main(TestHiveJdbc.java:56)
Caused by: org.apache.thrift.transport.TTransportException: Peer indicated failure: GSS initiate failed
at org.apache.thrift.transport.TSaslTransport.receiveSaslMessage(TSaslTransport.java:190)
at org.apache.thrift.transport.TSaslTransport.open(TSaslTransport.java:258)
at org.apache.thrift.transport.TSaslClientTransport.open(TSaslClientTransport.java:37)
at org.apache.hadoop.hive.thrift.client.TUGIAssumingTransport$1.run(TUGIAssumingTransport.java:52)
at org.apache.hadoop.hive.thrift.client.TUGIAssumingTransport$1.run(TUGIAssumingTransport.java:49)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/javax.security.auth.Subject.doAs(Subject.java:423)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
at org.apache.hadoop.hive.thrift.client.TUGIAssumingTransport.open(TUGIAssumingTransport.java:49)
at org.apache.hive.jdbc.HiveConnection.openTransport(HiveConnection.java:144)
... 5 more
Kindly help me with this.

How to connect to office365 using IMAPS protocol from Java application

There are few articles out there about this, but non of them worked for me. Basically I have following java code to connect to office 365:
Properties props = new Properties();
props.put("mail.imaps.auth.plain.disable", "true");
props.put("mail.imaps.ssl.enable", "true");
session = Session.getInstance(props, null);
store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, "user#mydomain.com", "psw");
but it fails with LOGIN failed error;
javax.mail.AuthenticationFailedException: LOGIN failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:725)
at javax.mail.Service.connect(Service.java:366)
Also I'm able to login into my account using IMAPS from Thunderbird.
Any pointers to resolve an issue would be appreciated!
This code works for me for outlook I have modified it for use with Office365. I did the research to find the IMAP host for office 365. I hope it helps you.
public static void main(String[] args) throws MessagingException {
MultiPartEmail email = new MultiPartEmail();
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
//extra codes required for reading OUTLOOK mails during IMAP-start
props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.socketFactory.port", "993");
//extra codes required for reading OUTLOOK mails during IMAP-end
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("outlook.office365.com", "some.one#some.org", "mypassword");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
inbox.addMessageCountListener(new MessageCountListener() {
#Override
public void messagesAdded(MessageCountEvent messageCountEvent) {
Message[] messages = messageCountEvent.getMessages();
System.out.println("A message was added, you now have: " + messages.length + " emails");
}
#Override
public void messagesRemoved(MessageCountEvent messageCountEvent) {
}
});
while (true) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
inbox.getMessageCount(); // Keeps connection alive
}
}
As it turned out, office 365 was rejecting connections because of unsupported characters inside the password. Particularly quote character. So, as simple as changing psw fixed my problem.
And following code snippet works just fine:
Properties props = new Properties();
props.put("mail.store.protocol", "imaps");
session = Session.getInstance(props, null);
store = session.getStore();
store.connect("outlook.office365.com", 993, "user#mydomain.com", "psw");
With 'javax.mail', version: '1.5.6'

Error when sending email in Java

I have a problem with sending emails in Java. I am using the JavaMail api to send emails. I have a program which downloads an email attachment using pop3, reads the content, does some manipulation and then sends the result in an email using smtp.
The program works fine until the last step where it sends the email and I get the following exception.
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:295)
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 com.adidas.monitoring.SendMail.sendMail(SendMail.java:46)
at com.adidas.monitoring.MainClass.main(MainClass.java:115)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
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:1927)
I am using the following code to send the email
public void sendMail(String strMailContent)
{
MimeMessage emailMessage;
Properties emailProperties = new Properties();
try {
emailProperties.load(new FileInputStream("Email.ini"));
} catch (IOException e){
DataLogger.logger.error(e.getMessage());
}
/*Get the properties from the email configuration file*/
String From = emailProperties.getProperty("Email.From");
String ToAdd = emailProperties.getProperty("Email.To");
String CC = emailProperties.getProperty("Email.CC");
String Subject = emailProperties.getProperty("Email.Subject");
String Host = emailProperties.getProperty("Email.Gateway");
emailProperties.setProperty("mail.smtp.host", Host);
Session emailSendSession = Session.getDefaultInstance(emailProperties);
try{
emailMessage = new MimeMessage(emailSendSession);
emailMessage.setFrom(new InternetAddress(From));
emailMessage.addRecipients(javax.mail.Message.RecipientType.TO,ToAdd);
emailMessage.addRecipients(javax.mail.Message.RecipientType.CC,CC);
emailMessage.setSubject(Subject);
emailMessage.setText(strMailContent);
Transport.send(emailMessage);
}
catch (Exception mailEx)
{
mailEx.printStackTrace();
}
}
The above code works fine when I use it with other programs. But when I am using it along with the pop3 code in this case, I have this error. Strange thing is the host is shown as localhost even though I set the property "mail.smtp.host".
Any help on this topic is really appreciated.

Java send mail, Takes time in Activation

I need to send a mail using SMTP of Gmail, and javax.mail api.
The same code I'm using, runs successfully in Android, If I take it to a Java Application or tries to use it in a Java Web Application it starts making troubles.
I spent time trying to understand what is the difference but no way!
My code is as following:
public class GMailSender extends Authenticator
{
private final String mailhost;
private final String password;
private final Session session;
private final String user;
public GMailSender(String username, String password)
{
this.mailhost = "smtp.gmail.com";
this.user = username;
this.password = password;
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.host", mailhost);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.debug", "true");
properties.setProperty("mail.smtp.quitwait", "false");
System.out.println("Creating session ...");
session = Session.getInstance(properties, this);
System.out.println("Session createed ...");
}
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
System.out.println("Authintecation ...");
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String dataHandler, String senderAddress, String recepeintAddress)
throws Exception
{
MimeMessage mimemessage;
mimemessage = new MimeMessage(session);
DataHandler datahandler = new DataHandler(new ByteArrayDataSource(dataHandler.getBytes(), "text/plain"));
mimemessage.setSender(new InternetAddress(senderAddress));
mimemessage.setSubject(subject);
mimemessage.setDataHandler(datahandler);
mimemessage.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recepeintAddress));
System.out.println("Sending ...");
Transport transport = session.getTransport("smtp");
transport.send(mimemessage);
System.out.println("Sent!");
}
static {
Security.addProvider(new JSSEProvider());
}
public static void main(String[] args){
System.out.println("Starting email ...");
GMailSender sender = new GMailSender("myEmail#gmail.com", "my password");
try {
sender.sendMail("Test", "alot of data", "myEmail#gmail.com", "someonesemail#gmail.com");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public final class JSSEProvider extends Provider {
private static final long serialVersionUID = 1L;
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController
.doPrivileged(new java.security.PrivilegedAction<Void>() {
#Override
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
When I run my code I got the following:
> Starting email ...
> Creating session ...
> Session createed ...
> Sending ...
> Authintecation ...
Then it takes around 10 min to return with the following:
> javax.mail.MessagingException: Could not connect to SMTP host:
> smtp.gmail.com, port: 465, response: -1
> at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1379)
> at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
> at javax.mail.Service.connect(Service.java:310)
> at javax.mail.Service.connect(Service.java:169)
> at javax.mail.Service.connect(Service.java:118)
> at javax.mail.Transport.send0(Transport.java:188)
> at javax.mail.Transport.send(Transport.java:118)
> at com.srycrm.mail.GMailSender.sendMail(GMailSender.java:66)
> at org.apache.jsp.send_jsp._jspService(send_jsp.java:85)
> at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
> at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
> at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
> at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
> at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
> at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
> at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
> at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
> at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Anyone can help me please!!
Thank you.
Ok you are using port 465, so enable ssl mail.smtp.ssl.enable to true :
properties.put("mail.smtp.ssl.enable", "true");
if it doesn;t work , then have properties.put("mail.smtp.starttls.enable", "true"); and change port to 587 and see if it helps.
Great!
Thanks for all the people that tried to help.
The Solution is a bit strange! I just downgraded my JRE and JDK to 1.6 and this solved the problem!
It might be something with the Java 1.7 enviroment.
Anyway, Thanks for all you are like always awesome :)
There's a bunch of errors in your code. Start here to fix the most common mistakes.
After that, see the JavaMail FAQ for connection debugging tips. Post the debug output here if you can't figure it out.

Fail to connect to james server localhost

I'm trying to connect to James server localhost, but I'm getting an exception
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port:25;
nested exception is:
java.net.SocketException: Network is unreachable: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1545)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:453)
at javax.mail.Service.connect(Service.java:313)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at mail.main(mail.java:78)
Caused by: java.net.SocketException: Network is unreachable: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:267)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:227)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1511)
... 7 more
The directory structure of my James Server is:
C:\apache-james-2.3.2
|
|
|
|------C:\apache-james-2.3.2\james-2.3.2
|
|------C:\apache-james-2.3.2\javamail-1.4.2
|
|------C:\apache-james-2.3.2\jaf-1.0.2
Here's the code, which is throwing an exception:
I've not changed anything in the config file of james-2.3.2 subdirectory, then why I'm
getting that exception?
Here's the code, which is throwing an exception:
// imports omitted
public class mail {
public static void main(String[] args) {
String to = "blue#localhost";
String from = "red#localhost";
String subject = "Hello";
String body = "What's up";
if ((from != null) && (to != null) && (subject != null) && (body != null)) {
try { // we have mail to send
Properties props = new Properties();
props.put("mail.host", "localhost");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("red", "red");
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
Address[] add = { new InternetAddress(to) };
message.setRecipients(Message.RecipientType.TO, add);
message.setSubject(subject);
message.setContent(body, "text/plain");
message.setText(body);
Transport.send(message);
System.out.println(" Your message to " + to + " was successfully sent.");
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
The exception is saying that localhost is unreachable. I expect that your machine does not have its loopback network address (localhost / 127.0.0.1) correctly configured.
EDIT: I assume that you are running the client and server on the same machine. If not, you cannot use localhost / 127.0.0.1.
I always try to telnet to port 25 on the mailhost, to check if the server can be reached. Try to connect to 127.0.0.1 to check if James is accepting incoming connections. I presume you have checked the logs of James for errors?
Try using the IP address 127.0.0.1 instead of the hostname 'localhost' - maybe DNS lookup on your machine is not set up properly, so that it doesn't know what the name 'localhost' means.
Open the file C:\Windows\System32\drivers\etc\hosts, and make sure it contains a line like this:
127.0.0.1 localhost
Also, try switching off your firewall or anti-virus software.
try to start apache james as root user in linux or start as
Administrator on windows. and check the server is successfully
started or not on james-server.log file in logs folder
add the host name on your hosts file
127.0.0.1 localhost
file placed
on linux /etc/hosts
on windows C:\Windows\System32\drivers\etc\hosts
and restart your server.

Categories

Resources