小工具知识网

当前位置: 首页 > 行业知识 > SpringBoot集成mail

行业知识

SpringBoot集成mail

2026-11-06 05:04:26 来源:互联网转载

发送邮件:SMPT、MIME,是一种基于"推"的协议,通过SMPT协议将邮件发送至邮件服务器,MIME协议是对SMPT协议的一种补充,如发送图片附件等

()

接收邮件:POP、IMAP,是一种基于"拉"的协议,收件人通过POP协议从邮件服务器拉取邮件

账号准备:mail 客户端设置说明:参考官方Gmail帮助

()

一、依赖

            springboot-demo        com.et        1.0-SNAPSHOT        4.0.0    mail            8        8                            org.springframework.boot            spring-boot-starter-web                            org.springframework.boot            spring-boot-autoconfigure                            org.springframework.boot            spring-boot-starter-mail                            org.springframework.boot            spring-boot-starter-test            test                            org.springframework.boot            spring-boot-starter-thymeleaf            

二、配置文件和启动类

application.properties

#这里以qq邮箱为例# qq邮箱服务器spring.mail.host=smtp.qq.com# 你的qq邮箱账户spring.mail.username=yourAccount@qq.com# 你的qq邮箱第三方授权码spring.mail.password=yourPassword# 编码类型spring.mail.default-encoding=UTF-8spring.thymeleaf.prefix=classpath:/template/
@SpringBootApplicationpublic class DemoApplication {   public static void main(String[] args) {      SpringApplication.run(DemoApplication.class, args);   }}

三、MailUtil.java

@Servicepublic class MailUtils{// 日志    private final Logger logger = LoggerFactory.getLogger(MailUtils.class);       @Value("${spring.mail.username}") //注入 application.properties中指定的用户名    private String from;@Autowired //用于发送文件    private JavaMailSender mailSender;//发送普通文本邮件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邮件public void sendHtmlMail(String to, String subject, String content){//使用MimeMessage,MIME协议        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);//true代表支持html            mailSender.send(message);            logger.info("发送HTML邮件成功");        } catch (MessagingException e) {            e.printStackTrace();            logger.error("发送HTML邮件失败:", e);        }}//发送带附件的邮件public void sendAttachmentMail(String to, String subject,String content, String filePath){// 日志        logger.info("发送带附件邮件开始:{},{},{},{}", to, subject, content, 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);            logger.info("发送带附件邮件成功");        } catch (MessagingException e) {            logger.error("发送带附件邮件失败", e);        }}//发送带图片的邮件public void sendInlineResourceMail( String to, String subject, String content,String rscPath, String rscId){// 日志        logger.info("发送带图片邮件开始:{},{},{},{},{}", to, subject, content, rscPath, 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);            logger.info("发送带图片邮件成功");        } catch (MessagingException e) {            logger.error("发送带图片邮件失败", e);        }}}

四、邮件模板

        邮件模板您好,感谢您的注册,这是一封验证邮件,请点击下面的链接完成注册,感谢您的支持!
激活账户

测试:

@RunWith(SpringRunner.class)@SpringBootTest(classes = DemoApplication.class)public class SpringBootApplicationTest {    @Autowired    MailUtils mailUtils;    @Autowired    private TemplateEngine templateEngine;    /**     * 指定模板发送邮件     */    /**     * 指定模板发送邮件     */    @Test    public void testTemplateMail() {        //向Thymeleaf模板传值,并解析成字符串        Context context = new Context();        context.setVariable("id", "001");        String emailContent = templateEngine.process("emailTemplate", context);        mailUtils.sendHtmlMail("zhaokuii11@163.com", "这是一个模板文件", emailContent);    }    /**     * 发送简单纯文本邮件     */    @Test    public void sendSimpleMail() {        mailUtils.sendSimpleMail("zhaokuii11@163.com", "发送邮件测试", "大家好,这是我用springboot进行发送邮件测试");    }    /**     * 发送HTML邮件     */    @Test    public void sendHtmlMail() {        String content = "

" + "大家好,这是springboot发送的HTML邮件" + "

"; mailUtils.sendHtmlMail("zhaokuii11@163.com", "发送邮件测试", content); } /** * 发送带附件的邮件 */ @Test public void sendAttachmentMail() { String content = "

" + "大家好,这是springboot发送的HTML邮件,有附件哦" + "

"; String filePath = "your file path"; mailUtils.sendAttachmentMail("zhaokuii11@163.com", "发送邮件测试", content, filePath); } /** * 发送带图片的邮件 */ @Test public void sendInlineResourceMail() { String rscPath = "your picture path"; String rscId = "001"; String content = "

" + "大家好,这是springboot发送的HTML邮件,有图片哦" + "

" + ""; mailUtils.sendInlineResourceMail("zhaokuii11@163.com", "发送邮件测试", content, rscPath, rscId); }}

上一篇:WP源码建站零基础教程,轻松搭建网站,上手无忧!

下一篇:magento怎么样?