MailConnectException when sending email with JavaMail - java

I am trying to send an email with JavaMail following this tutorial:
http://www.tutorialspoint.com/java/java_sending_email.htm
This is my code:
public void sendAccountActivationEmail()
{
String to = "myemail#gmail.com";
String from = "myemail#gmail.com";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Account activation");
message.setContent("<h1>This is actual message</h1>", "text/html" );
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
However when running this method I get the following exception:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: 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: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 com.myproject.managed.UserRegistrationController.sendAccountActivationEmail(UserRegistrationController.java:161)
...
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.TwoStacksPlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(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:331)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2066)
... 58 more
Any idea of what should I do?

Related

JDBC Mysql SSH Connection, Url cannot be null [duplicate]

This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 4 years ago.
I am creating an application and I need to connect to a remote MySql DB. I am using JSch to connect via SSH. I am able to connect via JSch, however when I try to connect to my database I keep getting errors.
public void connectSSH() {
int lport = 5656;
String rhost = "host"; //not actual host
String host = "host"; //not actual host
int rport = 3306;
String user = "user"; //not actual user
String password = "*********";
String dbuserName = "user"; //not actual user
String dbpassword = "********";
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:" + rport + "?user=" + dbuserName + "&password=" + dbpassword + "&useSSL=true";
Connection conn = null;
Session session = null;
try {
//Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
int assinged_port = session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);
System.out.println("Port Forwarded");
//mysql database connectivity
Class.forName(driverName).newInstance();
conn = DriverManager.getConnection(url);
System.out.println("Database connection established");
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (conn != null && !conn.isClosed()) {
System.out.println("Closing Database Connection");
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
if (session != null && session.isConnected()) {
System.out.println("Closing SSH Connection");
session.disconnect();
}
}
}
Output:
Connected
localhost:5656 -> rhost:3306
Port Forwarded
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago.The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:990)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:342)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2188)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2221)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2016)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:776)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:386)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at com.ej.ozyazgan.classes.SqlHelper.connectSSH(SqlHelper.java:176)
at com.ej.ozyazgan.classes.MainController.initialize(MainController.java:52)
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:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2566)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at com.ej.ozyazgan.classes.Main.start(Main.java:13)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused: 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 com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:211)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:301)
... 43 more
Closing SSH Connection
The url cannot be null
Caused by: java.net.ConnectException: Connection refused: connect
You didn't read the stack trace. The actual error here is 'connection refused'. The port in the JDBC URL should be the local SSH forwarding port, not the remote port.

Java Email SMTP & TSL, Error Can't sending email

I have problem with Java Email using SMTP & TSl, please help me resolve this problem. I think the problem was Transport, but I'm not sure. Below is my code and error snippets, please help me find my mistake and solution.
TSLEmail.class
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
public class TSLEmail
{
public static void main(String[] args)
{
final String fromEmail = "mail#gmail.com"; //requires valid
gmail id
final String password = "mypass12"; // correct password for gmail id
final String toEmail = "recipients#gmail.com"; // can be any email id
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "10.20.200.220"); //SMTP Host
props.put("mail.user", "user12");
//props.put("mail.password", password);
props.put("mail.smtp.port", "587"); //TLS Port
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
//create Authenticator object to pass in Session.getInstance argument
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication
getPasswordAuthentication() {
return new
PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getInstance(props, auth);
EmailUtil.sendEmail(session, toEmail,"TLSEmail Testing Subject",
"TLSEmail Testing Body");
}
}
EmailUtil.class
import java.util.Date;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailUtil
{
public static void sendEmail(Session session, String toEmail, String
subject, String body)
{
try
{
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("mail#gmail.com"));
msg.setReplyTo(InternetAddress.parse("recipients#gmail.com"));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
The Results(ERROR):
TLSEmail Start
Message is ready
javax.mail.MessagingException: Can't send command to SMTP host;
nested exception is:
javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to
find valid certification path to requested target
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1564)
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1551)
at com.sun.mail.smtp.SMTPTransport.ehlo(SMTPTransport.java:935)
at
com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:426)
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.bca.controller.EmailUtil.sendEmail(EmailUtil.java:35)
at com.bca.controller.TSLEmail.main(TSLEmail.java:34)
Caused by: javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find
valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown
Source)
at sun.security.ssl.SSLSocketImpl.writeRecord(Unknown Source)
at sun.security.ssl.AppOutputStream.write(Unknown Source)
at com.sun.mail.util.TraceOutputStream.write(TraceOutputStream.java:114)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1562)
... 10 more
Caused by: sun.security.validator.ValidatorException: PKIX path building
failed: sun.security.provider.certpath.SunCertPathBuilderException: unable
to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown
Source)
... 22 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown
Source)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown
Source)
at java.security.cert.CertPathBuilder.build(Unknown Source)
... 28 more
Please help me find an simple and certain solution for my problem.
Thank You
It sounds like you need to add the certificates returned by the Server into your JRE's truststore,
There are many good articles that explain how to do this, including:
Java Keytool Essentials: Working with Java Keystores
If this is a web app (for example, Tomcat or JBoss), then do this at the server level (instead of your JRE).
Add this property too. It worked for me.
props.put("mail.smtp.ssl.trust", Smtp_host);

