springboot发送邮件

引入maven

  
            org.springframework.boot
            spring-boot-starter-mail
        

  

yml配置

spring:
  mail:
    host: smtp.163.com    #邮件服务器地址,邮箱不一样,服务器地址不一样
    username:  #邮箱用户名 
    password:  #一般使用授权码
    properties:
      'mail.smtp.ssl.enable': 'true'   #设置安全连接

  

发送邮件工具类

MailUtis.java

package cn.stylefeng.guns.utils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class MailUtil {

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    public static MailUtil mailUtil;

    @PostConstruct
    public void init(){
        mailUtil=this;
        mailUtil.javaMailSender=this.javaMailSender;
    }

       
    public static void sendMail(){
        SimpleMailMessage mailMessage=new SimpleMailMessage();
        mailMessage.setSubject("测试");   #主题
        mailMessage.setText("aaa");      #发送的内容
        mailMessage.setTo("[email protected]");   #发送给谁邮箱地址
        mailMessage.setFrom("[email protected]"); #发送人,这里与yml配置的username一样
        mailUtil.javaMailSender.send(mailMessage);
    }

    //发送附件代码 
public static void sendMailAttach() {
MimeMessage mimeMessage=mailUtil.javaMailSender.createMimeMessage();
MimeMessageHelper helper= null;
try {
helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject("测试");
helper.setText("aaa",true); //发送含有html代码的内容
helper.setTo("[email protected]");
helper.setFrom("[email protected]");

helper.addAttachment("1.jpg",new File("C:\\Users\\Pictures\\1.jpg")); 发送附件 可以多个,前面是附件名称,后面是附件绝对路径
helper.addAttachment("2.jpg",new File("C:\\Users\\Pictures\\1.jpg"));
} catch (MessagingException e) {
e.printStackTrace();
}

mailUtil.javaMailSender.send(mimeMessage);
  }
}

  

你可能感兴趣的:(springboot发送邮件)