2404
浏览量
5
粉丝
7
关注

使用springboot+javamail发送邮件


2020-07-31 20:41:07 96 0

本文以springboot的组件mail组件为例 1.首先引入stater配置

    <!--邮件组件-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

1.yml配置如下,注意代码网使用的是qq邮箱,因此这里使用456端口

mail:
    host: smtp.exmail.qq.com
    username: admin@daima.net
    password: ENC(UGHBTyNKUejoYVk823N8KPDI7kONkZam)
    default-encoding: UTF-8
    port: 465
    properties:
      mail:
        smtp:
          ssl:
            enable: true

3.java代码,代码玩使用的是实现类,注意helper.setText(content, true),的参数,可以设置html或者text类型

    public String sendHtmlMail(String to, String subject, String content) {
        log.info("发送HTML邮件开始:{},{},{}", to, subject, content);
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper;
        String result = "";
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(new InternetAddress(from, "代码网", "UTF-8"));
            helper.setTo(to);
            helper.setSubject(subject);
            //true代表支持html
            helper.setText(content, true);
            mailSender.send(message);
            result = "发送HTML邮件成功";
        } catch (MessagingException | UnsupportedEncodingException e) {
            result = "发送HTML邮件失败";
        }
        return result;
    }
精彩评论
暂无评论