Fail to connect to james server localhost - java

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.

Related

SFTP with java client when keys are shared [duplicate]

This question already has an answer here:
Can we use JSch for SSH key-based communication?
(1 answer)
Closed 4 years ago.
I have two servers A and B.
I want to SFTP a file from server A to B.
Public key of server A (~/.ssh/id_rsa.pub) has been added to the ~/.ssh/authorized_keys of server B.
From command line, I can SFTP from server A to B without entering password.
However, from a Java client using library Jsch I am unable to make SFTP connection to server B and I am getting authentication error:
Error occurred during SFTP. Auth fail
com.jcraft.jsch.JSchException: Auth fail
at com.jcraft.jsch.Session.connect(Session.java:519)
at com.jcraft.jsch.Session.connect(Session.java:183)
at Main.main(Main.java:15)
Is there a way I can connect to server B for SFTP purposes using Java client without specifying password?
Below is my Java code for reference:
import com.jcraft.jsch.*;
public class Main {
public static void main(String[] args) {
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("processor", "remoteserver.myorg.com", 22);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Trying to connect...");
session.connect();
System.out.println("Connected successfully.");
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
System.out.println("Doing SFTP...");
sftpChannel.put("/tmp/test.txt", "/some/remote/folder");
System.out.println("Success");
sftpChannel.exit();
session.disconnect();
} catch (JSchException | SftpException e) {
System.err.println("Error occurred during SFTP. " + e.getMessage());
e.printStackTrace();
}
}
}
Use addIdentity() api in jsync and point to your private key file location.
Ref:
Can we use JSch for SSH key-based communication?
String privateKey = "~/.ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");

JavaMail Connection using Main Method and Some other Thread

I am trying to connect to a gmail inbox to listen to messages using the JavaMail api. I can connect fine to the mailbox when I run my program through the main method. However when I create a separate thread and run it using some other class it seems that I get the following exception.
javax.mail.MessagingException: null; nested exception is:
java.io.IOException
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:298)
at javax.mail.Service.connect(Service.java:234)
at javax.mail.Service.connect(Service.java:135)
at com.emdi.sl3.server.emailConnector.EmailListenerAcknowledge.run(Email ListenerAcknowledge.java:92)
at java.lang.Thread.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)`
My code to connect to the mailbox looks like,
import java.util.*;
import javax.mail.*;
import javax.mail.event.*;
import com.sun.mail.imap.*;
public class EmailListenerAcknowledge implements Runnable {
private Store store;
private Folder folder;
String host;
String user;
String password;
public void run() {
try {
// TODO: Set email protocol, username and password.
host = "imap.gmail.com";
user = "fdsfds";
password = "sdfsff";
String mbox = "inbox";
String frequency = "1";
System.out.println("\nTesting monitor\n");
Properties props = new Properties();
props.setProperty("mail.imap.ssl.enable", "true");
props.setProperty("mail.imap.port", "993");
// Get a Session object
Session session = Session.getInstance(props);
// Get a Store object
store = session.getStore("imap");
// Connect
store.connect(host, user, password);
System.out.println("Connected!!!");
// Open a Folder
folder = store.getFolder(mbox);
if (folder == null || !folder.exists()) {
System.out.println("Invalid folder");
System.exit(1);
}
folder.open(Folder.READ_ONLY);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I also notice that when I remove the line props.setProperty("mail.imap.port", "993"), I get a different exception (again running the program from the main method works fine),
javax.mail.MessagingException: Connection timed out: connect; nested exception is:java.net.ConnectException: Connection timed out: connect
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:298)
at javax.mail.Service.connect(Service.java:234)
at javax.mail.Service.connect(Service.java:135)
at com.emdi.sl3.server.emailConnector.EmailListener.run(Email ListenerAcknowledge.java:92)
at java.lang.Thread.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)`
I seem not to understand why running the program from the main method works fine whereas running the program from a separate thread don't work.

java.net.UnknownHostException when attempting to connect to database

I am attempting to connect to an Oracle database through Java with the Oracle JDBC driver with the following code (obscuring the host, service, user, and password):
import java.sql.*;
public class Main {
public Main () {
try {
String host = "HOST_NAME";
String port = "1521";
String service = "SERVICE_NAME";
String user = "SCHEMA_USER";
String password = "SCHEMA_PASSWORD";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" +
host +
")(PORT=" +
port +
")))(CONNECT_DATA=(SERVICE_NAME=" +
service +
")))",
user,
password);
connection.close ();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main (String args) {
new Main ();
}
}
However, I receive the following error:
java.sql.SQLException: IO Error: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:458)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:546)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:236)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:521)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.acxiom.axle.reporting.database.DatabaseConnection.connect(DatabaseConnection.java:23)
at com.acxiom.axle.reporting.Reporting.establishDatabaseConnection(Reporting.java:53)
at com.acxiom.axle.reporting.Reporting.beginReporting(Reporting.java:20)
at com.acxiom.axle.reporting.Entry.<init>(Entry.java:28)
at com.acxiom.axle.reporting.Entry.main(Entry.java:118)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:392)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:434)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:687)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:247)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1102)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:320)
... 11 more
Caused by: java.net.UnknownHostException: null
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$2.lookupAllHostAddr(Unknown Source)
at java.net.InetAddress.getAddressesFromNameService(Unknown Source)
at java.net.InetAddress.getAllByName0(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:117)
at oracle.net.nt.ConnOption.connect(ConnOption.java:133)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:370)
... 16 more
The strange thing is, I can connect to the database from PL/SQL Developer, I can ping the remote host, and I can telnet to the remote host on port 1521.
Why would only Java appear to give an UnknownHostException, but I can connect and ping the host with other applications?
EDIT: I removed "hr/hr" from the connection string above. I have tried the connection as-is with it removed and still receive the same error. I've also tried changing the connection string to match the version morgano listed in his answer, with the same result. Finally, I tried to change the port number to a port I know it's not listening on, and it still receives the same error.
The connection string is of the correct format. The problem is that the host isn't set. It's null, or perhaps the string "null". There's simply no other way to generate the error message java.net.UnknownHostException: null
In your sample code, you write String host = "HOST_NAME";. This makes it look like in your real code you are assigning a constant string to the variable host. However, I'm going to stick my neck out and say that in your real code you are not doing this. You are looking up the host name from somewhere, this lookup fails for some reason, you don't check this, and hence you pass a null value into the connection string.
Your JDBC url is wrong, according to the documentation it should be something like:
jdbc:oracle:driver_type:[username/password]#//host_name:port_number/service_name
In your case your code would be something like:
import java.sql.*;
public class Main {
public Main () {
try {
String host = "HOST_NAME";
String port = "1521";
String service = "SERVICE_NAME";
String user = "SCHEMA_USER";
String password = "SCHEMA_PASSWORD";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:#//" + host
+ ":" + port + "/" + service, user, password);
connection.close ();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main (String args) {
new Main ();
}
}

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.

JavaMail SocketException: Connection reset

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.

Categories

Resources