原创 | Springboot发邮件,你还不会来打我

大家好,我是润森。期末化学已挂,谁来烧纸,挂得又有动力学习了?

Python发邮件

Python发邮件是个小儿科,只需要使用 smtplib和email

smtplib是用来发送邮件用的,email是用来构建邮件内容的。

具体博客链接:https://maoli.blog.csdn.net/article/details/89857715

小儿科的东西就不一一论述了

Java发邮件

菜鸟教程迎接有具体教程,

https://www.runoob.com/java/java-sending-email.html

mavenjavax.mail

创建maven工程,就搞定

<!-- https://mvnrepository.com/artifact/cn.howardliu/gear-email -->
<dependency>
    <groupId>cn.howardliu</groupId>
    <artifactId>gear-email</artifactId>
    <version>1.0.1-RELEASE</version>
</dependency>

搜了下Email竟然高达600多jar包,可见Java得强大

其中使用Springboot发邮件,广泛运用

使用Springboot发邮件

Spring 提供了JavaMailSender 接口帮我们来实现邮件的发送。在SpringBoot 更是提供了邮件的发送的 starter 依赖来简化邮件发送代码的开发 。

开通SMTP服务

需要拿到授权码

创建SpringBoot项目

创建SpringBoot项目,只需要引用Web模块即可

在项目的pom.xml文件中引用spring-boot-starter-mail

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

application.properties项目配置

[email protected]
spring.mail.password=授权码
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true
TaskApplicationTests.java测试类

只需要wiredJavaMailSenderImpl进行@Auto标注就ok

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.SimpleMailMessage;

@SpringBootTest
class TaskApplicationTests {

    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("通知-润森有空写书");
        simpleMailMessage.setText("今晚7:30写下博客");
        simpleMailMessage.setTo("[email protected] ");
        simpleMailMessage.setFrom("[email protected]");
        mailSender.send(simpleMailMessage);
    }
}

运行测试,这样我的QQ邮箱[email protected]发送邮件到我的126邮箱[email protected]

成功接收

上传文件

发个消息有什么意思呢?我万一要发个文件怎么办?

文件

其实创建一个复杂的消息邮件mailSender,mailSender是Java内置的jar包,通过addAttachment方法简单解决

@Test
    public void test02() throws Exception {
        //1、创建一个复杂的消息邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        //邮件设置
        helper.setSubject("通知-润森交下书最近的情况");
        helper.setText("<b style='color:red'>其实我啥都没写</b>", true);

        helper.setTo("[email protected] ");
        helper.setFrom("[email protected]");


        //上传文件
        helper.addAttachment("第二章.md", new File("C:\\Users\\YIUYE\\Desktop\\数据之道\\Python数据分析\\第二章.md"));


        mailSender.send(mimeMessage);

    }

成功接受

结语

SpringBoot中集成邮件服务记录,小白成长中,望不吝赐教

再自我介绍一下吧。我叫润森,是一个的学习者,分享自己的所学所得。

关注我,和我一样变得更强大

扫描公众号回复IDEA关键字领取破解文档和jar包。

发布了790 篇原创文章 · 获赞 100 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/weixin_44510615/article/details/103848674