I am fairly new to Java spring - I am getting the following errors when trying to send a test email.
Error in sending email:
org.springframework.mail.MailSendException: Mail server connection
failed; nested exception is javax.mail.MessagingException: Could not
connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?. Failed messages: javax.mail.MessagingException: Could not
connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?; message exceptions (1) are:
Failed message 1: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?"
SimepleEmailController.java
package controller;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class SimpleEmailController {
#Autowired
private JavaMailSender sender;
#RequestMapping("/simpleemail")
#ResponseBody
String home() {
try {
sendEmail();
return "Email Sent!";
}catch(Exception ex) {
return "Error in sending email: "+ex;
}
}
private void sendEmail() throws Exception{
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo("set-your-recipient-email-here#gmail.com");
helper.setText("How are you?");
helper.setSubject("Hi");
sender.send(message);
}
}
The application.properties settings are as follows - testing on a test account
spring.mail.port=587
spring.mail.host=smtp.gmail.com
spring.mail.username=xxxxxxxxxxxxx#gmail.com
spring.mail.password=zzzzzzzzzzz
spring.mail.protocol=smtp
spring.mail.defaultEncoding=UTF-8
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.socketFactory.port = 25
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = true
spring.mail.properties.mail.smtp.ssl.enable=true
support.mail.address=xxxxxxxxxxxxxxx#gmail.com
Remove this line from your application.properties:
spring.mail.properties.mail.smtp.ssl.enable=true
Since your are using port 587 which is for sending message with TLS. You should use above configuration if you are using port 465 which is a SMTP SSL port.
Try to use your # as setTo() param for a first quick test.
Then, you can let default configuration, you don't need much of it.
spring.mail.host=smtp.gmail.com
spring.mail.username=romanineers#gmail.com
spring.mail.password=****** #hope it wasn't your real password :)
spring.mail.properties.mail.smtp.auth = true
As per the error you are getting, just set spring.mail.properties.mail.smtp.ssl.enable=true
property value to false and try.
Problem fixed --- javax.mail.AuthenticationFailedException is thrown while sending email in java -- have to configure the gmail to allow less secure apps --
spring.mail.port=465
spring.mail.host=smtp.gmail.com
spring.mail.username=xx#gmail.com
spring.mail.password=yyyyy
spring.mail.protocol=smtp
spring.mail.defaultEncoding=UTF-8
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.socketFactory.port = 465
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = false
spring.mail.properties.mail.smtp.ssl.enable=false
support.mail.address=xx#gmail.com
Related
Good evening,
I have been facing this error for a couple of days by now, and despite looking for a solution all over the web, I coul'd fix this error.
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class LDAPtest {
public static void main(String[] args) {
try {
String keystorePath = "C:/Program Files/Java/jdk-13.0.2/lib/security/cacerts";
System.setProperty("javax.net.ssl.keyStore", keystorePath);
System.setProperty("javax.net.ssl.keyStorePassword", "changeit");
Hashtable<String, String> ldapEnv = new Hashtable<>();
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, "ldaps://localhost:10636");
ldapEnv.put(Context.SECURITY_AUTHENTICATION,"simple");
ldapEnv.put(Context.SECURITY_PRINCIPAL,"uid=admin,ou=system");
ldapEnv.put(Context.SECURITY_CREDENTIALS,"secret");
DirContext connection = new InitialDirContext(ldapEnv);
System.out.println("Benvenuto " + connection);
NamingEnumeration enm = connection.list("");
while (enm.hasMore()) {
System.out.println(enm.next());
}
enm.close();
connection.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
This code is actually working when SSL is not tested, replacing the
ldapEnv.put(Context.PROVIDER_URL, "ldaps://localhost:10636");
with
ldapEnv.put(Context.PROVIDER_URL, "ldap://localhost:10389");
I made the setup for the LDAP server with Apache Directory Studio, and followed this tutorial here in order to get the LDAPS to work:
http://directory.apache.org/apacheds/basic-ug/3.3-enabling-ssl.html
So I made the certificate, even installed it and imported it with keytool into cacerts.
I enabled portforwarding for the chosen port (10636), but still, I'm getting this exception:
javax.naming.CommunicationException: simple bind failed: localhost:10636 [Root exception is
java.net.SocketException: Connection or outbound has closed]
at java.naming/com.sun.jndi.ldap.LdapClient.authenticate(LdapClient.java:219)
at java.naming/com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2795)
at java.naming/com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:320)
at java.naming/com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxFromUrl(LdapCtxFactory.java:225)
at java.naming/com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:189)
at java.naming/com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:243)
at java.naming/com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:154)
at java.naming/com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:84)
at java.naming/javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:730)
at java.naming/javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:305)
at java.naming/javax.naming.InitialContext.init(InitialContext.java:236)
at java.naming/javax.naming.InitialContext.<init>(InitialContext.java:208)
at java.naming/javax.naming.directory.InitialDirContext.<init>(InitialDirContext.java:130)
at Prova3.main(Prova3.java:31)
Caused by: java.net.SocketException: Connection or outbound has closed
at java.base/sun.security.ssl.SSLSocketImpl$AppOutputStream.write(SSLSocketImpl.java:1246)
at java.base/java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:81)
at java.base/java.io.BufferedOutputStream.flush(BufferedOutputStream.java:142)
at java.naming/com.sun.jndi.ldap.Connection.writeRequest(Connection.java:398)
at java.naming/com.sun.jndi.ldap.Connection.writeRequest(Connection.java:371)
at java.naming/com.sun.jndi.ldap.LdapClient.ldapBind(LdapClient.java:359)
at java.naming/com.sun.jndi.ldap.LdapClient.authenticate(LdapClient.java:214)
... 13 more
Thank you in advance
For Googlers:
simple bind failed errors are almost always related to SSL connection.
With nc or telnet, check whether a connection can be established between client and remote host and port.
With SSLPoke.java (a simple Java class to check SSL connection), check whether certificates are correctly imported and used, also check correct TLS version. Use something like java -Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2 -Djavax.net.debug=all SSLPoke google.com 443 > log.txt 2>&1.
Look for:
Warning: no suitable certificate found - continuing without client authentication = check whether you have set javax.net.ssl.trustStore
Fatal (HANDSHAKE_FAILURE): Couldn't kickstart handshaking = could be mismatched TLS versions
Also check whether your intermediate CA is expired
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've already researched the topic for a few days but none of the answers I found online did the trick for me.
Context: I've got a Spring Boot web application which sends automatic emails notifications using Java Mail API and Spring Boot Starter Mail.
It is using GMail SMTP server with a GSuite account. I recently upgraded to use Spring 5.0.6 and Spring Boot 2.0.2 and the email sending stopped working.
A few clues:
the Java code sending the email is the same as before
Gmail SMTP still works correctly (from another VM using older version of the application with the same settings and authentication, the emails are sent properly).
unless I am missing something, the application configuration remains the same as before
The things that have changed:
upgrade to Spring 5.0.6
upgrade to Spring Boot 2.0.2
changes in many places in the Java code to match this upgrades and add features in other parts of the app
The IP address of the VM is different than before (AWS EC2 instance)
Here are the relevant dependencies in pom.xml :
<!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Here is the application.yml relevant to Spring mail:
spring:
mail:
host: ${FT_MAIL_SMTP_HOST}
port: ${FT_MAIL_SMTP_PORT}
username: ${FT_MAIL_SMTP_USERNAME}
password: ${FT_MAIL_SMTP_PASSWORD}
debug: false
properties:
mail:
smtp:
starttls:
enable: ${FT_MAIL_SMTP_STARTTLS}
required: ${FT_MAIL_SMTP_TLSREQUIRED}
auth: ${FT_MAIL_SMTP_AUTH}
connectiontimeout: ${FT_MAIL_SMTP_CONN_TIMEOUT}
timeout: ${FT_MAIL_SMTP_TIMEOUT}
writetimeout: ${FT_MAIL_SMTP_WRITE_TIMEOUT}
These variables are defined in the environment:
FT_MAIL_SMTP_HOST=smtp.gmail.com
FT_MAIL_SMTP_PORT=587
FT_MAIL_SMTP_USERNAME=myaccount#myapp.com
FT_MAIL_SMTP_PASSWORD=mypassword
FT_MAIL_SMTP_STARTTLS=true
FT_MAIL_SMTP_TLSREQUIRED=true
FT_MAIL_SMTP_AUTH=true
FT_MAIL_SMTP_CONN_TIMEOUT=5000
FT_MAIL_SMTP_TIMEOUT=5000
FT_MAIL_SMTP_WRITE_TIMEOUT=5000
Here is the Spring #Service used to send the email (unchanged):
#Service
public class EmailServiceImpl {
#Autowired
public JavaMailSender emailSender;
#Autowired
private SpringTemplateEngine templateEngine;
#Value("${myapp.mail.from}")
private String fromAddress;
#Value("${myapp.mail.replyto}")
private String replyToAddress;
public void sendTemplatedMessage(String template, String to, String subject, Map<String, Object> model) throws MailException, MessagingException {
sendTemplatedMessage(template, to, fromAddress, replyToAddress, subject, model);
}
public void sendTemplatedMessage(String template, String to, String from, String subject, Map<String, Object> model) throws MailException, MessagingException {
sendTemplatedMessage(template, to, from, replyToAddress, subject, model);
}
private void sendTemplatedMessage(String template, String to, String from, String replyTo, String subject, Map<String, Object> model) throws MailException, MessagingException {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
//helper.addAttachment("logo.png", new ClassPathResource("memorynotfound-logo.png"));
Context context = new Context();
context.setVariables(model);
String html = templateEngine.process(template, context);
helper.setTo(to);
helper.setFrom(from);
helper.setReplyTo(from);
helper.setSubject(subject);
helper.setText(html, true);
emailSender.send(message);
}
public void sendSimpleMessage(String to, String from, String subject, String text) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setFrom(from);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now here is the error I get when trying to send an email:
04:42:19.900 [https-jsse-nio-443-exec-3] ERROR c.f.controller.StayController - Could not send Guest confirmation email to gfgorostidi#protonmail.com
org.springframework.mail.MailSendException: Failed to close server connection after message sending; nested exception is javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:482)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:359)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:354)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:61)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:35)
at com.myapp.controller.StayController.sendConfirmEmailToGuest(StayController.java:437)
at com.myapp.controller.StayController.saveStay(StayController.java:383)
at com.myapp.controller.StayController.createStay(StayController.java:163)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
......
......
......
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2202)
at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1212)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:473)
... 104 more
Caused by: java.net.SocketTimeoutException: Read timed out
at java.base/java.net.SocketInputStream.socketRead0(Native Method)
at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:425)
at java.base/sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(SSLSocketInputRecord.java:65)
at java.base/sun.security.ssl.SSLSocketImpl.bytesInCompletePacket(SSLSocketImpl.java:918)
at java.base/sun.security.ssl.AppInputStream.read(AppInputStream.java:144)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:124)
at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:252)
at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:271)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:89)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2182)
... 106 more
org.springframework.mail.MailSendException: Failed to close server connection after message sending; nested exception is javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:482)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:359)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:354)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:61)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:35)
at com.myapp.controller.StayController.sendConfirmEmailToGuest(StayController.java:437)
at com.myapp.controller.StayController.saveStay(StayController.java:383)
at com.myapp.controller.StayController.createStay(StayController.java:163)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
......
......
......
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2202)
at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1212)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:473)
... 104 more
Caused by: java.net.SocketTimeoutException: Read timed out
at java.base/java.net.SocketInputStream.socketRead0(Native Method)
at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:425)
at java.base/sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(SSLSocketInputRecord.java:65)
at java.base/sun.security.ssl.SSLSocketImpl.bytesInCompletePacket(SSLSocketImpl.java:918)
at java.base/sun.security.ssl.AppInputStream.read(AppInputStream.java:144)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:124)
at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:252)
at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:271)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:89)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2182)
... 106 more
I have tried setting an incorrect SMTP server or bad credentials and this made the connection fail, so I assumed the server and credentials are correct as they are, and the error happens after a successful connection.
The account used hasn't reached its limit, as another VM uses the same credentials and sends emails without problem.
I've tried changing "Start TLS" settings to false and use port 465 instead, but this isn't working either.
Any help is appreciated !! Thanks in advance!
After much more trial and error with the configuration, I found out that it required an application property "spring.mail.protocol" in the configuration.
I've added the line protocol: smtp in application.yml:
spring:
mail:
protocol: smtp
And that fixed the read timeout issue, email are now sent properly. Hope that may help someone in the future.
I did face the same issue, but my scenario was a bit different
I was trying to send in a schedule manner using quartz
When I did not use Quartz, it was all working fine, but with quartz it started failing
The above solution did not help me, but pointed me in direction of looking at the properties that I had set.
Increasing the connection timeout did the job for me
Thus changed the application properties
from:
spring.mail.properties.mail.smtp.timeout=3000
to:
spring.mail.properties.mail.smtp.timeout=25000
Hope it works for others as well
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 have the following code:
package daoImp;
import java.util.List;
import javapns.Push;
import javapns.communication.exceptions.KeystoreException;
import javapns.notification.PushedNotification;
import javapns.notification.ResponsePacket;
import org.json.JSONException;
import com.sun.jmx.snmp.daemon.CommunicationException;
public class Notification {
public static void main(String args[]) {
try {
new Notification().sendMessageToAPN();
} catch (CommunicationException | KeystoreException | JSONException
| javapns.communication.exceptions.CommunicationException e) {
e.printStackTrace();
}
}
public void sendMessageToAPN() throws CommunicationException,
KeystoreException, JSONException,
javapns.communication.exceptions.CommunicationException {
String regId1 = "6f9d340ab4d0f81206f7d8c1ab7b8994d90d139e0d1d2b99999b02887e60d54f";
List<PushedNotification> notifications = Push.alert("hello","C:/Program Files (x86)/Java/jdk1.7.0_21/jre/lib/security/gameover.p12", "gameover",
false, regId1);
for (PushedNotification notification : notifications) {
if (notification.isSuccessful()) {
System.out.println("Push notification sent successfully to: " + notification.getDevice().getToken());
} else {
String invalidToken = notification.getDevice().getToken();
System.err.println("Invalid Token " + invalidToken);
System.out.println(" The problem was");
Exception theProblem = notification.getException();
theProblem.printStackTrace();
ResponsePacket theErrorResponse = notification.getResponse();
if (theErrorResponse != null) {
System.out.println(theErrorResponse.getMessage());
}
}
}
}
}
When I run the code, I get the following exception message: handshake to ssl failed as connection to remote host failed during handshake.
log4j:WARN No appenders could be found for logger (javapns.notification.Payload).
log4j:WARN Please initialize the log4j system properly.
Invalid Token 6f9d340ab4d0f81206f7d8c1ab7b6774d90d139e0d1d2b58599b02887e60d54f
The problem was
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.writeRecord(Unknown Source)
at sun.security.ssl.AppOutputStream.write(Unknown Source)
at java.io.OutputStream.write(Unknown Source)
at javapns.notification.PushNotificationManager.sendNotification(PushNotificationManager.java:402)
at javapns.notification.PushNotificationManager.sendNotification(PushNotificationManager.java:350)
at javapns.notification.PushNotificationManager.sendNotification(PushNotificationManager.java:320)
at javapns.Push.sendPayload(Push.java:177)
at javapns.Push.alert(Push.java:47)
at daoImp.Notification.sendMessageToAPN(Notification.java:27)
at daoImp.Notification.main(Notification.java:16)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at sun.security.ssl.InputRecord.read(Unknown Source)
... 12 more
I don't know why I'm getting this message.
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
Caused by: java.io.EOFException: SSL peer shut down incorrectly
Above Exception is a generic exception we get in the client if there is any of below scenario:
If Server and Client support different version of TLS e.g. server
support TLS2 while Client support only TLS1. This issue can be resolved by setting below property in Client side :
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
If the server is not able to validate the certificate chain of the client, then also it will close the conection.
Certificate chain qtp510727907-31, fatal error: 42: null cert chain
javax.net.ssl.SSLHandshakeException: null cert chain %%
Invalidated: [Session-3, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA]
qtp510727907-31, SEND TLSv1 ALERT: fatal, description =
bad_certificate qtp510727907-31, WRITE: TLSv1 Alert, length = 2
main, WRITE: TLSv1 Change Cipher Spec, length = 1 qtp510727907-31,
fatal: engine already closed. Rethrowing
javax.net.ssl.SSLHandshakeException: null cert chain
To know the exact cause of failure, we need to enable -Djavax.net.debug=all while executing the client call towards the server.
This issue occurs because of Internet connection problem/poor internet connection.
Please check your internet connectivity.
I believe you are missing your certificates.
You can generate them using the InstallCerts app. (http://miteff.com/install-cert)
or http://opentox.ntua.gr/blog/77-ssl-certificates
Once you get your certificate, you need to put it under your security directory within your jdk home, for example:
C:\Program Files\Java\jdk1.6.0_45\jre\lib\security
Hope this resolves your issue