一起学习Spring boot 2.1.X | 第二十三篇:Email

1.依赖



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

2.EmailUtil工具类
 

package com.demo.utils;

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.internet.MimeMessage;
import java.io.File;


@Service
public class EmailUtil {

    @Value("${spring.mail.username}")
    private String username;

    @Autowired
    private JavaMailSender mailSender;



    //文本邮件
    public void sendSimpleEmail() {
        // 构造Email消息
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(username);
        message.setTo("[email protected]");
        message.setSubject("邮件主题");
        message.setText("邮件内容");


        //添加附件,第一个参数表示添加到 Email 中附件的名称,第二个参数是图片资源
//        message("boot.png", new ClassPathResource("public/images/boot.png"));
        mailSender.send(message);
    }

    //Html
    public void sendHtmlMail(String Sender) {
        MimeMessage message = null;
        try {
            message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(username);
            helper.setTo(Sender);
            helper.setSubject("标题:发送Html内容");

            StringBuffer sb = new StringBuffer();
            sb.append("

大标题-h1

") .append("

红色字

") .append("

右对齐

"); helper.setText(sb.toString(), true); } catch (Exception e) { e.printStackTrace(); } mailSender.send(message); } //资源邮件 public void sendInlineMail(String Sender) { MimeMessage message = null; try { message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(username); helper.setTo(Sender); helper.setSubject("主题:带静态资源的邮件"); //第二个参数指定发送的是HTML格式,同时cid:是固定的写法 helper.setText("带静态资源的邮件内容 图片:", true); FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/image/picture.jpg")); helper.addInline("picture",file); } catch (Exception e){ e.printStackTrace(); } mailSender.send(message); } }

3.测试

 @Autowired
    private EmailUtil emailUtil;

    @RequestMapping("/")
    public String start(){
        emailUtil.sendSimpleEmail();
        return "Success";
    }

 

你可能感兴趣的:(Spring,boot,2.1.X)