SpringBoot发送QQ邮件

xiaoxiao2021-02-28  27

说明

使用SpringBoot来发送QQ邮件十分简单,省去了很多的配置文件和接口的使用,使用原生java来实现QQ邮件的方式可以查看我的另一篇博客:http://blog.csdn.net/weixin_38187317/article/details/79327246原生实现的方式有点复杂,需要很多的类,但在SpringBoot里,只需要简单配置application.properties和pom.xml引入依赖即可使用。

步骤

1 PO3/SMTP服务必须开启
开启方式可以查看上面我所说的博客
2 更新pom.xml

添加依赖:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
3 更新application.properties文件
#配置上下文,根据自己项目设置 server.contextPath=/MavenSpringBoot #配置邮件消息 spring.mail.host=smtp.qq.com #发送邮件者信箱 spring.mail.username=xxxxxxxxx@qq.com #这里不是邮箱的登录密码,而是开启PO3/SMTP服务时邮箱的授权码 spring.mail.password=xxxxxxxxxxxxxxxx spring.mail.default-encoding=UTF-8 spring.mail.port=587 spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory spring.mail.properties.mail.debug=true
3 编写controller
package test.controller; import org.springframework.web.bind.annotation.RestController; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @RestController public class HelloController { private static String content = "<!DOCTYPE html>" + "<html>" + "<head>" + "<title>测试邮件2</title>" + "<meta name=\"content-type\" content=\"text/html; charset=UTF-8\">" + "</head>" + "<body>" + "<p style=\"color:#0FF\">这是一封测试邮件~</p>" + "</body>" + "</html>"; // 可以用HTMl语言写 @Autowired JavaMailSender mailSender;//自动注入 @RequestMapping(value = "/sendEmail/{name}", method = RequestMethod.GET) public Object sendEmail(@PathVariable("name") String name) { try { MimeMessage mimeMessage = this.mailSender.createMimeMessage(); MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setFrom("xxxxxxxx@qq.com");//设置发信人,发信人需要和spring.mail.username配置的一样否则报错 name+="@qq.com"; //补全地址 message.setTo(name); //设置收信人 message.setSubject("测试邮件主题"); //设置主题 message.setText(content,true); //第二个参数true表示使用HTML语言来编写邮件 //            FileSystemResource file = new FileSystemResource(   //            new File("src/main/resources/static/image/picture.jpg"));   //            helper.addAttachment("图片.jpg", file);//添加带附件的邮件   //            helper.addInline("picture",file);//添加带静态资源的邮件 this.mailSender.send(mimeMessage); return "sucesss"; } catch (Exception ex) { ex.printStackTrace(); return "error"; } } }
4 运行
运行启动类,打开浏览器输入:http://127.0.0.1:8080/MavenSpringBoot/sendEmail/xxxxxx,后面的xxx为收件者的邮箱(不带后缀@qq.com),结果:

转载请注明原文地址: https://www.6miu.com/read-2630579.html

最新回复(0)