What is blocking my Java mail? - java

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.

Related

How connect to IBM MQ using Jms

Please help me.
I can't send a normal hello world to the queue. Because it gives an authorization error. The fact is that the connection to the queue manager is carried out through the user, a password is not needed for it. I can't figure out what exactly I'm doing wrong.
import javax.jms.*;
import javax.jms.Message;
import com.ibm.mq.jms.*;
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.jms.internal.JmsFactoryFactoryImpl;
import com.ibm.msg.client.wmq.WMQConstants;
import org.apache.camel.Producer;
public class SenderMQ {
public static void main(String[] args){
String QMName = "";
String requstQueueName = "";
try {
JmsFactoryFactory jff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
JmsConnectionFactory jcf = jff.createConnectionFactory();
jcf.setStringProperty(WMQConstants.WMQ_HOST_NAME, host);
jcf.setIntProperty(WMQConstants.WMQ_PORT, 1414);
jcf.setStringProperty(WMQConstants.WMQ_CHANNEL,"SYSTEM.ADMIN.SVRCONN");
jcf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE,WMQConstants.WMQ_CM_CLIENT);
jcf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER,"N_QM");
jcf.setStringProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, String.valueOf(true));
jcf.setStringProperty(WMQConstants.USERID, "admin");
jcf.setStringProperty(WMQConstants.PASSWORD, null);
Connection connection = jcf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("queue://EGG_TEST_IN");
MessageProducer producer = session.createProducer(destination);
long uniqueNUmber = System.currentTimeMillis()%1000;
String mess_xml = "<?xml version=\"1.0\" encoding=\"UTF8\"?><RequestMessage xmlns=\"MQMessage\" processID=\"FD12C7B4617F11ecB2E0005056AD53F8\" serviceID=\"SMEV3_ESIA3_IM\" departmentID=\"0\" systemID=\"SBL_FR:ULBSFCNT\"><Request>PFRvU21ldiBIRVhDb2RlPSJTdHJpbmciIHhtbG5zOm5zND0iaHR0cDovL3NjaGVtYXMub3JhY2xlLmNvbS9icGVsL2V4dGVuc2lvbiIgeG1sbnM6bnM2PSJ1cm46Ly9taW5jb21zdnlhei9jb21tb25zL2ludGVncmF0aW9uX21vZHVsZV90eXBlcy8xLjAuMSIgeG1sbnM6bnM1PSJ1cm46Ly94LWFydGVmYWN0cy1zbWV2LWdvdi1ydS9zZXJ2aWNlcy9tZXNzYWdlLWV4Y2hhbmdlL3R5cGVzLzEuMSIgeG1sbnM6bnM3PSJ1cm46Ly9taW5jb21zdnlhei9pbnRlcmdyYXRpb25fbW9kdWxlLzEuMC4xIiB4bWxuczp0bnM9Imh0dHA6Ly93d3cuYnNzeXMuY29tL3Byb2R1Y3RzL2Jzcy1lZ2cvU01FVjNfRVNJQTNfSU0iIHhtbG5zPSJodHRwOi8vd3d3LmJzc3lzLmNvbS9wcm9kdWN0cy9ic3MtZWdnL1NNRVYzX0VTSUEzX0lNIj48dG5zOkNvbnRlbnRUb1NtZXYgU2VhcmNoQWdlPSIzMCIgUmVxdWVzdE1vZGU9InhvciIgVHJhbnNmZXJNZXRob2Q9IjIiPjxuczc6VXNlck9yZGVyUmVxdWVzdD48bnM3OlJvdXRpbmdDb2RlPlBST0Q8L25zNzpSb3V0aW5nQ29kZT48bnM3OnBlcnNvbj48bnM2OnNuaWxzPjEzMi05OTEtOTg3IDk5PC9uczY6c25pbHM+PG5zNjpmaXJzdE5hbWU+0JTQvNC40YLRgNC40Lk8L25zNjpmaXJzdE5hbWU+PG5zNjpsYXN0TmFtZT7QodC60LjQtNCw0L3QvtCyPC9uczY6bGFzdE5hbWU+PG5zNjpzZWNvbmROYW1lPtCU0LzQuNGC0YDQuNC10LLQuNGHPC9uczY6c2Vjb25kTmFtZT48bnM2OmJkYXRlPjE5NzItMDEtMjk8L25zNjpiZGF0ZT48bnM2OnBhc3Nwb3J0PjxuczY6c2VyaWVzPjYwIDE1PC9uczY6c2VyaWVzPjxuczY6bnVtPjkwMzA3MzwvbnM2Om51bT48bnM2Omlzc3VlRGF0ZT4yMDE2LTAyLTA5PC9uczY6aXNzdWVEYXRlPjxuczY6aXNzdWVDb2RlPjYxMC0wMDI8L25zNjppc3N1ZUNvZGU+PC9uczY6cGFzc3BvcnQ+PG5zNjpwaG9uZT4rNyAoOTM4KSAxMDItMjItMDk8L25zNjpwaG9uZT48L25zNzpwZXJzb24+PG5zNzpzZXJ2aWNlRm9ybUNvZGU+MTAwMDAwOTI1NTc8L25zNzpzZXJ2aWNlRm9ybUNvZGU+PG5zNzpzZXJ2aWNlQ29kZT4xMDAwMDU2OTUyNDwvbnM3OnNlcnZpY2VDb2RlPjwvbnM3OlVzZXJPcmRlclJlcXVlc3Q+PC90bnM6Q29udGVudFRvU21ldj48dG5zOkF0dGFjaG1lbnRzPjx0bnM6QXR0YWNobWVudD48dG5zOkZpbGVEYXRhLz48L3RuczpBdHRhY2htZW50PjwvdG5zOkF0dGFjaG1lbnRzPjwvVG9TbWV2Pg==</Request></RequestMessage>";
TextMessage messag = session.createTextMessage(mess_xml);
connection.start();
producer.send(messag);
} catch (JMSException e) {
e.printStackTrace();
}
}
}
What to do with such a output:
com.ibm.msg.client.jms.DetailedJMSSecurityException: JMSWMQ2013: The
security authentication was not valid that was supplied for
QueueManager 'N_MQ' with connection mode 'Client' and host name
'localhost(1414)'. Please check if the supplied username and password
are correct on the QueueManager to which you are connecting.
at com.ibm.msg.client.wmq.common.internal.Reason.reasonToException(Reason.java:531)
at com.ibm.msg.client.wmq.common.internal.Reason.createException(Reason.java:215)
at com.ibm.msg.client.wmq.internal.WMQConnection.<init>(WMQConnection.java:424)
at com.ibm.msg.client.wmq.factories.WMQConnectionFactory.createV7ProviderConnection(WMQConnectionFactory.java:8475)
at com.ibm.msg.client.wmq.factories.WMQConnectionFactory.createProviderConnection(WMQConnectionFactory.java:7815)
at com.ibm.msg.client.jms.admin.JmsConnectionFactoryImpl._createConnection(JmsConnectionFactoryImpl.java:303)
at com.ibm.msg.client.jms.admin.JmsConnectionFactoryImpl.createConnection(JmsConnectionFactoryImpl.java:236)
at com.ibm.mq.jms.MQConnectionFactory.createCommonConnection(MQConnectionFactory.java:6016)
at com.ibm.mq.jms.MQConnectionFactory.createConnection(MQConnectionFactory.java:6041)
at SenderMQ.main(SenderMQ.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
Caused by: com.ibm.mq.MQException: JMSCMQ0001: IBM MQ call failed with
compcode '2' ('MQCC_FAILED') reason '2035' ('MQRC_NOT_AUTHORIZED').
at com.ibm.msg.client.wmq.common.internal.Reason.createException(Reason.java:203)
... 13 more

Eclipse, Javamail, Tomcat, and socket unreachable / network unreachable?

I have a regular Java Application that works with Javamail. As in, if I just run it in a Main(String[] args) it will work but if I'm running it from a webapp, specifically VAADIN with Tomcat (AND Jetty), I always get a java.net.SocketException: network is unreachable: connect
I can ping the MSExchange server. And the regular program works.
In eclipse, I tried following this guide by changing the server.xml and web.xml settings, but after adding in all th changes, I still get the same error.
This is the Java Application that works in Eclipse, it will send an email using the MSExchange server we have. Are there specific ports I need to add? I've tried to force Tomcat to use IPV4 by adding 0.0.0.0 to all my connectors but that didn't do anything.
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import javax.mail.Session;
import java.text.SimpleDateFormat;
public class SendEmail {
public static void main(String[] args) {
//Creates a connection with the Exchange Server.
String smtpHostServer = "MSExchangeServerName";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.socketFactory.port", "25");
props.put("java.net.preferIPv4Stack","True");
Session session = Session.getInstance(props, null);
String todayStr = new SimpleDateFormat("MM-dd-yyyy").format(new Date());
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, 14);
Date d = c.getTime();
String dateStr = new SimpleDateFormat("MM/dd/yyyy").format(d);
SendEmailUtility.sendEmail(session, "email#host.com", "Test <b>Email</b>");
Here is the SendEmailUtility:
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class SendEmailUtility {
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
{
//Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress("blah#test.com"));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toEmail));
// Set Subject: header field
message.setSubject(subject);
// This mail has 2 part, the BODY and the embedded image
MimeMultipart multipart = new MimeMultipart("related");
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<img src=\"cid:image\"><p>"+body;
messageBodyPart.setContent(htmlText, "text/html");
// add it
multipart.addBodyPart(messageBodyPart);
// second part (the image)
messageBodyPart = new MimeBodyPart();
String fdsImg;
fdsImg = "c:\download.jpg";
DataSource fds = new FileDataSource(fdsImg);
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<image>");
// add image to the multipart
multipart.addBodyPart(messageBodyPart);
// put everything together
message.setContent(multipart);
// Send message
Transport.send(message); //ERROR HAPPENS HERE ON TOMCAT
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This is the exactly same copy pasted code in the webapp with the exact same EmailUtils above, only that this version DOESN'T WORK.
btnSendEmail.addClickListener(new ClickListener(){
#Override
public void buttonClick(ClickEvent event) {
try {
String smtpHostServer = "MSExchangeServerName";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.socketFactory.port", "25");
props.put("java.net.preferIPv4Stack","True");
Session session = Session.getInstance(props, null);
String todayStr = new SimpleDateFormat("MM-dd-yyyy").format(new Date());
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, 14);
Date d = c.getTime();
String dateStr = new SimpleDateFormat("MM/dd/yyyy").format(d);
SendEmailUtility.sendEmail(session, "blah#test.com", "test <b>email");
} catch (Exception e) {
e.printStackTrace();
Notification.show("Error sending the email", Notification.Type.ERROR_MESSAGE);
}
}
});
layout.addComponent(btnSendEmail);
My Stacktrace:
javax.mail.MessagingException: Could not connect to SMTP host: MSExchangeName, port: 25;
nested exception is:
java.net.SocketException: Network is unreachable: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
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 org.test.EmailUtils.sendEmail(EmailUtils.java:57)
Are there any other options I have to do or that I might not have done correctly? As a shot in the dark, I tried looking up eclipse, javamail, tomcat and I got this question and added the Javamail jar to my Tomcat Lib folder and also in my classpath. I still get the cannot connect error.
When I Right Click > Run as >Run on server, I tried to see if Tomcat was running on a system account, but when I checked in Task Manager, it had my Username under here:
Does this mean it has access to the network? Or something is still blocked? Or I need to add proxy settings specifically for Tomcat?
Sounds like a firewall or anti-virus problem. The JavaMail FAQ has connection debugging tips.

NoRouteToHostException trying to connect to remote host via org.apache.commons.net.ftp.FTPClient in SFTP mode

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.

Using JavaMail to read the mail

I am getting this error when tried to read mail using JavaMail. please let me know how to resolve this error. I have added activation.jar and mail.jar into eclipse.
DEBUG POP3: server doesn't support TOP, disabling it
javax.mail.AuthenticationFailedException: Command is not valid in this state.
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:174)
at javax.mail.Service.connect(Service.java:291)
at javax.mail.Service.connect(Service.java:172)
at library.VerifyEmail.main(VerifyEmail.java:40)
Below is the code I am trying:
package library;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import com.sun.mail.pop3.POP3Store;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.SubjectTerm;
import javax.activation.*;
import java.io.*;
public class VerifyEmail {
public static void main(String[] args) throws Exception {
// SUBSTITUTE YOUR ISP's POP3 SERVER HERE!!!
String host = "myhost";
// SUBSTITUTE YOUR USERNAME AND PASSWORD TO ACCESS E-MAIL HERE!!!
String user = "myuser";
String password = "mypass";
// Get a session. Use a blank Properties object.
Session session = Session.getInstance(new Properties());
try {
// Get a Store object
Store store = session.getStore("pop3");
store.connect(host, user, password);
// Get "INBOX"
Folder fldr = store.getFolder("INBOX");
fldr.open(Folder.READ_WRITE);
int count = fldr.getMessageCount();
System.out.println(count + " total messages");
// Message numebers start at 1
for(int i = 1; i <= count; i++) {
// Get a message by its sequence number
Message m = fldr.getMessage(i);
// Get some headers
Date date = m.getSentDate();
Address [] from = m.getFrom();
String subj = m.getSubject();
String mimeType = m.getContentType();
System.out.println(date + "\t" + from[0] + "\t" +
subj + "\t" + mimeType);
}
}catch (MessagingException ioex) {
ioex.printStackTrace();
}
}
}
When you're getting the javax.mail.AuthenticationException it means that your application is unable to authenticate to the mail server.
One possible reason for this might be that an SSL certificate of the mail server is missing from the client keystore.
According to microsoft: For exchange 2010, by default, the server would need the client use ssl for pop3.
Without ssl the server responds with "ERR command is not valid in this state."
Here's how to use javamail with ssl - Javamail and Gmail Pop3 SSL
DEBUG POP3: server doesn't support TOP, disabling it
this message can be disable by updating the java mail jar version to 1.4.4

javax.mail.MessagingException: Could not connect to SMTP host?

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.

Categories

Resources