RMI with different PCs

I am learning RMI and I made a basic program that uses codebase.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class Server implements sInterface,s2int {
public void go()
{
System.out.println("GO");
}
public void doIt()
{
}
public static void main(String[] args)
{
if(System.getSecurityManager()==null)
{
System.setSecurityManager(new SecurityManager());
}
try
{
System.setProperty("java.rmi.server.hostname","helios");
String s = "SERVER";
Registry r = LocateRegistry.getRegistry();
sInterface stub = (sInterface) UnicastRemoteObject.exportObject(new Server(),0);
r.rebind(s,stub);
}catch(Exception x){x.printStackTrace();}
}
}
Client:
public class Client {
public static void main(String[] args)
{
if(System.getSecurityManager()==null)
{
System.setSecurityManager(new SecurityManager());
}
try{
String name = "SERVER";
Registry r = LocateRegistry.getRegistry(args[0]);
sInterface inf = (sInterface)r.lookup(name);
inf.go();
}catch(Exception x)
{
x.printStackTrace();
}
}
}
Client does not have 's2int' interface and that is downloaded from the codebase.
The commands used to start the server and the client modules are as follows:
java -Djava.rmi.server.codebase=http://helios/~owner/rmi.jar
-Djava.security.policy=server.policy Server
java -Djava.security.policy=client.policy
-Djava.rmi.server.codebase=http://helios/~owner/
-Djava.rmi.server.hostname=helios Client localhost
Now,this works when both the server and client are on the same PC, but when I tried running it on a different PC on the same network, I got a
java.rmi.ConnectException: Connection refused to host: localhost; nested exception is:
java.net.ConnectException: Connection refused: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.createConnection(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.newConnection(Unknown Source)
at sun.rmi.server.UnicastRef.newCall(Unknown Source)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at Client.main(Client.java:20)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(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 java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at
sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(Unknown S
ource) at
sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(Unknown S
ource)
... 6 more
I am not very knowledgeable when it comes to networking. Can anyone explain why it's not working?
Your client is looking up the wrong Registry. It needs to lookup the Registry at the server host, not its own localhost.

Getting exception while sending a mail using javax mail

Below are the methods which I am using to send an email
public static void main(String[] args) {
final String fromEmail = "abc#gmail.com"; //requires valid gmail id
final String password = "123456"; // correct password for gmail id
final String toEmail = "xyz#gmail.com,ghi#gmail.com";
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getInstance(props, auth);
sendEmail(session, toEmail,"TLSEmail Testing Subject", "TLSEmail Testing Body");
}
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
{
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
String content = getContent();
msg.setSubject(subject, "UTF-8");
msg.setContent(content.toString(), "text/html");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport transport = session.getTransport("smtp");
transport.connect();
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
transport.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
And this is the exception which I suddenly I started getting
javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: timestamp check failed
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1999)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:709)
at javax.mail.Service.connect(Service.java:386)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at com.sharique.mail.util.EmailUtil.sendEmail(EmailUtil.java:45)
at com.sharique.main.TestMain.main(TestMain.java:38)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: timestamp check failed
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:543)
at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:480)
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1994)
... 6 more
Caused by: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: timestamp check failed
at sun.security.validator.PKIXValidator.doValidate(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 17 more
Caused by: java.security.cert.CertPathValidatorException: timestamp check failed
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(Unknown Source)
at sun.security.provider.certpath.PKIXCertPathValidator.doValidate(Unknown Source)
at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(Unknown Source)
at java.security.cert.CertPathValidator.validate(Unknown Source)
... 23 more
Caused by: java.security.cert.CertificateExpiredException: NotAfter: Sat Apr 04 20:45:55 IST 2015
at sun.security.x509.CertificateValidity.valid(Unknown Source)
at sun.security.x509.X509CertImpl.checkValidity(Unknown Source)
at sun.security.provider.certpath.BasicChecker.verifyTimestamp(Unknown Source)
at sun.security.provider.certpath.BasicChecker.check(Unknown Source)
... 27 more
Code was working fine without any errors, but just few minutes ago it started giving me the above exception. I didn't change the code, so how it is coming I don't know. Please let me know of how to resolve this.
the solution is add that line props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
The exception clearly states what is causing it.
The certificate of your mail server seems to have expired, try accessing the server using a browser and check its certificate or try getting any page on the server using wget, you should receive a certificate error.
Caused by: java.security.cert.CertPathValidatorException: timestamp check failed
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(Unknown Source)
at sun.security.provider.certpath.PKIXCertPathValidator.doValidate(Unknown Source)
at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(Unknown Source)
at java.security.cert.CertPathValidator.validate(Unknown Source)
... 23 more
Caused by: java.security.cert.CertificateExpiredException: NotAfter: Sat Apr 04 20:45:55 IST 2015
at sun.security.x509.CertificateValidity.valid(Unknown Source)
at sun.security.x509.X509CertImpl.checkValidity(Unknown Source)
at sun.security.provider.certpath.BasicChecker.verifyTimestamp(Unknown Source)
at sun.security.provider.certpath.BasicChecker.check(Unknown Source)
... 27 more
I was having the exact same issue as well. (Was even showing the same "Not After" message and same time as yours). After changing some configurations around, it started working again, however, I went back to my original configuration and it worked. I believe this was a hiccup in Gmail, which they have since fixed. Have you tried using port 465? That's the port I'm using which is working for me.
Also, here is my config that seems to be sending emails without the exception (This is config in my grails application, but you should be able to port these over to your Java code):
grails.mail.host = "smtp.gmail.com"
grails.mail.port = 465
grails.mail.username = "xxxx#gmail.com"
grails.mail.password = "xxxxxxx"
grails.mail.props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
One of my app begin to send mail again automatically without any change in the code...

FTPClient Connection refused

I am trying to copy file through FTPClient and testing in my local system
My code is like this with my IPv4 address as input for host
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPUploader {
FTPClient ftp = null;
public FTPUploader(String host, String user, String pwd) throws Exception{
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect(host);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login(user, pwd);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
}
public void uploadFile(String localFileFullName, String fileName, String hostDir)
throws Exception {
try(InputStream input = new FileInputStream(new File(localFileFullName))){
this.ftp.storeFile(hostDir + fileName, input);
}
}
public void disconnect(){
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException f) {
// DO NOTHING
}
}
}
public static void main(String[] args) {
try{
System.out.println("Start");
FTPUploader ftpUploader = new FTPUploader("10.66.***.***", "username", "password");
ftpUploader.uploadFile("D:/Venkatesh.pptx", "65.pptx", "C:/Users/VENKATESH/Desktop");
ftpUploader.disconnect();
System.out.println("Done");
}catch(Exception exception){
exception.printStackTrace();
}
}
}
Now by this, Iam getting the following Exception
Start
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:168)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:189)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:278)
at fileTransfer.FTPUploader.<init>(FTPUploader.java:21)
at fileTransfer.FTPUploader.main(FTPUploader.java:51)
What is the mistake iam doing ????
The program is absolutely fine.
Problem is at the server side.
Exception here is :
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
The error is because of wrong credentials ( or ) the server is not started.
The file is transferred after restarting the server :)

Categories

Resources