邮件发送通知

一、 配置文件

spring:
  #邮件配置    
  mail:
    host: smtp.exmail.qq.com
    username: [email protected]
    password: aliyun
    default-encoding: UTF-8
    port: 465
    properties:
      mail: 
        smtp:  
          socketFactory.class: javax.net.ssl.SSLSocketFactory

二、 获取发件人邮箱

@Component
public class EmailConfig {
    /**
     * 邮件发送邮箱(配置文件获取)
     */  
   @Value("${spring.mail.username}")
    private String emailFrom;
    
    public String getEmailFrom() {

        return emailFrom;
    }
    public void setEmailFrom(String emailFrom) {
        this.emailFrom = emailFrom;
    }
}

三、 邮件发送工具类(引自阿里开发文档)

@Slf4j
@Service
@EnableAsync
public class AsyncFileService {
    @Autowired
    private JavaMailSender mailSender;
    
    @Autowired
    private EmailConfig emailConfig;
    
    /**
     * 简单邮件的发送
     * @param sendTo 邮件接收邮箱
     * @param title  标题
     * @param content  邮件内容
     */
    public void sendSimpleMail(String sendTo, String title, String content) {
        //简单邮件的发送
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(emailConfig.getEmailFrom());
        message.setTo(sendTo);
        message.setSubject(title);
        message.setText(content);

        mailSender.send(message);
    }

    /**
     * 发送带多附件的邮件
     * @param sendTo 邮件接收邮箱
     * @param title  标题
     * @param content 邮件内容
     * @param file1 附件一
     * @param file2 附件二
     * @param name1  附件一在邮件中名称
     * @param name2  附件二在邮件中名称
     */
    public void sendAttachmentMail(String sendTo, String title, String content, File file1, File file2 , String name1,String name2) {
        //开始时间
        long startTimeMillis = System.currentTimeMillis();
        //发送邮件
        log.info("准备发送邮件至"+sendTo);
        MimeMessage msg = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(msg, true);
            helper.setFrom(emailConfig.getEmailFrom());
            helper.setTo(sendTo);
            helper.setSubject(title);
            helper.setText(content);

            FileSystemResource r1 = new FileSystemResource(file1);
            helper.addAttachment(name1, r1);
            FileSystemResource r2 = new FileSystemResource(file2);
            helper.addAttachment(name2, r2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mailSender.send(msg);
        //执行时间
        long execTimeMillis = System.currentTimeMillis() - startTimeMillis;
        log.info("已发送至"+sendTo+"邮箱"+",执行时间:"+execTimeMillis);
    }
}

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