目录
一 协议简介
SMTP:simple mail transfer protocol 简单邮件传输协议 → 用于发送电子邮件的传输协议
POP3:post office protocol-version3 用于接收电子邮件的标准协议 (不能做邮件状态的双向同步)
IMAP:internet mail access protocol 互联网消息协议,是pop3的替代协议 (可以做邮件状态的双向同步 → 已读未读)
二 代码
准备工作
QQ邮箱--设置--账户--开启(协议)服务--发短信--给一个密码
备注:该授权码会用在配置文件中
1 导坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2 配置文件
username就是发送邮件的邮箱地址
password就是邮箱开启服务发完短信给的码
3 操作
sevice
package com.qing.service;
public interface SendMailService {
void sendMail();
}
seviceImpl
package com.qing.service.impl;
import com.qing.service.SendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class SendMailServiceImpl implements SendMailService {
@Autowired
private JavaMailSender javaMailSender;
private String from = "[email protected]";
private String to = "[email protected]";
private String subject = "测试邮件";
private String content = "测试邮件,无需回复";
@Override
public void sendMail() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
javaMailSender.send(message);
}
}
备注:配置文件的username 和 from的邮箱地址要一致
4 测试
package com.qing;
import com.qing.service.SendMailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootMailApplicationTests {
@Autowired
private SendMailService sendMailService;
@Test
void contextLoads() {
sendMailService.sendMail();
}
}
结果