JAVA Spring邮件通过gmail发送

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (122)

我想使用gmail smtp服务器和弹簧邮件发件人发送电子邮件,它不会抛出任何异常,但我的邮件没有发送,我没有收到它。

以下是服务的外观:

@Service
public class MailSenderService {

    @Autowired
    public MailSender mailSender;

    public void prepareAndSend(String recipient, String message) {
        try {

            SimpleMailMessage mail = new SimpleMailMessage();
            String from = "testSender1@gmail.com";
            String to = "testRecipient1@gmail.com";
            String subject = "Test subject";
            mail.setFrom(from);
            mail.setTo(recipient);
            mail.setSubject(subject);
            mail.setText(message);
            mailSender.send(mail);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

AppProperties

spring.mail.host = smtp.gmail.com
spring.mail.username = ********@gmail.com
spring.mail.password = ********
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 = true

和pom依赖

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

我在端口8080上部署我的应用程序,并使用这两个参数调用此服务,没有捕获异常,但在我的testRecipient1收件箱中我找不到任何新邮件,我错过了什么?

提问于
用户回答回答于

如果你没有在你的网络应用程序中使用SSL证书而不是尝试我的代码,它在spring启动,文本邮件和HTML邮件中都能很好地工作。

@Autowired
private JavaMailSender mailSender;

@RequestMapping(value="/ShareVecancy",method=RequestMethod.GET)
public ModelAndView sendEmailToReference(HttpServletRequest request,HttpSession session){

    try {

            MimeMessage mail = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mail, true);
            messageHelper.setTo("reciverEmail@mail.com");
            messageHelper.setSubject("Testing mail");
            messageHelper.setText("HTML Text or Any text You want to send ", true);
            mailSender.send(mail);

        } catch (MailException e) {
            e.printStackTrace();
        }


}

Property File:::

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=xyz@gmail.com
spring.mail.password=*******
spring.mail.protocol=smtp
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.default-encoding=UTF-8

Dependency ::

 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
用户回答回答于

application.yml示例(使用Spring Boot 2.1.1测试):

spring
  mail:
    host: smtp.gmail.com
    username: youremail@gmail.com
    port: 587
    password: ******
    protocol: smtp
    properties:
      mail:
        smtp:
          starttls:
            enable: true

扫码关注云+社区

领取腾讯云代金券