I'm using apache commons mail to send emails. Unfortunately I'm getting following Exception:
org.apache.commons.mail.EmailException: Sending the email to the following server failed : mail.xxx.com:25
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1242)
at org.apache.commons.mail.Email.send(Email.java:1267)
at com.xxx.UserBean.sendMail(UserBean.java:92)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
.
.
.
Caused by: javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
java.io.IOException: Server is not trusted: mail.xxx.com
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1880)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:648)
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 org.apache.commons.mail.Email.sendMimeMessage(Email.java:1232)
... 85 more
Caused by: java.io.IOException: Server is not trusted: mail.xxx.com
at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:443)
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1875)
... 92 more
And here is my java code:
public void sendMail(){
try {
SimpleEmail mail = new SimpleEmail();
mail.setTLS(true);
mail.setAuthenticator(new DefaultAuthenticator("user","xyxyxyxy"));
mail.setHostName("mail.xxx.com");
mail.getMailSession().getProperties().put("mail.smtps.auth", true);
mail.getMailSession().getProperties().put("mail.debug", true);
mail.getMailSession().getProperties().put("mail.smtps.port", "587");
mail.getMailSession().getProperties().put("mail.smtp.starttls.enable", true);
mail.getMailSession().getProperties().put("mail.smtp.ssl.trust", "smtpserver");
mail.addTo("user#server.com", "user");
mail.setFrom("info#xxx.com");
mail.setSubject("Bla Bla");
mail.setMsg("Bla Bla again");
mail.send();
} catch (Exception ex) {
logger.info("Senden der Email ist gescheitert!", ex);
}
}
I've already read many threads and tried many hints. I'm stuck here!
I should mention that I'm able to send emails with another method using "javax.mail". But I'd like to move to apache.
I'm thankful for any help.
setTLS (Transport layer security) to false. If you are not using. When it is true its expected to be mail.xxx.com trusted server.
mail.setTLS(false);
Finally Solved. I tried everything to get authenticated at my exchange server.
use the code below:
Properties props = (Properties)System.getProperties().clone();
props.put("mail.smtp.host", host);
props.setProperty("mail.smtp.port", "587");
props.put("mail.smtp.auth", true);
//Bypass the SSL authentication
props.put("mail.smtp.ssl.enable", false);
props.put("mail.smtp.starttls.enable", false);
If you're using Spring-Boot-Mail, try adding this line to you .properties file:
spring.mail.properties.mail.smtp.ssl.trust=smtp.mandrillapp.com
Related
I know there is several issue created about this error but nothing was helpful for me. I have method which is sending email with attachment on gmail server and it works fine. yesterday I bought a new mac mini m1. I tried this method to send email but it's throwing this error
public static void sentEmail(String report){
BaseTest base = new BaseTest();
String to = base.getProps().getProperty("emailTO"); ;//change accordingly
final String user = base.getProps().getProperty("emailFROM");//change accordingly
final String password = base.getProps().getProperty("emailPassword");//change accordingly
//1) get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
//2) compose message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("From Mobile Automation Project ");
//3) create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("Report");
//4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = report;//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
//5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//6) set the multiplart object to the message object
message.setContent(multipart );
//7) send message
Transport.send(message);
System.out.println("Report has been sent to: "+ to);
}catch (MessagingException ex) {ex.printStackTrace();}
}
Exception
javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1907)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:666)
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 com.qa.utils.TestUtils.SendEmailTLS(TestUtils.java:228)
at com.qa.BaseTest.afterSuite(BaseTest.java:153)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:134)
at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:63)
at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:348)
at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:302)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:351)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1109)
at org.testng.TestNG.runSuites(TestNG.java:1039)
at org.testng.TestNG.run(TestNG.java:1007)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:284)
at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:119)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:428)
at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:162)
at org.apache.maven.surefire.booter.ForkedBooter.run(ForkedBooter.java:562)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:548)
Caused by: javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
at sun.security.ssl.HandshakeContext.<init>(HandshakeContext.java:171)
at sun.security.ssl.ClientHandshakeContext.<init>(ClientHandshakeContext.java:101)
at sun.security.ssl.TransportContext.kickstart(TransportContext.java:238)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:394)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:373)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:486)
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1902)
... 31 more
I changed this parameter
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
To this
properties.setProperty("mail.smtp.ssl.trust", "smtp.gmail.com");
But then I'm getting this exception
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 587;
nested exception is:
java.net.ConnectException: Connection refused (Connection refused)
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: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 com.qa.utils.TestUtils.sentEmail(TestUtils.java:189)
at com.qa.BaseTest.afterSuite(BaseTest.java:152)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:134)
at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:63)
at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:348)
at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:302)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:351)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1109)
at org.testng.TestNG.runSuites(TestNG.java:1039)
at org.testng.TestNG.run(TestNG.java:1007)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:284)
at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:119)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:428)
at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:162)
at org.apache.maven.surefire.booter.ForkedBooter.run(ForkedBooter.java:562)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:548)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:476)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:218)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:394)
at java.net.Socket.connect(Socket.java:606)
at java.net.Socket.connect(Socket.java:555)
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)
... 31 more
I had a similar issue and it seems to be related to Deepak's response. Following these instructions solved the problem.
It seems to be necessary to explicitly set required flag and the protocols:
Adding the following settings worked for me:
properties.put("mail.smtp.starttls.required", "true");
properties.put("mail.smtp.ssl.protocols", "TLSv1.2");
I have to add that I tested this on port 465 and the full configuration looks like this
properies.put("mail.smtp.host", "smtp.gmail.com");
properies.put("mail.smtp.port", "465");
properies.put("mail.smtp.auth", "true");
properies.put("mail.smtp.starttls.enable", "true");
properies.put("mail.smtp.starttls.required", "true");
properies.put("mail.smtp.ssl.protocols", "TLSv1.2");
properies.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Warning do this own risk of enabling tlsv1 and tlsv1.1:
find the directory where java.security file saved.
in the case of ubuntu:
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security
find jdk.tls.disabledAlgorithms
remove TLSv1, TLSv1.1
reboot the server and run the project to try to send mail again.
To solve that issue, just upgrade the java library used to sendmail.
It worked for me.
I upgraded my javax.mail to 1.6.2 and solved the problem
I faced this issue due to older version of mysql-connector-java-5.1.40-bin.jar
Upgrading to 5.1.49 version solved my issue
while trying to send email via my spring boot application i got this error :
failures; nested exception is javax.mail.MessagingException: Can't send command to SMTP host;
nested exception is:
java.net.SocketException: Software caused connection abort: socket write error. Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 550 Access denied - Invalid HELO name (See RFC2821 4.1.1.1);
nested exception is:
com.sun.mail.smtp.SMTPSenderFailedException: 550 Access denied - Invalid HELO name (See RFC2821 4.1.1.1)
My Spring boot application is generated with jhipster and here is my application-dev.yml config for mail config :
mail:
host: mail.example.com
port: 587
username: support#example.com
password: ************
NB : example.com is just an example for not sharing confidential data, my config is correct i have tested it with and working great but not on my spring boot application
I have provided a sample below.
Showing how I send emails with spring-boot
add the starter mail dependency in your pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Add the below bean in your Application class :
#Bean
public JavaMailSenderImpl customJavaMailSenderImpl(){
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
mailSender.setPort(port);
mailSender.setUsername(username);
mailSender.setPassword(password);
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
return mailSender;
}
See an example, using the customJavaMailSenderImpl bean below :
#Service
public class emailSender{
#Autowired
JavaMailSenderImpl customJavaMailSenderImpl;
public void mailWithAttachment() throws Exception {
MimeMessage message = customJavaMailSenderImpl.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true,"utf-8");
helper.setTo("abc#example.com");
helper.setSubject("test");
helper.setText("hello test", true);
helper.setFrom("abd#example.com", "John Doe");
customJavaMailSenderImpl.send(message);
}
}
After review i found that i forgot to add some mail config in my application-dev.yml :
mail.smtp.starttls.enable : true and mail.smtp.starttls.auth : true
mail config should look like :
mail:
host: mail.example.com
port: 587
username: support#example.com
password: ************
properties:
mail:
smtp:
auth: true
starttls:
enable: true
I have created API key for sendGrid:
I have following spring mail configuration:
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.sendgrid.net
spring.mail.username=apikey
spring.mail.password=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
spring.mail.port=25
spring.mail.protocol=smtp
spring.mail.test-connection=true
And I have following code:
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
Template template = freemarkerConfig.getTemplate(templateFileName);
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, props);
helper.setTo("myEmail#gmail.com");
helper.setText(html, true);
helper.setSubject(subject);
helper.setFrom(from);
sender.send(message);
logger.debug("Send email to {} with subject: [{}]", Arrays.toString(to), subject);
Then I try to start application and experience following error:
27.01.18 20:07:20.460 [main] WARN c.d.m.s.c.MailSenderValidatorAutoConfiguration - Mail server is not available
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.sendgrid.net, 25; timeout -1
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2118)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:712)
at javax.mail.Service.connect(Service.java:366)
at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:501)
at org.springframework.mail.javamail.JavaMailSenderImpl.testConnection(JavaMailSenderImpl.java:382)
How can I fix this?
P.S.
Everything correct for port 587
But I want to use ssl and set port=465
spring.mail.port=465
And at this case my application freezes on startup.and after 5 min prints:
27.01.18 21:06:05.960 [main] WARN c.d.m.s.c.MailSenderValidatorAutoConfiguration - Mail server is not available
javax.mail.MessagingException: Could not connect to SMTP host: smtp.sendgrid.net, port: 465, response: -1
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2106)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:712)
at javax.mail.Service.connect(Service.java:366)
at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:501)
at org.springframework.mail.javamail.JavaMailSenderImpl.testConnection(JavaMailSenderImpl.java:382)
How can I avoid this?
I used the port 2525 (Non-privileged) instead of 578 (privileged) to solve the problem locally. I can still use the privileged one on the cloud. That solved my problem.
You may need add something like this to your configuration.
spring.mail.smtp.ssl.enable=true
There is a probability that SendGrid SMTP servers are not discoverable in your country. try a proxy or VPN.
I used this tutorial to send emails from inside my app.
I used the same code to 3 different apps and it all worked well. But now, a few months later, it stopped working.
I have searched all the possible sites, but none of them helped me.
I tried setting a lower security from my Gmail account and also changing the properties for my session, but nothing worked.
I would really appreciate some help.
Log.d("EmailSender","sending message");
Properties props = new Properties();
props.put("mail.smtp.host", host);
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");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,pass);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(SharedPreferenceUtils.getUserEmail(getActivity())));
message.setSubject(subject);
message.setContent(content, "text/html; charset=utf-8");
//Transport.send(message);
Transport transport = session.getTransport("smtps");
transport.connect (host, Integer.parseInt(port), user, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
Log.d("EmailSender", "message sent");
} catch (MessagingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
My error:
java.net.ConnectException: failed to connect to smtp.gmail.com/2a00:1450:4013:c01::6d (port 465) after 90000ms: isConnected failed: ENETUNREACH (Network is unreachable)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
at javax.mail.Service.connect(Service.java:288)
at com.mihaela.myapp.ui.dialog.EnterPasswordDialog$SendMailTask.doInBackground(EnterPasswordDialog.java:222)
at com.mihaela.myapp.ui.dialog.EnterPasswordDialog$SendMailTask.doInBackground(EnterPasswordDialog.java:179)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.net.ConnectException: failed to connect to smtp.gmail.com/2a00:1450:4013:c01::6d (port 465) after 90000ms: isConnected failed: ENETUNREACH (Network is unreachable)
at libcore.io.IoBridge.isConnected(IoBridge.java:267)
at libcore.io.IoBridge.connectErrno(IoBridge.java:191)
at libcore.io.IoBridge.connect(IoBridge.java:127)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:461)
at java.net.Socket.connect(Socket.java:918)
at java.net.Socket.connect(Socket.java:844)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
... 10 more
Caused by: android.system.ErrnoException: isConnected failed: ENETUNREACH (Network is unreachable)
at libcore.io.IoBridge.isConnected(IoBridge.java:252)
... 19 more
From the logs:
java.net.ConnectException: failed to connect to smtp.gmail.com/2a00:1450:4013:c01::6d (port 465) after 90000ms: isConnected failed: ENETUNREACH (Network is unreachable)
Network is unreachable. The code looks okay, therefore the issue must be with the network. Please check your connectivity. Possible causes could be:
Very slow/ bad network. Try changing the network.
Internet permission not available in the manifest (this shouldn't be the case as described by your problem). Add the permission.
For future, you can add a network-check before sending network requests. This thread has some good answers for checking the network connectivity: How to check internet access on Android? InetAddress never times out
I would like to write a program which connects with the gmail server using SMTP TLS. I am using the code mentioned on this page :
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
I am getting connection time out exception. I can succefully send email if I use SMTP SSL.
public void sendUsingSMTP_TLS() {
final String username = "username#gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "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("from-email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
I get following exception:
Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException:
Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at SMTP_TLS.main(SMTP_TLS.java:48)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out: 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:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at SMTP_TLS.main(SMTP_TLS.java:43)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
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.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:299)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:234)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
… 7 more
The exception means that you are unable to connect to port 587 on server smtp.gmail.com . Verify this using telnet:
telnet smtp.gmail.com 587
(This works for me, so the server and port number are correct.)
Possible reasons for this to do not work from your location are:
Misconfigured proxy settings in Java
A firewall at your location, which forbids to connect to this port number.
If the telnet command above can connect, then you can rule out a problem with the firewall. But if it does not work and you are in a company network, then it's most likely the firewall which causes the problem.
Also, find out the port number which is used with your other connection method. Maybe that also works with TLS.