• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Springboot实现发送邮件

springboot 搞代码 4年前 (2022-01-09) 17次浏览 已收录 0个评论
文章目录[隐藏]

本文实例为大家分享了Springboot实现发送邮件功能的具体代码,供大家参考,具体内容如下

第一章 背景介绍

1.1 使用场景

1、注册验证;
2、网站营销;
3、安全的最后一道防线;
4、提醒、监控警告;
5、触发机制。

1.2 邮件发送原理

1.邮件传输协议:SMTP协议和POP3协议
2.内容不断发展:IMAP和Mme协议

1.3 邮件发送流程

第二章 使用SpringBoot完成邮件发送

2.1 开发流程

2.2 开发简单文本邮件

2.2.1 引入相关jar包

在pom.xml中添加依赖

<dependency>
  <gro<strong style="color:transparent">本文来源gao@daima#com搞(%代@#码@网&</strong>upId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2.2.2 配置邮箱参数

在配置文件里面配置:这里的密码是授权码,不是网页上的密码

spring.mail.host=smtp.163.com
[email protected]
spring.mail.password=XXX
spring.mail.default-encoding=utf-8

2.2.3 封装SimpleMailMessage

SimpleMailMessage message = new SimpleMailMessage();

2.2.4 JavaMailSender进行发送

@Autowired
private JavaMailSender mailSender;
//使用JavaMailSender发送邮件
mailSender.send(message);

具体的实现:

/**
 * @Description: 发送邮件
 * @Author: yzy
 * @Date:  2021/10/19 14:01
 **/
@Service
public class MailService {

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

    @Autowired
    private JavaMailSender mailSender;

    /**
     * @Description:  发送文本文件
     * @author:       yzy
     * @date:         2021/10/19 14:01
     * @Param:
     * @return:
     */
     public void sendSimpleMail(String to,String subject,String content) {
         SimpleMailMessage message = new SimpleMailMessage();
         //接收方
         message.setTo(to);
         //发送邮件的主题
         message.setSubject(subject);
         //发送邮件内容
         message.setText(content);
         //发送人
         message.setFrom(sendPeople);
         //使用JavaMailSender发送邮件
         mailSender.send(message);

     }

}

测试:

package com.yzy.restaurant.mapper;

import com.yzy.restaurant.MailService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

    @Autowired
    private MailService mailService;


    @Test
    public void sendSimpleMailTest() {
        mailService.sendSimpleMail("[email protected]","这是一个简单的demo","哈哈哈,发送成功了!");
    }
}

启动:


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Springboot实现发送邮件

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址