• springboot发送邮件


    springboot发送邮件

    邮件发送,在我们的日常开发中,也非常的多,Springboot也帮我们做了支持

    • 邮件发送需要引入spring-boot-start-mail
    • SpringBoot 自动配置MailSenderAutoConfiguration
    • 定义MailProperties内容,配置在application.yml中
    • 自动装配JavaMailSender
    • 测试邮件发送

    1. 引入依赖

    依赖: Java Mail Sender

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

    2. 配置文件

    简易配置:

    spring:
        mail:
            # 邮件服务地址
            host: smtp.qq.com
            # qq邮箱
            username: *****@qq.com
            # 授权码(注意! 不是邮箱密码)
            password: arpaxwwaeoqvtbceb # 经加密处理
            # other
            properties:
              mail:
                # 是否开启SSL(QQ邮箱请开启)
                smtp:
                  ssl:
                    enable: true
    

    完整配置:

    spring:
      mail:
        # 邮件服务地址
        host: smtp.qq.com
        # 邮件服务端口
        port: 465
        # 编码格式
        default-encoding: UTF-8
        # qq邮箱
        username: ****@qq.com
        # 授权码(注意! 不是邮箱密码)
        password: arpaxwwaeoqvtbceb # 经加密处理
        # 协议
        protocol: smtp
        # other
        properties:
          mail:
            # 是否开启SSL(QQ邮箱请开启)
            smtp:
              ssl:
                enable: true
              required: true
            # 邮件接收时间限制(毫秒)
            timeout: 10000
            # 连接时间显示
            connectiontimeout: 10000
            # 邮件发送时间的限制,单位毫秒
            writetimeout: 10000
    

    3. 编写代码

    3.1 简单的邮件

    @Resource
    private JavaMailSenderImpl javaMailSender;
    
    @Test
    void contextLoads() {
        SimpleMailMessage message = new SimpleMailMessage(); // 创建消息对象
        message.setSubject("标题"); // 标题
        message.setText("正文"); // 只支持文本, 不支持html
        message.setTo("****@qq.com"); // 收件人
        message.setFrom("****@qq.com"); // 发件人
        javaMailSender.send(message); // 发送
    }
    

    3.2 复杂的邮件

    @Test
    void testMail() throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setSubject("标题"); // 标题
        // 内容, 第二个参数为true则以html方式发送, 否则以普通文本发送
        helper.setText("<h1 style='red'>内容</h1>", true);
        //发送附件
        helper.addAttachment("1.jpg",new File("C:\Users\zpk\Desktop\loading\加载-063.gif"));
        helper.addAttachment("2.jpg",new File("C:\Users\zpk\Desktop\loading\加载-067.gif"));
        helper.setTo("****@qq.com"); // 收件人
        helper.setFrom("****@qq.com"); // 发件人
        javaMailSender.send(message); // 发送
    }
    
  • 相关阅读:
    PTA 两个有序链表序列的合并
    PTA 递增的整数序列链表的插入
    PTA 链表逆置
    PTA 带头结点的链式表操作集
    _KPCR, _NT_TIB, _KPRCB
    FSOP
    逆向PspCreateProcess
    寒假训练 [GKCTF2020]Domo(4/250) 劫持vtable
    IO_FILE利用与劫持vtables控制程序流程、FSOP
    线程结构
  • 原文地址:https://www.cnblogs.com/zpKang/p/13274055.html
Copyright © 2020-2023  润新知