SpringBoot实现QQ邮箱邮件发送
程序员文章站
2022-07-08 11:58:17
...
一、邮件发送前的准备
使用QQ邮箱发送邮件,首先要申请开通POP3/SMTP服务或者IMAP/SMTP。
1、登录QQ邮箱,依次单击顶部的设置按钮和账号按钮
2、在账户选择卡下方找到POP3/SMTP服务,单击后方的“开启”按钮
单击“开启”按钮后,依照引导步骤发送短信,操作成功后,会获取一个授权码,将授权码保存下来过后使用。
二、项目搭建
1、pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
2、application.properties
server.port=8082
spring.mail.host=smtp.qq.com
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
spring.mail.password=授权码
aaa@qq.com
spring.mail.port=587
spring.mail.properties.mail.stmp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
3、发送简单邮件
@Component
public class MailService {
@Autowired
JavaMailSender javaMailSender;
//发送简单邮件
public void sandSimpleMail(String from,String to,String cc,String subject,String content)
{
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(from);
mailMessage.setTo(to);
mailMessage.setCc(cc);
mailMessage.setSubject(subject);
mailMessage.setText(content);
javaMailSender.send(mailMessage);
}
}
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
class MailApplicationTests {
@Autowired
MailService mailService;
@Test
void contextLoads() {
}
@Test
public void sendSimpleMail()
{
mailService.sandSimpleMail("aaa@qq.com","aaa@qq.com",
"aaa@qq.com","测试邮件主题","测试邮件内容");
}
}
运行结果:
4、发送带附件的邮件
@Component
public class MailService {
@Autowired
JavaMailSender javaMailSender;
//带附件的邮件
public void sandAttachMail(String from, String to, String subject, String content, File file)
{
try {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content);
helper.addAttachment(file.getName(),file);
javaMailSender.send(message);
}catch (MessagingException e)
{
e.printStackTrace();
}
}
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
class MailApplicationTests {
@Autowired
MailService mailService;
@Test
public void sendAttachMail()
{
mailService.sandAttachMail("aaa@qq.com",
"aaa@qq.com","测试邮件主题",
"测试邮件内容",new File("D:\\Java_All_\\redis启动命令.txt"));
}
}
运行结果: