gpt4 book ai didi

如何使用Spring Boot发送邮件

转载 作者:知者 更新时间:2024-03-12 08:30:07 24 4
gpt4 key购买 nike

Spring 框架通过使用 JavaMailSender 接口为发送电子邮件提供了一个简单的抽象,Spring Boot 为其提供了自动配置以及一个启动模块。 首先创建一个使用“mail”启动模块的新项目:

spring init -dmail demo-mail

将添加以下依赖项:

<?xml version="1.0" encoding="UTF-8"?><project>
   <dependencies>
       	
      <dependency>
          		
         <groupId>org.springframework.boot</groupId>
          		
         <artifactId>spring-boot-starter-mail</artifactId>
          	
      </dependency>
       	
      <dependency>
          		
         <groupId>org.springframework.boot</groupId>
          		
         <artifactId>spring-boot-starter-test</artifactId>
          		
         <scope>test</scope>
          	
      </dependency>
       
   </dependencies>
</project>

接下来,添加一个使用 JavaMailSender 接口发送邮件消息的类:

package com.example.demomail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
@Service public class MailClient {
  private JavaMailSender mailSender;
  @Autowired public MailClient(JavaMailSender mailSender) {
    this.mailSender = mailSender;
  }
  public void prepareAndSend(String recipient, String message) {
    MimeMessagePreparator messagePreparator = mimeMessage -> {
      MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);messageHelper.setFrom("john.doeATgmail.com");messageHelper.setTo(recipient);messageHelper.setSubject("Sample mail subject");messageHelper.setText(message);
    };
    try {
      mailSender.send(messagePreparator);
    } catch (MailException e) {
      // runtime exception; compiler will not force you to handle it
    }
  }
}

最后,您可以将 SMTP 配置包含到 application.properties 文件中:

spring.mail.host=localhost spring.mail.port=25 spring.mail.username= spring.mail.password=   spring.mail.protocol=smtp

邮件属性也可以使用 JavaMailSenderImpl 以编程方式定义。 例如:

@Bean public JavaMailSender getJavaMailSender() {
  JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
  mailSender.setHost("smtp.gmail.com");
  mailSender.setPort(587);
  mailSender.setUsername("john.doeATgmail.com");
  mailSender.setPassword("12345678");
  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;
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com