OneMoreError
OneMoreError

Reputation: 7728

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

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("[email protected]");
        mailMessage.setFrom("[email protected]");


        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.

Upvotes: 1

Views: 2038

Answers (2)

asr9
asr9

Reputation: 21

I faced similar issue. I followed below 2 steps & it worked -

  1. In gmail settings, Turn ON access for less secure app.
  2. Antivirus settings. Turn off web-shield and mail-shield.

Upvotes: 1

Ali Dehghani
Ali Dehghani

Reputation: 48123

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.

Upvotes: 2

Related Questions