following is my code to send mail:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public void sendMail(String m_from,String m_to,String m_subject,String m_body){
try {
Session m_Session;
Message m_simpleMessage;
InternetAddress m_fromAddress;
InternetAddress m_toAddress;
Properties m_properties;
m_properties = new Properties();
m_properties.put("mail.smtp.host", "usdc2spam2.slingmedia.com");
m_properties.put("mail.smtp.socketFactory.port", "465");
m_properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
m_properties.put("mail.smtp.auth", "true");
m_properties.put("mail.smtp.port", "9000");
m_Session=Session.getDefaultInstance(m_properties,new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("aaaaa","bbbbb#1"); // username and the password
}
});
m_simpleMessage = new MimeMessage(m_Session);
m_fromAddress = new InternetAddress(m_from);
m_toAddress = new InternetAddress(m_to);
m_simpleMessage.setFrom(m_fromAddress);
m_simpleMessage.setRecipient(RecipientType.TO, m_toAddress);
m_simpleMessage.setSubject(m_subject);
m_simpleMessage.setContent(m_body, "text/html");
//m_simpleMessage.setContent(m_body,"text/plain");
Transport.send(m_simpleMessage);
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
SendMail send_mail = new SendMail();
String empName = "xxxxx";
String title ="<b>Hi !"+empName+"</b>";
send_mail.sendMail("123erft#slingmedia.com", "abz#gmail.com", "Please apply for leave for the following dates", title+"<br>by<br><b>HR<b>");
}
}
but when i run the code it gives me the following exception.
javax.mail.MessagingException: Could not connect to SMTP host: usdc2spam2.slingmedia.com, port: 9000;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
at javax.mail.Service.connect(Service.java:317)
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 samples.SendMail.sendMail(SendMail.java:46)
at samples.SendMail.main(SendMail.java:55)
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:288)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
when i ping this usdc2spam2.slingmedia.com it gives me reply without any problem. I am using windows 7
Please help me to resolve this.
This is these two lines which was casting me the problem :
m_properties.put("mail.smtp.socketFactory.port", "465");
m_properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
and added this line :
m_properties.put("mail.smtp.starttls.enable", "true");
After removing and adding the above lines of code it worked fine.
What causes your problem is right there in the stack trace:
java.net.ConnectException: Connection refused: connect
do you need a password to connect to the SMTP server? Are you sure you are using the right settings (as in port number)? Are you behind a proxy or a firewall? Can you use those settings in a regular mail program (e.g. Thunderbird) and send mails?
This exception usually occurs when there is no service listening on the port you are trying to connect to.
Try to connect using putty or telnet. I can bet you will get the same error.
Verify these things:
Host name and port you're trying to connect to,
The server is listening correctly, and
There's no firewall blocking the connection.
Try to add port 9000 to your inbound rules in your windows firewall.
Related
I am trying to make a simple program that connects two computers; one as a server and the other one as a client, but when I run the client program I get the following error:
Connection refused to host: 127.0.0.1; nested exception is:
java.net.ConnectException: Connection refused
java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is:
java.net.ConnectException: Connection refused
at java.rmi/sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:626)
at java.rmi/sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:217)
at java.rmi/sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:204)
at java.rmi/sun.rmi.server.UnicastRef.newCall(UnicastRef.java:345)
at java.rmi/sun.rmi.registry.RegistryImpl_Stub.lookup(RegistryImpl_Stub.java:116)
at clienteRMI.main(clienteRMI.java:17)
Caused by: java.net.ConnectException: Connection refused
at java.base/sun.nio.ch.Net.connect0(Native Method)
at java.base/sun.nio.ch.Net.connect(Net.java:579)
at java.base/sun.nio.ch.Net.connect(Net.java:568)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:576)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
at java.base/java.net.Socket.connect(Socket.java:666)
at java.base/java.net.Socket.connect(Socket.java:600)
at java.base/java.net.Socket.<init>(Socket.java:509)
at java.base/java.net.Socket.<init>(Socket.java:289)
at java.rmi/sun.rmi.transport.tcp.TCPDirectSocketFactory.createSocket(TCPDirectSocketFactory.java:40)
at java.rmi/sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:620)
Reading I have found the error may be the /etc/hosts file in the server, but I don't think something is wrong.
My /etc/hosts file:
127.0.0.1 localhost
::1 localhost
127.0.0.1 archjoni.localhost archjoni
I have also tried to write the IP of my server in the client java file before my registry by writing
System.setProperty("java.rmi.server.hostname", "192.168.1.13");
However, the problem remains the same.
My server java file:
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
/**
* Servidor
*/
public class servidorRMI {
public static void main(String[] args) {
try {
Registry rmi = LocateRegistry.createRegistry(8080);
rmi.rebind("Chat", (Remote) new implementacionChat());
System.out.println("Servidor activo");
} catch (Exception e) {
e.printStackTrace();
}
}
}
My client java file:
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import javax.swing.JOptionPane;
/**
* clienteRMI
*/
public class clienteRMI {
public static void main(String[] args) {
try {
String nombre = JOptionPane.showInputDialog("Ingresa tu nombre");
String nom = nombre;
System.setProperty("java.rmi.server.hostname", "192.168.1.13");
Registry rmii = LocateRegistry.getRegistry(8080);
chatServidor servidor = (chatServidor) rmii.lookup("Chat");
new Thread(new implementacionChatCliente(nom, servidor)).start();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
I don't know if it may be relevant but when I try the program with the localhost in the program work fine, the issue is that it takes my localhost IP when I try to connect to another computer.
Another thing to note is that both the server and the client are on Linux.
Why java is showing this output for every port connections And is it require any thing like basic frame or package in java other than these.i am working on basic server client program first is client and second is server.I tried basic code for only connection.but it shows this output every time
import java.io.*;
import java.net.*;
class DateClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
BufferedReader in=new BufferedReader(new InputStreamReader(soc.getInputStream() ));
System.out.println(in.readLine());
}
}
import java.net.*;
import java.io.*;
import java.util.*;
class DateServer
{
public static void main(String args[]) throws Exception
{
ServerSocket s=new ServerSocket(5217);
while(true)
{
System.out.println("Waiting For Connection ...");
Socket soc=s.accept();
DataOutputStream out=new DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date: " + (new Date()).toString() + "\n");
out.close();
soc.close();
}
}
}
THIS IS OUTPUT
output:=
Exception in thread "main" java.net.ConnectException: Connection timed out: conn
ect
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 DateClient.main(DateClient.java:8)
You are using the DNS resolver to get the local hostname, and you encounter a timeout when connecting to it, so:
either your DNS resolver is configured to a host that is down or filtered by a firewall,
or the DNS resolver resolves the local host name to an IP that is not the one of your server and is down or filtered by a firewall.
These are the two main cases for which you may have such a timeout, instead of a host unreachable or port unreachable error.
So, replace the line:
Socket soc = new Socket(InetAddress.getLocalHost(),5217);
by this one:
Socket soc = new Socket(InetAddress.getLoopbackAddress(), 5217);
to solve your problem.
I have a web application developed with "pure" JSP, Servlet and Hibernate. It is also working with Java Mail. The Java mail function is working almost every machine we tested here, until today. It didn't work on the deployment server (it is actually a windows 7 PC I think bcs it has a GUI). It gave me the below error
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: mail.xxx.com, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2053)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:69
7)
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 javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at RemindeWorker.Listener.MailClient.sendEmail(MailClient.java:65)
at Filter.AuthenticationFilter_Level1.doFilter(AuthenticationFilter_Leve
l1.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
alve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
alve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(Authentica
torBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
ava:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
ava:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:
950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
ve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.jav
a:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp
11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(
AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoin
t.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.
java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskTh
read.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketI
mpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.ja
va:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocket
Impl.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:312)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:236)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2019)
... 25 more
Level1 executed
NUM is: 1
Below is my Code.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package RemindeWorker.Listener;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* #author Yohan
*/
public class MailClient
{
public void sendEmail(final String userName, final String password, final String host, final String html, final List<String>emails, String subject) throws MessagingException
{
System.out.println("User Name: "+userName);
System.out.println("Password: "+password);
System.out.println("Host: "+host);
// String host="mail.xxx.com";
// final String user="abc#xxx.com";//change accordingly
// final String password="knight55";//change accordingly
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName,password);
}
});
if(!emails.isEmpty())
{
//Compose the message
InternetAddress[] address = new InternetAddress[emails.size()];
for (int i = 0; i < emails.size(); i++) {
address[i] = new InternetAddress(emails.get(i));
}
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(userName));
message.setRecipients(Message.RecipientType.TO, address);
message.setSubject(subject);
message.setContent(html,"text/html");
//send the message
Transport.send(message);
System.out.println("message sent successfully...");
}
else
{
System.out.println("No Recieptions");
}
}
}
What kind of thing is stopping my application from sending emails? The sever is having JRE 8 and XAMPP. Server admin says the firewall is turned off!
The issue was that port 25 was blocked in the server by somehow. The default port for SMTP is port 25. I changed the port for the Java mail using Properties and it worked.
I'm trying to upload a file via Secure FTP with org.apache.commons.net.ftp.FTPClient but I receive "java.net.NoRouteToHostException: No route to host" when connecting. The host is pingable and I can even read/write files with my FTP user via Filezilla SFTP connection to it. No firewall active in my router.
What could be the problem?
My specs: Mint 17 x64, Java 7, router Netgear DGND4000 (maybe this help)
This is the code:
package it.eproject.pdf;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
public class Test {
public static void main(String[] args) {
System.out.println("Start upload file");
String sourceFile = "pdf/d00001.pdf";
String pdfName = "d00001.pdf";
String pdfDestFolder = "/pdf";
String ftpHost = "itsa.pingable.host";
String ftpUsername = "username";
String ftpPassword = "password";
FTPClient ftp = new FTPClient();
try {
ftp.setConnectTimeout(5000);
ftp.connect(ftpHost);
ftp.login(ftpUsername, ftpPassword);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
InputStream input = new FileInputStream(new File(pdfName));
ftp.storeFile(pdfDestFolder + pdfName, input);
ftp.logout();
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
and this the exception:
java.net.NoRouteToHostException: No route to host
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 org.apache.commons.net.SocketClient.connect(SocketClient.java:182)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:203)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:296)
at it.eproject.pdf.Test.main(Test.java:26)
SFTP (Secure FTP) is not the same as FTPS (FTP over SSL). Make sure you're not mixing apples and oranges.
I suppose Apache Commons libs does not provide SFTP APIs, so I switched to JCraft Jsch (http://www.jcraft.com/jsch/) and it works like a charm.
I have tried to connect to an https url using sample Java code I found on the web:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
public class SSLClientTest {
public static void main(String[] args) {
try {
URL hp = new URL("https://godaddy.com");
//URL hp = new URL("https://127.0.0.1:8443");
//URL hp = new URL("https://www.google.com/");
HttpsURLConnection hpCon = (HttpsURLConnection) hp.openConnection();
System.out.println("after connection made:");
int responseCode = hpCon.getResponseCode();
System.out.println("responseCode:" + responseCode);
boolean isProxy = hpCon.usingProxy();
System.out.println("is using proxy:" + isProxy);
InputStream obj = hpCon.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(obj));
String s;
while ((s = br.readLine()) != null) {
System.out.println("content >>" + s);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
but get various error messages that I cannot resolve or resolve with any of the many internet posts on these error messages. How can I connect to an https url, ssl, with Java?
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1902)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
...
Caused by: java.security.cert.CertificateException: No subject alternative names present
at sun.security.util.HostnameChecker.matchIP(HostnameChecker.java:142)
at sun.security.util.HostnameChecker.match(HostnameChecker.java:91)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:347)
at
... 13 more
and
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:946)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1328)
...
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at sun.security.ssl.InputRecord.read(InputRecord.java:352)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
... 10 more
...
Caused by: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:946)
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 sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:515)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1299)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at SSLClientTest.print_https_cert(SSLClientTest.java:56)
at SSLClientTest.main(SSLClientTest.java:21)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at sun.security.ssl.InputRecord.read(InputRecord.java:352)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
... 10 more