SpringBoot整合Mail发送邮件&发送模板邮件

一、pom文件引入依赖
复制代码

org.springframework.boot
spring-boot-starter-mail

org.springframework.boot spring-boot-starter-freemarker 复制代码 二、application.yml文件中配置 复制代码 spring: mail: host: smtp.qq.xyz #这里换成自己的邮箱类型 例如qq邮箱就写smtp.qq.com username: xx@qq.com #QQ邮箱 password: xxxxxxxxxxx #邮箱密码或者授权码 protocol: smtp #发送邮件协议 properties.mail.smtp.auth: true properties.mail.smtp.port: 465 #端口号465或587 properties.mail.smtp.starttls.enable: true properties.mail.smtp.starttls.required: true properties.mail.smtp.ssl.enable: true #开启SSL default-encoding: utf-8 freemarker: cache: false # 缓存配置 开发阶段应该配置为false 因为经常会改 suffix: .html # 模版后缀名 默认为ftl charset: UTF-8 # 文件编码 template-loader-path: classpath:/templates/ # 存放模板的文件夹,以resource文件夹为相对路径 复制代码 邮箱密码暴露在配置文件很不安全,一般都是采取授权码的形式。点开邮箱,然后在账户栏里面点击生成授权码:

三、编写MailUtils工具类
复制代码
@Component
@Slf4j
public class MailUtils{

/**
 * Spring官方提供的集成邮件服务的实现类,目前是Java后端发送邮件和集成邮件服务的主流工具。
 */
@Resource
private JavaMailSender mailSender;

/**
 * 从配置文件中注入发件人的姓名
 */
@Value("${spring.mail.username}")
private String fromEmail;

@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;

/**
 * 发送文本邮件
 * @param to      收件人
 * @param subject 标题
 * @param content 正文
 */
public void sendSimpleMail(String to, String subject, String content) {
    SimpleMailMessage message = new SimpleMailMessage();
    //发件人
    message.setFrom(fromEmail);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    mailSender.send(message);
}

/**
 * 发送html邮件
 */
public void sendHtmlMail(String to, String subject, String content) {
    try {
        //注意这里使用的是MimeMessage
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(fromEmail);
        helper.setTo(to);
        helper.setSubject(subject);
        //第二个参数:格式是否为html
        helper.setText(content, true);
        mailSender.send(message);
    }catch (MessagingException e){
        log.error("发送邮件时发生异常!", e);
    }
}

/**
 * 发送模板邮件
 * @param to
 * @param subject
 * @param template
 */
public void sendTemplateMail(String to, String subject, String template){
    try {
        // 获得模板
        Template template1 = freeMarkerConfigurer.getConfiguration().getTemplate(template);
        // 使用Map作为数据模型,定义属性和值
        Map<String,Object> model = new HashMap<>();
        model.put("myname","Ray。");
        // 传入数据模型到模板,替代模板中的占位符,并将模板转化为html字符串
        String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template1,model);
        // 该方法本质上还是发送html邮件,调用之前发送html邮件的方法
        this.sendHtmlMail(to, subject, templateHtml);
    } catch (TemplateException e) {
        log.error("发送邮件时发生异常!", e);
    } catch (IOException e) {
        log.error("发送邮件时发生异常!", e);
    }
}

/**
 * 发送带附件的邮件
 * @param to
 * @param subject
 * @param content
 * @param filePath
 */
public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
    try {
        MimeMessage message = mailSender.createMimeMessage();
        //要带附件第二个参数设为true
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(fromEmail);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        FileSystemResource file = new FileSystemResource(new File(filePath));
        String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
        helper.addAttachment(fileName, file);
        mailSender.send(message);
    }catch (MessagingException e){
        log.error("发送邮件时发生异常!", e);
    }

}

}
复制代码
MailUtils其实就是进一步封装Mail提供的JavaMailSender类,根据业务场景可以在工具类里面添加对应的方法,这里提供了发送文本邮件、html邮件、模板邮件、附件邮件的方法。

四、Controller层的实现
复制代码
@Api(tags = “邮件管理”)
@RestController
@RequestMapping("/mail")
public class MailController {

@Autowired
private MailUtils mailUtils;

/**
 * 发送注册验证码
 * @return 验证码
 * @throws Exception
 */
@ApiOperation("发送注册验证码")
@GetMapping("/test")
public String send(){
    mailUtils.sendSimpleMail("ruiyeclub@foxmail.com","普通文本邮件","普通文本邮件内容");
    return "OK";
}

/**
 * 发送注册验证码
 * @return 验证码
 * @throws Exception
 */
@ApiOperation("发送注册验证码")
@PostMapping("/sendHtml")
public String sendTemplateMail(){
    mailUtils.sendHtmlMail("ruiyeclub@foxmail.com","一封html测试邮件",
            "<div style=\"text-align: center;position: absolute;\" >\n"
                    +"<h3>\"一封html测试邮件\"</h3>\n"
                    + "<div>一封html测试邮件</div>\n"
                    + "</div>");
    return "OK";
}

@ApiOperation("发送html模板邮件")
@PostMapping("/sendTemplate")
public String sendTemplate(){
    mailUtils.sendTemplateMail("ruiyeclub@foxmail.com", "基于模板的html邮件", "hello.html");
    return "OK";
}

@ApiOperation("发送带附件的邮件")
@GetMapping("sendAttachmentsMail")
public String sendAttachmentsMail(){
    String filePath = "D:\\projects\\springboot\\template.png";
    mailUtils.sendAttachmentsMail("xxxx@xx.com", "带附件的邮件", "邮件中有附件", filePath);
    return "OK";
}

}
复制代码
为了方便测试,这里使用了swagger3,详情可以查看SpringBoot整合Swagger3生成接口文档。

发送模板邮件这里,会读取resources下面的templates文件夹,测试中读取的是hello.html,具体代码如下:

复制代码

freemarker简单示例

Hello Freemarker

My name is ${myname}
深圳网站建设www.sz886.com
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了`JavaMailSender`来发送邮件,下面是整合Mail发送邮件的步骤: 1. 添加依赖:在`pom.xml`文件中添加`spring-boot-starter-mail`依赖。 2. 配置邮件信息:在`application.yml`文件中配置邮件信息,包括邮件服务器的地址、端口号、发送者的邮箱地址、用户名、密码等。 3. 发送邮件:在需要发送邮件的地方注入`JavaMailSender`,调用其`send()`方法发送邮件。 具体代码如下: 1. 添加依赖 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 2. 配置邮件信息 ```yml spring: mail: host: smtp.qq.com # 邮件服务器的地址 port: 587 # 邮件服务器的端口号 username: your-email@qq.com # 发送者的邮箱地址 password: your-email-password # 邮箱密码或者授权码 properties: mail.smtp.auth: true mail.smtp.starttls.enable: true mail.smtp.starttls.required: true mail.smtp.ssl.trust: smtp.qq.com # 邮件服务器的地址 ``` 3. 发送邮件 ```java @Service public class MailService { @Autowired private JavaMailSender mailSender; public void sendMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(content); message.setFrom("your-email@qq.com"); // 发送者的邮箱地址 mailSender.send(message); } } ``` 这里使用了`SimpleMailMessage`来设置邮件信息,可以设置收件人、主题、内容等。通过`JavaMailSender`的`send()`方法发送邮件。 需要注意的是,如果邮件服务器需要使用SSL/TLS等加密方式,需要在`application.yml`中设置相应的属性。另外,如果使用的是第三方邮件服务商,可能需要开启SMTP服务和获取授权码等操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值