Unable to POST to URL from within a client's network - java

PostMethod post = new PostMethod(strURL);
try {
post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
post.setRequestHeader("Content-type","text/xml; charset=ISO-8859-1");
HttpClient httpclient = new HttpClient();
HostConfiguration config = httpclient.getHostConfiguration();
config.setProxy("zz.zz.zz.zz", 1111);
String username = "username";
String password = "password";
Credentials credentials = new UsernamePasswordCredentials(username, password);
AuthScope authScope = new AuthScope("zz.zz.zz.zz", 1111);
httpclient.getState().setProxyCredentials(authScope, credentials);
int result = httpclient.executeMethod(post);
The above code works fine when I am outside client network. Could someone please check if anything wrong in the code
Dec 29, 2015 2:34:26 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
Dec 29, 2015 2:34:26 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
java.net.ConnectException: Connection timed out: 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)

Related

Java Mongo driver unintentionally connects to localhost

I downloaded the mongo driver for java (mongo-java-driver-3.12.4.jar) and connect a MongoClient to a remote host.
The connection to the remote host gets successfully established.
But additionally to this intended connection, I have error messages in the log that indicate, that the driver tries to connect to the localhost, on which no mongo db runs:
09:52:52,082 INFO [org.mongodb.driver.cluster] (default task-1) Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
09:52:52,843 INFO [org.mongodb.driver.cluster] (default task-1) Cluster created with settings {hosts=[remoteHost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
09:52:52,879 INFO [org.mongodb.driver.cluster] (default task-1) Cluster description not yet available. Waiting for 30000 ms before timing out
09:52:53,159 INFO [org.mongodb.driver.connection] (cluster-ClusterId{value='5ef457d443933341aa40d5f3', description='null'}-remoteHost:27017) Opened connection [connectionId{localValue:2, serverValue:373}] to remoteHost:27017
09:52:53,219 INFO [org.mongodb.driver.cluster] (cluster-ClusterId{value='5ef457d443933341aa40d5f3', description='null'}-remoteHost:27017) Monitor thread successfully connected to server with description ServerDescription{address=remoteHost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 18]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=54329200}
09:52:53,707 INFO [org.mongodb.driver.connection] (default task-1) Opened connection [connectionId{localValue:3, serverValue:374}] to remoteHost:27017
09:52:54,198 INFO [org.mongodb.driver.cluster] (cluster-ClusterId{value='5ef457d443933341aa40d5f2', description='null'}-127.0.0.1:27017) Exception in monitor thread while connecting to server 127.0.0.1:27017: com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70)
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:128)
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117)
at java.lang.Thread.run(Unknown Source)
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 com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:64)
at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79)
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65)
... 3 more
I use MongoClient(ServerAddress addr, MongoCredential credential, MongoClientOptions options) to set the connection settings to the remote host. I use at no point localhost or 127.0.0.1.
How come that the driver tries to connect to localhost and more important how can I disable this behaviour? :)
Edit:
Here is how I initialize the MongoClient:
{
...
String connectionString = "mongodb://user:password#remoteHost:27017/";
MongoClientURI clientURI = new MongoClientURI(connectionString);
mongoClient = new MongoClient(createServerAddress(clientURI.getHosts().get(0)), clientURI.getCredentials(), addOptions(clientURI.getOptions()));
MongoDatabase db = mongoClient.getDatabase(dbName);
...
}
private ServerAddress createServerAddress(String host) {
if (host.contains(":")) {
String[] parts = host.split(":");
return new ServerAddress(parts[0], Integer.parseInt(parts[1]));
} else {
return new ServerAddress(host);
}
}
private MongoClientOptions addOptions(MongoClientOptions options) {
Builder builder = new Builder(options);
File ksFile = new File(config.getKeystorePath()));
char[] password = config.getKeystorePassword()).toCharArray();
if (ksFile.exists()) {
try {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
try (FileInputStream fis = new FileInputStream(ksFile)) {
ks.load(fis, password);
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
builder.sslEnabled(true);
builder.sslContext(sslContext);
} catch (Exception e) {
logger.error("TLS initialization failed: ", e.getCause());
}
}
return builder.build();
}

MailConnectException when sending email with JavaMail

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?

How to invoke the appium server and emulator via Java code in windows machine

I need to start up the Appium server and emulator through the Java code with Selenium. When I run the Java program the startappiumserver method is working well. When it comes to startApplication method (creation of new remoteWebDriver) I am getting an error like:
Exception in thread "main" org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
CODE:
package startup;
import io.appium.java_client.AppiumDriver;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class Startup {
static RemoteWebDriver driver = null;
public void startAppiumServer() throws IOException, InterruptedException {
CommandLine command = new CommandLine("cmd");
command.addArgument("/c");
command.addArgument("D:\\SOFTWARES\\AppiumForWindows-1.2.4.1\\Appium\\node.exe");
command.addArgument("D:\\SOFTWARES\\AppiumForWindows-1.2.4.1\\Appium\\node_modules\\appium\\lib\\appium.js");
command.addArgument("--address", false);
command.addArgument("127.0.0.1");
command.addArgument("--port", false);
command.addArgument("4723");
command.addArgument("--full-reset", false);
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
executor.execute(command, resultHandler);
}
public void stopAppiumServer() throws IOException {
CommandLine command = new CommandLine("cmd");
command.addArgument("/c");
command.addArgument("Taskkill /F /IM node.exe");
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
executor.execute(command, resultHandler);
}
public static void startApplication() throws Exception{
System.out.println("application has started...................");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
capabilities.setCapability("deviceName","emulator-5554");
capabilities.setCapability("platformVersion","4.3");
capabilities.setCapability("platformName","Android");
capabilities.setCapability("app","D:/SOFTWARES/Apks/autoInsurancelatest.apk");
driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
System.out.println("Appium SetUp for Android is successful and Appium Driver is launched successfully");
}
public static void main(String as[]) throws Exception
{
Startup aps = new Startup();
System.out.println("Starting Server...");
aps.startAppiumServer();
System.out.println("Server Started....");
try{Thread.sleep(5000);}catch(Exception e){}
Startup.startApplication();
try{Thread.sleep(5000);}catch(Exception e){}
System.out.println("Stopping Server");
aps.stopAppiumServer();
System.out.println("Server Stopped");
}
}
I found that there is some port error when it is creating the new remotewebdriver. I don't find what is missing in the code.
Help me out from this issue. Suggestions and comments are welcome.
Console log:
Exception in thread "main"
org.openqa.selenium.remote.UnreachableBrowserException: Could not
start a new session. Possible causes are invalid address of the remote
server or browser start-up failure. Build info: version: '2.45.0',
revision: '32a636c', time: '2015-03-05 22:01:35' System info: host:
'IMPC1388', ip: '172.16.11.2', os.name: 'Windows 7', os.arch: 'amd64',
os.version: '6.1', java.version: '1.7.0_51' Driver info:
driver.version: RemoteWebDriver at
org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:593)
at
org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:240)
at
org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:126)
at
org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:153)
at startup.Startup.startApplication(Startup.java:65) at
startup.Startup.main(Startup.java:79) Caused by:
org.apache.http.conn.HttpHostConnectException: Connect to
127.0.0.1:4723 [/127.0.0.1] failed: Connection refused: connect at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:142)
at
org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:319)
at
org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
at
org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
at
org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at
org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at
org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at
org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at
org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72)
at
org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
at
org.openqa.selenium.remote.internal.ApacheHttpClient.fallBackExecute(ApacheHttpClient.java:126)
at
org.openqa.selenium.remote.internal.ApacheHttpClient.execute(ApacheHttpClient.java:72)
at
org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:133)
at
org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:572)
... 5 more Caused by: java.net.ConnectException: Connection refused:
connect at java.net.DualStackPlainSocketImpl.waitForConnect(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.http.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:72)
at
org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:125)
... 18 more
Could you please do the following changes in your code:
1) Take the appium.js from bin directory rather than from lib
2) Add the following
command.addArgument("--bootstrap-port",false);
command.addArgument("4724",false);
command.addArgument("--selendroid-port",false);
command.addArgument("8082",false);
Also please be sure that you take enough time until appium will start.
Please see this answer for the details.
If the problem will still appear, could you please copy the command string that your code build and try to launch it from cmd.

mail sending in java( I am using java mail api for this)

I have written code for mail sending in java( I am using java mail api for this). Here uerId and Password(For authentication purpose) I am giving of my domain because I want my email server to be use.
The Problem is, when I am sending mail from localhost it is working fine, But when I am deploying on my live staging server,and trying to send the mail, it is giving following exception:
Apr 08, 2015 7:32:26 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Could not connect to SMTP host: mail.dreamdays.ae, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out. Failed messages: javax.mail.MessagingException: Could not connect to SMTP host: mail.dreamdays.ae, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out; message exceptions (1) are:
Failed message 1: javax.mail.MessagingException: Could not connect to SMTP host: mail.dreamdays.ae, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out] with root cause
java.net.ConnectException: Connection timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at javax.mail.Service.connect(Service.java:291)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:389)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:340)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:336)
at com.service.MailMail.sendMail(MailMail.java:34)
at com.controller.UserController.saveUser(UserController.java:143)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:647)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:603)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:950)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:859)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:883)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:792)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.ajp.AjpAprProcessor.process(AjpAprProcessor.java:197)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Code is below, Please check it and help me out.
public class MailDao {
private static final String SMTP_HOST_NAME = "mail.dreamdays.ae";
private static final String SMTP_AUTH_USER ="cpverma#dreamdays.ae";
private static final String SMTP_AUTH_PWD = "********";
public void postMail(String emailTo, String recipients[ ], String subject, String message , String from) throws MessagingException, AuthenticationFailedException
{
boolean debug = false;
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
try{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
// session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
// InternetAddress[] addressTo = new InternetAddress[recipients.length];
InternetAddress[] emailToArr = new InternetAddress[1];
emailToArr[0] = new InternetAddress(emailTo);
System.out.println("emailTo---"+emailTo);
msg.setRecipients(Message.RecipientType.TO, emailToArr);
// if(recipients.length >0)
// msg.setRecipients(Message.RecipientType.CC, emailToArr);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/html");
Transport.send(msg);
System.out.println("emailTo3---"+emailTo);
}catch(Exception e){
System.out.println("mail sending failed:--"+e);
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
}
The exception means that connection to the host is timing out which might be because of the host not being available. So verify whether the connection to the host is possible by using telnet
telnet mail.dreamdays.ae 25
Also you are able to connect using telnet then there should not be any problem in sending mail.
So ensure that the host server is up and available in the first place

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...

Categories

Resources