写在前面: 从2018年底开始学习SpringBoot,也用SpringBoot写过一些项目。这里对学习Springboot的一些知识总结记录一下。如果你也在学习SpringBoot,可以关注我,一起学习,一起进步。
目录
开通QQ邮箱的POP3/SMPT协议
发送邮件所需要的依赖文件
相关配置
发送邮件方法
开通QQ邮箱的POP3/SMPT协议
打开qq邮箱点击设置,之后点击账户,往下翻,如图。
找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,点击开启,开启后会出现一个授权码,发送邮件时会用到。
发送邮件所需要的依赖文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
相关配置
在application.properties配置文件中配置发邮件的相关配置:
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
spring.mail.password=发送者的邮箱密码
spring.mail.port=587
spring.mail.protocol=smtp
spring.mail.username=1234567@qq.com
发送邮件方法
新建一个测试控制器,编写发送邮件方法(一个不带附件发送,一个带附件发送),代码如下:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@RestController
public class IndexController {
@Value("${spring.mail.username}")
private String mailusername;
@Autowired
JavaMailSender jms;
@RequestMapping(value = "send")
public String send(){
try {
SimpleMailMessage mainMessage = new SimpleMailMessage();
mainMessage.setFrom(mailusername);
mainMessage.setTo("123@qq.com");
mainMessage.setSubject("Springboot发送邮件");
mainMessage.setText("邮件内容");
System.out.println("123");
jms.send(mainMessage);
return "发送成功";
}catch (Exception e){
return "发送失败";
}
}
@RequestMapping(value = "sends")
public String sends() {
try {
MimeMessage mainMessage = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mainMessage, true);
helper.setFrom(mailusername);
helper.setTo("123@qq.com");
helper.setSubject("Springboot发送邮件");
helper.setText("邮件内容");
helper.addAttachment("ATM.pptx", new File("E:\\HTML\\ATM.pptx"));
jms.send(mainMessage);
return "发送成功";
}catch (Exception e){
return "发送失败";
}
}
}
测试效果
运行项目,在浏览器中输入
http://localhost:8080/send
发送邮件到对应的邮箱。可以看到标题和内容都是对应的(不带附件发送)。如下:
访问
http://localhost:8080/sends
地址,发送带附件的邮件,效果如下:
最后有什么不足之处,欢迎大家指出,期待与你的交流。如果感觉对你有帮助,点个赞在走呗 O(∩_∩)O ~