SpringBoot项目开发(十二):发送邮件_zhuyu19911016520-CSDN博客

沙海
沙海
沙海
1018
文章
2
评论
2021年4月28日12:00:45
评论
2 4253字阅读14分10秒
摘要

SpringBoot项目开发(十二):发送邮件

SpringBoot项目开发(十二):发送邮件

SpringBoot项目开发(十二):发送邮件_zhuyu19911016520-CSDN博客

闪耀的瞬间
2018-04-20 16:03:33
SpringBoot项目开发(十二):发送邮件_zhuyu19911016520-CSDN博客
672

SpringBoot项目开发(十二):发送邮件_zhuyu19911016520-CSDN博客

收藏


分类专栏:
spring boot
java
SpringBoot 项目开发
文章标签:
email

版权

SpringBoot项目开发(十二):发送邮件_zhuyu19911016520-CSDN博客

Spring Boot 发送邮件

1.引入依赖,在 pom.xml 文件中引入邮件配置:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>1234

2.配置文件

spring.mail.host=smtp.qq.com
spring.mail.username=xxxxxx@qq.com
spring.mail.password=xxxxxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true123456

使用QQ邮箱发送邮件,spring.mail.username为你的qq邮箱,需要将spring.mail.password改为QQ邮箱的授权码。 QQ邮箱->设置->账户->POP3/SMTP服务:开启服务后会获得QQ的授权码

3.代码实现

3.1新建一个类,用来告知收件人、主题、内容、附件等

public class EmailInfo {
    private String from;              //发件人(获取配置文件中的发送人信息)
    private String to;                //收件人
    private String subject;          //邮件主题
    private String content;          //邮件内容,(包括html)
    private List<String> attachPath; //附件路径

    //getter and setter
}123456789

3.2发送邮件的服务类(3个方法–1发送简单文本邮件、2发送Html邮件、3发送带附件邮件)

    @Autowired
    private JavaMailSender mailSender; //自动注入的Bean

    @Value("${spring.mail.username}")
    private String Sender; //读取配置文件中的参数 -- 发件人

    /**
     * 发送简单文本邮件
     * @param emailModel
     */
    public void sendSimpleMail(EmailInfo emailModel){
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(Sender);
            message.setTo(emailModel.getTo()); 
            message.setSubject(emailModel.getSubject());
            message.setText(emailModel.getContent());
            mailSender.send(message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 发送Html邮件
     * @param emailModel
     */
    public void sendHtmlMail(EmailInfo emailModel){
        MimeMessage message = null;
        try {
            message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(Sender);
            helper.setTo(emailModel.getTo());
            helper.setSubject(emailModel.getSubject());
            //StringBuffer sb = new StringBuffer();
            //sb.append("<h1>大标题-h1</h1>").append("<p style='color:#F00'>红色字</p>").append("<p style='text-align:right'>右对齐</p>");
            //helper.setText(sb.toString(), true);
            helper.setText(emailModel.getContent(), true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mailSender.send(message);
    }

    /**
     * 发送带附件的邮件
     * @param emailModel
     */
    public void sendAttachmentsMail(EmailInfo emailModel){
        MimeMessage message = null;
        try {
            message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(Sender);
            helper.setTo(emailModel.getTo());
            helper.setSubject(emailModel.getSubject());
            helper.setText(emailModel.getContent());  //发送普通邮件,发送html邮件要加一个boolean参数
            //注意项目路径问题,自动补用项目路径
            if(emailModel.getAttachPath() != null){
                for (String path : emailModel.getAttachPath()){
                    //FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/image/picture.jpg"));
                    FileSystemResource file = new FileSystemResource(new File(path));
                    //加入邮件
                    helper.addAttachment(file.getFilename(), file);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        mailSender.send(message);
    }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172

3.3运行测试发送邮件 ,在 ApplicationTests 中测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailApplicationTests {

    @Autowired
    private SendEmailService sendEmailService;

    //发送简单文本邮件
    @Test
    public void sendSimpleEmail(){
        EmailInfo model = new EmailInfo();
        model.setTo("xxxxxx@qq.com");
        model.setSubject("spring boot test send text email "+ new Date());
        model.setContent("test send email ,content is date :" + new Date());
        sendEmailService.sendSimpleMail(model);
    }

    //发送html邮件
    @Test
    public void sendHtmlEmail(){
        EmailInfo model = new EmailInfo();
        model.setTo("xxxxx@qq.com");
        model.setSubject("spring boot test send html email "+ new Date());

        StringBuffer html = new StringBuffer();
        html.append("<h1>大标题-h1</h1>").append("<p style='color:#F00'>test红色字</p>").append("<p style='text-align:right'>右对齐</p><div>恭喜您,邮件发送成功</div>");
        model.setContent(html.toString());
        sendEmailService.sendHtmlMail(model);
    }

    @Test
    public void sendAttachmentsMail(){
        EmailInfo model = new EmailInfo();
        model.setTo("xxxxx@qq.com");
        model.setSubject("spring boot test send attach email "+ new Date());
        model.setContent("test send email ,content is date :" + new Date());
        List<String> attachPath = new ArrayList<>();
        attachPath.add("src/main/resources/static/image/1.jpg");
        attachPath.add("src/main/resources/static/image/2.jpg");
        model.setAttachPath(attachPath);
        sendEmailService.sendAttachmentsMail(model);
    }
}12345678910111213141516171819202122232425262728293031323334353637383940414243

3.4测试结果:发送和接收都 successful SpringBoot项目开发(十二):发送邮件_zhuyu19911016520-CSDN博客

下篇 文件上传,监听、过滤非自身网站的请求,对资源进行防盗链等

继续阅读
weinxin
资源分享QQ群
本站是一个IT技术分享社区, 会经常分享资源和教程; 分享的时代, 请别再沉默!
沙海
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: