Springboot2 整合mail 发送邮件

引入依赖
<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
编写 application.properties 文件
#邮箱服务器
#关于服务器设置 https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=369
spring.mail.host=smtp.qq.com
#邮箱账户
spring.mail.username=1310072293@qq.com
#QQ邮箱第三方授权码
spring.mail.password=第三方授权码
#编码类型
spring.mail.default-encoding=UTF-8
具体代码
package me.yundongis.service.impl;

import me.yundongis.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class MailServiceImpl implements MailService {

    //注入application.properties中指定的用户名
    @Value("${spring.mail.username}")
    private String from;

    //用于发送文件
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送普通文本邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);//收信人
        message.setSubject(subject);//主题
        message.setText(content);//内容
        message.setFrom(from);//发信人
        mailSender.send(message);
    }

    /**
     * 发送HTML邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容(可以包含<html>等标签)
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        //使用MimeMessage,MIME协议
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper;
        //MimeMessageHelper帮助我们设置更丰富的内容
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            //true代表支持html
            helper.setText(content, true);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }


    /**
     * 发送带附件的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param filePath 附件路径
     */
    @Override
    public void sendAttachmentMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            //true代表支持多组件,如附件,图片等
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);//添加附件,可多次调用该方法添加多个附件
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }


    /**
     * 发送带图片的邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 文本
     * @param rscPath 图片路径
     * @param rscId   图片ID,用于在<img>标签中使用,从而显示图片
     */
    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource res = new FileSystemResource(new File(rscPath));
            // 添加图片
            helper.addInline(rscId, res);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Controller
package me.yundongis.controller;

import me.yundongis.service.impl.MailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class MailController {

    //发送操作
    @Autowired
    private MailServiceImpl mailServiceimpl;

    /**
     * 发送普通邮件
     */
    @RequestMapping("/sendSimpleMail")
    public Object sendSimpleMail() {
        mailServiceimpl.sendSimpleMail("1637378732@qq.com", "hello", "this is send mail test");
        return "OK";
    }

    /**
     * 发送HTML邮件
     */
    @RequestMapping("/sendHtmlMail")
    public Object sendHtmlMail() {
        String html = "<h1>Hello</h1>";
        mailServiceimpl.sendHtmlMail("1637378732@qq.com", "hello", html);
        return "OK";
    }

    /**
     * 发送带附件的邮件
     */
    @RequestMapping("/sendAttachmentMail")
    public Object sendAttachmentMail() {
        String html = "<h1>Hello</h1>";
        mailServiceimpl.sendAttachmentMail("1637378732@qq.com", "hello", html, "/Users/annie/Documents/ViewSonic VX2478-4K-525.icc");
        return "OK";
    }

    /**
     * 发送带图片的邮件
     */
    @RequestMapping("/sendInlineResourceMail")
    public Object sendInlineResourceMail() {
        String rscPath = "/Users/annie/Documents/37401462.jpg";
        String rscId = "001";
        // 这里的 cid 必须要加
        String content = "<img src='cid:" + rscId + "'>";
        mailServiceimpl.sendInlineResourceMail("1637378732@qq.com", "hello", content, rscPath, rscId);
        return "OK";
    }


}


扩展内容
github
个人博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值