Springboot整合JAVAMail实现发邮件功能

一、导入依赖


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

二、在邮箱设置-账户中开启相应协议服务,获取授权码Springboot整合JAVAMail实现发邮件功能_第1张图片

三、在Springboot配置文件配置邮件信息

  mail:
    host: smtp.qq.com      //协议和邮件供应商
    username: *****@qq.com  //邮箱地址
    password: ******     //上一步获取的授权码

四、设置发送信息

package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class SendMailService {
    @Autowired
    private JavaMailSenderImpl javaMailSender;
    //发送邮件人的邮箱地址
    String from="******@163.com";
    //接收人的邮箱地址
    String to="****@qq.com";
    //标题
    String subject="小甜甜";
    //文本
    String context="点开有惊喜哦";
    String text="";
    public void sendMail(){
        SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
        simpleMailMessage.setFrom(from+"(小懒猪)");
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(context);
        javaMailSender.send(simpleMailMessage);
    }
    public void sendMailWithOther() throws MessagingException {
        MimeMessage mimeMessage= javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
        mimeMessageHelper.setFrom(from+"(小可爱)");
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(context+text,true);
        javaMailSender.send(mimeMessage);
    }
}

你可能感兴趣的:(spring,boot,java)