Java教程

springboot 整合mail 发送邮件

本文主要是介绍springboot 整合mail 发送邮件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

springboot 整合mail 发送邮件

 

pom.xml

<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
</dependencies>


application.properites

# 应用名称
spring.application.name=mail
# 应用服务 WEB 访问端口
server.port=8080
# THYMELEAF (ThymeleafAutoConfiguration)
# 开启模板缓存(默认值: true )
spring.thymeleaf.cache=true
# 邮箱用户名
spring.mail.username=359073594@qq.com
# 授权码
spring.mail.password=qltrocunzsqvcbdc
# 邮箱主机
spring.mail.host=smtp.qq.com
# 开启SSL
spring.mail.properties.mail.smtp.ssl.enable=true
# 认证
spring.mail.properties.mail.smtp.auth=true
# 开启SSL安全模式
spring.mail.properties.mail.smtp.starttls.enable=true
# 必须启动SSL安全模式
spring.mail.properties.mail.smtp.starttls.required=true
# SSL Config
# 端口
spring.mail.port=465
# 协议
spring.mail.protocol=smtp
# 默认编码
spring.mail.default-encoding=UTF-8
# 套接字工厂端口
spring.mail.properties.mail.smtp.socketFactory.port=465
# 套接字工厂类
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory

// 发送邮件的方法
@RestController
@RequestMapping("/mail")
public class Demo2 {

    //template模板引擎
    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private JavaMailSender javaMailSender;
    @RequestMapping("/send")
    public String send() {

        //建立邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        // 发送人的邮箱
        message.setFrom("359073594@qq.com");
        //标题
        message.setSubject("测试邮件");
        //发给谁  对方邮箱
        message.setTo("359073594@qq.com");
        //内容
        message.setText("这是一封测试的邮件");
        try {
            //发送
            javaMailSender.send(message);
        } catch (MailException e) {
            throw new RuntimeException("邮件发送失败");
        }
        return "发送完成!";
    }

    @RequestMapping("/tempSend")
    public String tempSend() {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            // 发送人的邮箱
            messageHelper.setFrom("359073594@qq.com");
            //发给谁  对方邮箱
            messageHelper.setTo("359073594@qq.com");
            //标题
            messageHelper.setSubject("测试邮件");
            //使用模板thymeleaf
            //Context是导这个包import org.thymeleaf.context.Context;
            Context context = new Context();
            //定义模板数据
            HashMap<String, Object> map = new HashMap<>();
            map.put("username","法外狂徒张三");
            List<User> list = new ArrayList<>();
            for (int i = 0; i < 4; i++) {
                User user = new User("list"+i,"而非留守",23+i);
                list.add(user);
            }
            map.put("listUser",list);
            map.put("img","../static/2.jpg");
            context.setVariables(map);
            //获取thymeleaf的html模板
            String emailContent = templateEngine.process("indexPatternMail.html",context); //指定模板路径

            messageHelper.setText(emailContent,true);
            //添加图片
            FileSystemResource file = new FileSystemResource(new File(Demo2.class.getResource("/static/2.jpg").getFile()));
            messageHelper.addInline("test001", file);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new RuntimeException("邮件发送失败");
        }
        return "发送成功了啊!";
    }

    @RequestMapping("/sendImageMail")
    public void sendImageMail() throws MessagingException {
        //创建message
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        //发件人
        helper.setFrom("359073594@qq.com");
        //收件人
        helper.setTo("359073594@qq.com");
        //标题
        helper.setSubject("测试邮件");
        //true指的是html邮件,false指的是普通文本
        helper.setText("<h1 style='color:red'>helloWorld</h1><img src='cid:test001'/>", true);
        //添加图片
        FileSystemResource file = new FileSystemResource(new File(Demo2.class.getResource("/static/2.jpg").getFile()));
        helper.addInline("test001", file);
        //发送邮件D:\java_code\email\src\main\resources\static\2.jpg
        javaMailSender.send(message);
    }


}
// 携带附件信息
 public void sendMimeMessage() throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("mail sender");
        helper.setTo("mail receiver");
        helper.setSubject("title");
        File file = new File("your file");
        helper.addAttachment(file.getName(), file);
        // 带附件邮件正文必须显式设置一次,可以为空字符
        helper.setText("hello world");
        mailSender.send(message);
    }


// 模板的集合遍历

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>title</title>
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
<h3>你看我<span style="font-size: 35px" th:text="${username}"></span>, 哈哈哈!</h3>
<div>
    <table >
        <tr>
            <th>名称</th>
            <th>年龄</th>
            <th>英雄</th>
        </tr>
        <tr th:each="c, State : ${listUser}">
            <td th:text="${c.name}"></td>
            <td th:text="${c.age}"></td>
            <td th:text="${c.lol}"></td>
        </tr>
    </table>
</div>
<h1 style='color:red'>helloWorld</h1><img src='cid:test001'/>
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
    // 基于准备好的dom,初始化echarts实例
    var myChart = echarts.init(document.getElementById('main'));

    // 指定图表的配置项和数据
    console.log('123');
    var option = {
        title: {
            text: '第一个 ECharts 实例'
        },
        tooltip: {},
        legend: {
            data:['销量']
        },
        xAxis: {
            data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
        },
        yAxis: {},
        series: [{
            name: '销量',
            type: 'bar',
            data: [5, 20, 36, 10, 10, 20]
        }]
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
</script>
</body>
</html>
 
这篇关于springboot 整合mail 发送邮件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!