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

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.

Related

javax.mail.AuthenticationFailedException: [AUTH] Web login required

I build an application using Java to read emails. And It worked without any errors past days. But suddenly today came up an error like this.
javax.mail.AuthenticationFailedException: [AUTH] Web login required: https://support.google.com/mail/answer/78754
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:207)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at MailReader.readMail(MailReader.java:44)
at MailReader.run(MailReader.java:32)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
I can't figure out how to fix this. I didn't put 2-way authentication. And also I put less secure app allowed. So I can't figure out what is wrong. Anybody can help me? I greatly appreciate that.
Here is the code I am using,
String host = "pop.gmail.com";
String username = "somename#gmail.com";
String password = "password";
Properties prop = new Properties();
Session session = Session.getInstance(prop, null);
Store store = session.getStore("pop3s");
store.connect(host, username, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
The error was due to an error at Google, which caused POP3 services to work incorrectly. It was fixed after 2 days.
Could not find official statement, only forum posts. Related sources:
1, 2, 3
My working snippet looks like below:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
public class CheckingMails {
public static void check(String host, String user, String password)
{
try {
// create properties field
Properties properties = new Properties();
properties.put("mail.pop3s.host", host);
properties.put("mail.pop3s.port", "995");
properties.put("mail.pop3s.starttls.enable", "true");
// Setup authentication, get session
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
// session.setDebug(true);
// create the POP3 store object and connect with the pop server
Store store = session.getStore("pop3s");
store.connect();
// create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
// close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";
String username = "abc#gmail.com";// change accordingly
String password = "*****";// change accordingly
check(host, username, password);
}
}
My problem was that the same code was working on local but not on the remote cloud (Bitbucket pipeline) although I set the less secure enable. I solved it by enabled 2 step verification and create an app password. Then used this app password instead of the normal password in the code.
You can check the following link as well: https://docs.maildev.com/article/121-gmail-web-login-required-error---answer78754-failure

What is blocking my Java mail?

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.

Copy paste contents of excel into outlook

I have an excel sheet with one of the sheet as 'summary' which has summary of the execution, I am using javax mail to send this excel as attachment using outlook, however I would like to paste this summary in the email body so users get a summary before opening the excel.
I have tried with opening the excel and capturing the screen shot but whole excel is captured I only need whats inside excel.
I dont want to use VBA as the excel sheet may change.
Below is the code I am using for sending email:
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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;
import org.testng.annotations.Test;
public class EmailExecutionReport {
static DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
static Date date = new Date();
static String attachFiles="C:\\Excel_Report.xls";
static String messageToBeSent="<body > <p><font face="+"calibri"+">Hi All,</font></p><p><font face="+"calibri"+">Please find the Environment validations report as in the attached file</font></p><p><font face="+"calibri"+">This set of execution was completed on: "+dateFormat.format(date)+"</font></p><br><font face="+"calibri"+">Regards<br><font face="+"calibri"+"><br><br>---This is a auto generated email---</body>";
#Test
public static void JavaSentEamil() throws IOException {
// String host="host";
final String user="SSS#abcd.com";
String to="icpm-qa#abcd.com";
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host","abcd.abcd.com");
props.put("mail.smtp.auth", "false");
Session session=Session.getDefaultInstance(props, null);
session.setDebug(true);
//Compose the message
try {
MimeMessage message = new MimeMessage(session);
message.saveChanges();
message.setFrom(new InternetAddress(user));
//message.addRecipient(Message.RecipientType.TO,new InternetAddress (to));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject("Automation Environment validations Report as on: "+dateFormat.format(date));
// message.setText("This is test mail sent from Java Program");
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(messageToBeSent, "text/html ; charset=ISO-8859-1");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFiles != null) {
MimeBodyPart attachPart = new MimeBodyPart();
attachPart.attachFile(attachFiles);
multipart.addBodyPart(attachPart);
}
// sets the multi-part as e-mail's content
message.setContent(multipart);
//send the message
Transport.send(message);
System.out.println("Message sent successfully...");
}
catch (MessagingException e) {e.printStackTrace();}
}
}
I am not sure why you are not using Excel POI and using the ChartSheet object there. But just to give you an idea here is already an existing discussion
How to get chart info from an Excel spreadsheet using Apache POI?

Can't connect to mbox store

Using this code:
import java.io.*;
import java.util.*;
import javax.mail.*;
public class Mbox {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("mail.store.protocol", "mstor");
properties.setProperty("mstor.mbox.metadataStrategy", "none");
properties.setProperty("mstor.mbox.cacheBuffers", "disabled");
properties.setProperty("mstor.cache.disabled", "true");
properties.setProperty("mstor.mbox.bufferStrategy", "mapped");
properties.setProperty("mstor.metadata", "disabled");
Session session = Session.getDefaultInstance(properties);
try {
Store store = session.getStore(new URLName("mstor:C:/INBOX"));
store.connect();
Folder inbox = store.getDefaultFolder().getFolder("inbox");
inbox.open(Folder.READ_ONLY);
Message m = inbox.getMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to setup an mbox reading program in java. I have tried both on Linux and Windows but every time I get the exception javax.mail.NoSuchProviderException: No provider for mstor on session.getStore("mstor:C:/INBOX"). I searched for a while and made the properties file as shown above but still the error persited.
javax.mail.NoSuchProviderException: No provider for mstor
at javax.mail.Session.getProvider(Session.java:473)
at javax.mail.Session.getStore(Session.java:547)
at Mbox.main(Mbox.java:23)
What am I doing wrong?

Must issue a STARTTLS command first. - gsmtp ; Sending email with attachment using gmail account

I am quite new in programming, sorry for weak explanation. I have tried with almost all available answers in google. but could not figure out why the error is coming.The purpose of this code is to attach a file and send it to a email address. I dont have any email server.
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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 SendEmailMain {
public static void main(String[] args) {
final String username = "myusername#gmail.com";
final String password = "mypassword";
String emailID = "receiversUserName#yahoo.com";
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.auth", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(emailID));
message.setSubject("Testing Subject");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "snap1.jpg";
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Error message in eclipse console
Sending
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. of6sm3574020lbb.11 - gsmtp
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1388)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:959)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:583)
at javax.mail.Transport.send0(Transport.java:169)
at javax.mail.Transport.send(Transport.java:98)
at me.screenful.screenshot.ScreenShotTaker.SendEmailMain.main(SendEmailMain.java:70)
I have found why it was not working. Because I copied the code from google to my project. In the code
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.auth", true);
value true was not in inverted comma. It should be like this
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
If error come "530 5.7.0 Must issue a STARTTLS command first." at run time.
In IDE:
Right click the project. Click Run as then Run Configurations.
You can set the parameters "-Dmail.smtp.starttls.enable=true" in the (X)= Arguments tab in the VM Arguments box.
Click Run button.
or
At Command prompt:
You're giving parameters to java program
java -Dmail.smtp.starttls.enable=true <>.java

Categories

Resources