SpringBoot实现发送邮件功能(带附件)

  • 依赖
<!--springboot mail-->
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
 </dependency>
</dependencies>
  • yml配置
spring:
  mail:
    host: smtp.qq.com
    port: 465
    username: *********@qq.com
    #邮箱授权码
    password: qhwsedmzmiebbjfh
    protocol: smtps
    properties:
      mail:
        smtp:
          ssl:
            enable: true
  • 发送邮件client
@Component
@Data
public class MailClient {
    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);
    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username} ")
    private String from;
    public void sendMail(String toUser, String ccUser, String bccUser, String subject, String content, List<File> files) throws MessagingException, UnsupportedEncodingException {
        MimeMessage message = mailSender.createMimeMessage();
        //发件人
        message.setFrom(new InternetAddress(from));
        // 设置多个收件人地址  用逗号隔开
        if (null != toUser && !toUser.isEmpty()) {
            @SuppressWarnings("static-access")
            InternetAddress[] internetAddressTo = new InternetAddress().parse(toUser);
            message.setRecipients(Message.RecipientType.TO, internetAddressTo);
        }
        // 设置多个抄送地址  用逗号隔开
        if (null != ccUser && !ccUser.isEmpty()) {
            @SuppressWarnings("static-access")
            InternetAddress[] internetAddressCC = new InternetAddress().parse(ccUser);
            message.setRecipients(Message.RecipientType.CC, internetAddressCC);
        }
        // 设置多个密送地址  用逗号隔开
        if (null != bccUser && !bccUser.isEmpty()) {
            @SuppressWarnings("static-access")
            InternetAddress[] internetAddressBCC = new InternetAddress().parse(bccUser);
            message.setRecipients(Message.RecipientType.BCC, internetAddressBCC);
        }
        //主题
        message.setSubject(subject);
        Multipart multipart = new MimeMultipart();
        //邮件正文
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(content, "text/html;charset=utf-8");
        multipart.addBodyPart(contentPart);
        //邮件附件
        if (files != null) {
            for (File attachment : files) {
                BodyPart attachmentPart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachment);
                attachmentPart.setDataHandler(new DataHandler(source));
                //避免中文乱码的处理
                attachmentPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
                multipart.addBodyPart(attachmentPart);
            }
        }
        message.setContent(multipart);
        //保存邮件
        message.saveChanges();
        mailSender.send(message);
    }
}
  • 测试发送
@Test
    public void testMail() throws MessagingException, UnsupportedEncodingException {
        Vector files = new Vector(); //用于保存发送附件的文件名的集合
        File f1=new File("C:\\Users\\Lenovo\\Desktop\\testimg\\图片1.jpg");
        files.add(f1);
        File f2=new File("C:\\Users\\Lenovo\\Desktop\\testimg\\test.jpg");
        files.add(f2);
        //拼接正文
        String content = "";
        //判断环境
        StringBuffer sb = new StringBuffer("<p font-size:14px;line-height:24px;font-family:'微软雅黑',Helvetica,Arial,sans-serif;margin-bottom: 20px>");
        sb.append("<strong>Environment: </strong>");
        sb.append("TEST");
        sb.append("<br/>");
        sb.append("<strong>Name: </strong>");
        sb.append("张三");
        sb.append("<br/>");
        sb.append("<strong>Phone: </strong>");
        sb.append("13911111111");
        sb.append("<br/>");
        sb.append("<strong>Date: </strong>");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String strDate = sdf.format(date);
        sb.append(strDate);
        sb.append("<br/>");
        sb.append("<strong>Type: </strong>");
        sb.append("advice");
        sb.append("<br/>");
        sb.append("<strong>Priority: </strong>");
        String importance="low";
        if ("High".equals(importance)) {
            sb.append("<span style='color:red'>" + importance + "</span>");
        } else {
            sb.append(importance);
        }
        String description="java mail test";
        sb.append("<br/>");
        sb.append("<strong>Description: </strong>").append(description);
        sb.append("<br/>");
        sb.append("</p>");
        content=new String(sb);     
        mailClient.sendMail("wb****@163.com,wc****@163.com","wd****@163.com,we****@163.com","wf****@163.com,wg****@163.com", "java mail test", content,files);
    }

注意:授权码非密码 需要去邮箱客户端获取对应的授权码

  • 效果展示
    在这里插入图片描述
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值