1.引入依赖
<!--发送邮件的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置yml文件
spring:
mail:
host: smtp.163.com
port: 465 #邮箱服务器端口
username: ******@163.com #登录邮箱的账号
password: ****** #这里是客户端授权码,不是登录密码
default-encoding: UTF-8
properties.mail.debug: true
properties.mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
3.编写service
package com.example.mail.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
/**
* 发送邮件
*/
@Component
public class MailService {
@Autowired
JavaMailSender javaMailSender;
/**
*
* @param from 邮件发送者
* @param to 收件人
* @param cc 抄送人
* @param subject 邮件主题
* @param content 邮件内容
*/
public void sendSimpleMail(String from,String to,String cc,String subject,String content){
//创建邮件信息对象
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//邮件发送者
simpleMailMessage.setFrom(from);
//收件人
simpleMailMessage.setTo(to);
//抄送人
simpleMailMessage.setCc(cc);
//邮件主题
simpleMailMessage.setSubject(subject);
//邮件内容
simpleMailMessage.setText(content);
//开始发送邮件
javaMailSender.send(simpleMailMessage);
}
}
测试类
@Test
public void sendSimpleMail(){
mailService.sendSimpleMail("******@163.com","****@163.com","******@163.com","测试主题","测试内容");
}