Spring : Unable to send mail- Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1 - spring

I am trying to send an email through my spring boot app. However, I am getting the following exception:
Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
The controller class is as follows :
#RestController
#RequestMapping("/services")
public class MyController {
#Autowired
private MailSender mailSender;
#RequestMapping(value = "/my/mail", method = RequestMethod.GET)
#ResponseBody
public String sendmymail() {
System.out.println("Starting send");
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("Hello");
mailMessage.setTo("myemailid#gmail.com");
mailMessage.setFrom("myemailid#gmail.com");
SimpleMailMessage message = new SimpleMailMessage(mailMessage);
message.setText("Hello");
try {
this.mailSender.send(message);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("Finished send");
return "OK";
}
}
I have configured the properties in application.properties as follows :
spring.mail.host=smtp.gmail.com
spring.mail.port=465
spring.mail.username=<myemailid>
spring.mail.password=<mypassword>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.transport.protocol=smtps
spring.mail.properties.mail.smtps.quitwait=false
spring.mail.properties.mail.smtp.socketFactory=25
I have added the folllowing dependecy in pom.xml for autowiring MailSender:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
Is there anything that I am doing wrong. The email id and password is correct, as I have checked it multiple times.

Port number for google smtp server is 587:
spring.mail.port=587
Maybe add this too:
spring.mail.properties.mail.smtp.starttls.enable = true
I managed to send emails with my gmail account without these three config values:
spring.mail.properties.mail.transport.protocol=smtps
spring.mail.properties.mail.smtps.quitwait=false
spring.mail.properties.mail.smtp.socketFactory=25
I have no idea what are they but guess you should be ok without them.

I faced similar issue. I followed below 2 steps & it worked -
In gmail settings, Turn ON access for less secure app.
Antivirus settings. Turn off web-shield and mail-shield.

Related

sudden gmail smtp authentication failure when using app password

So I am trying to set up a spring boot app to send out automated emails. I have created a gmail account specifically for this purpose. I followed a tutorial which directed me to set up two factor authentication for my gmail account, and set up an app password to login. I did this and everything worked fine, I sent a test email from the app and it worked. HOWEVER without making any code changes I tried the proccess again a few hours later and I got the following message:
Exception in thread "main" org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 534-5.7.9 Please log in with your web browser and then try again. Learn more at
534 5.7.9 https://support.google.com/mail/?p=WebLoginRequired v8-20020a05683018c800b005cb39fc3e15sm11417144ote.13 - gsmtp
Here is my application.properties file:
spring.mail.protocol=smtp
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=
spring.mail.password=
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
mail.smtp.debug=true
and here is my mail service (although this error occurs at app startup so I dont think its the cause)
#Service("mailService")
public class MailServiceImpl implements MailService {
#Autowired
private JavaMailSender mailSender;
public void sendEmail(Mail mail) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setSubject(mail.getMailSubject());
mimeMessageHelper.setFrom(new InternetAddress(mail.getMailFrom(), "tyler"));
mimeMessageHelper.setTo(mail.getMailTo());
mimeMessageHelper.setText(mail.getMailContent());
mailSender.send(mimeMessageHelper.getMimeMessage());
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
I have tried following the link for advice but it recommends I use an app password (which I already am) or to enable "less secure apps" (which I cant as a 2FA user). Any help would be greatly appreciated.

Spring JAVA SSL - No name matching localhost found

I have two SSL end-points that share the same application.properties and key store file.
I want to have one end-point call the other, but getting an error No name matching localhost found
How can I adjust this to allow one microservice to call the other(s) as intended below?
I have played with the following to attempt a solution to no avail:
javax.net.ssl.HostnameVerifier()
Created a localhost certificate and added it to the keystore
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
public class submitapplicationcontroller {
#Bean
public WebClient.Builder getWebClientBuilder(){
return WebClient.builder();
}
#Autowired private WebClient.Builder webClientBuilder;
#PostMapping("/submitapplication")
public String submitapplication() {
/*** Returns Error Found Below ***/
String response = webClientBuilder.build()
.post()
.uri("https://localhost:8080/validateaddress")
.retrieve()
.bodyToMono(String.class)
.block();
return response;
}
}
javax.net.ssl.SSLHandshakeException: No name matching localhost found
at java.base/sun.security.ssl.Alert.createSSLException
Error has been observed at the following site(s):
|_ checkpoint ⇢ Request to POST https://localhost:8080/v1/validateaddress
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
public class validateaddresscontroller {
#PostMapping("/validateaddress")
public String validateaddress() {
return "response";
}
}
server.ssl.key-alias=server
server.ssl.key-password=asensitivesecret
server.ssl.key-store=classpath:server.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS
server.ssl.key-store-password=asensitivesecret
The problem here was the way I went about creating and implementing the certificates. I had 2 separate keystores and certificates; one named "server", and one named "localhost". I added the localhost certificate to the server keystore, and applied the server keystore and certificate to the springboot application / application.properties.
What you have to do is create just one certificate and keystore dubbed "localhost" and you have to use that to apply to the application / application.properties.
What you should have after creating the localhost JKS and certificate
server.ssl.key-alias=localhost
server.ssl.key-password=asensitivesecret
server.ssl.key-store=classpath:localhost.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS
server.ssl.key-store-password=asensitivesecret
Note: I don't believe you actually have to create a JKS named "localhost", just the certificate. I just did for testing purposes.

Spring and SimpleMailMessage: change setTo and setFrom

I am building a Spring app that allows the user to send an email to customer support.
I have noticed though that it doesn't matter what I put in the attributes "setTo" and "setFrom" of the SimpleMailMessage, I keep receiving the email from myself to myself.
Here is my code:
Controller Endpoint
#PostMapping("/send-email")
public ResponseEntity<Object> sendEmail(#RequestParam String userEmail) {
log.info("[START] send-email");
notificationService.sendNotification();
return new ResponseEntity<>(HttpStatus.OK);
}
Service
public void sendNotification(String emailUtente) {
SimpleMailMessage messaggio = new SimpleMailMessage();
messaggio.setTo(customerServiceAddress);
messaggio.setFrom(emailUtente);
messaggio.setSubject("Test Spring Email");
messaggio.setText("Tadaaaa! Email da Spring!");
try{
javaMailSender.send(messaggio);
} catch (Exception ex){
log.error("Error! " + ex.getMessage());
}
}
application.properties
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=theCustomerServiceAddress
spring.mail.password=thePassword
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
Where am I mistaking?
Also, I am not sure what should be put into the property spring.mail.username, I guessed the email address of whom is receiving the email?
Thank you for your experience and time.

Spring Email: Must issue a STARTTLS command first

I am trying to send a simple email to myself using Spring Email, but I'm encountering the following exception:
org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. p4sm7233776wrx.63 - gsmtp
; message exceptions (1) are:
Failed message 1: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. p4sm7233776wrx.63 - gsmtp
By googling it I saw that most people fixed this by adding the property spring.mail.properties.mail.smtp.starttls.enable=true, but I have already done it and isn't working in my case.
My application.properties:
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=myEmail#gmail.com
spring.mail.password=********
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.auth=true
My code:
#Service
#Slf4j
public class NotificationService {
#Autowired
private JavaMailSender javaMailSender;
public void sendNotification() {
SimpleMailMessage messaggio = new SimpleMailMessage();
messaggio.setTo("myEmail#gmail.com");
messaggio.setFrom("YourSpringFriend#gmail.com");
messaggio.setSubject("Test Spring Email");
messaggio.setText("Tadaaaa! Email da Spring!");
javaMailSender.send(messaggio);
}
}
What am I doing wrong?
Thanks in advance for your time and experience
Add this property in your application.properties
spring.mail.properties.mail.smtp.starttls.enable=true
This work fine

javax.mail.MessagingException: Could not connect to SMTP host or don't receive any email when using ionos

I have spring boot application and want's to send eamil using ionos. these are email configuration that i used:
#Configuration
public class MailConfiguration {
#Autowired
private Environment env;
#Bean
public JavaMailSender getMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(env.getProperty("spring.mail.host"));
mailSender.setPort(Integer.parseInt(env.getProperty("spring.mail.port")));
mailSender.setUsername(env.getProperty("spring.mail.username"));
mailSender.setPassword(env.getProperty("spring.mail.password"));
return mailSender;
}
}
spring:
mail:
host: smtp.ionos.com
port: 465
username: support#mysite.com
password: password
with 465 port i get this error:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.ionos.com, port: 465, response: -1
and with 587 port, i didn't get any error, but also didn't receive any email email in inbox.
If you're still stuck on this. Please check your DNS record with Ionos staff to make sure everything is as it should be and then - if it still isn't working, use Dror's answer from here because it worked for me.
Basically, the errors from Ionos are a red herring. You need to set the from field in your JavaMailSender method:
helper.setFrom(your email here);
It's easy to overlook this because Gmail has looser sec protocols and doesn't need it.
Hope that helps.

Resources