• SpringBoot | 实现邮件发送


    运行环境:

    • IntelliJ IDEA 2022.2.5 (Ultimate Edition) (注意:idea必须在2021版本以上)
    • JDK17

    项目目录:

    该项目分为pojo,service,controller,utils四个部分,

    在pojo层里面写实体内容(发邮件需要的发件人邮箱,授权码,服务器域名,身份验证开关),

    service层里面写send方法,

    utils里面写发送邮件实现的工具类,

    controller层里面调用service里面的方法测试send方法。

    在resource里面的application.yml写相关的发邮件参数(user,code,host,auth)

    前提:

    该项目涉及到了邮件的发送,所以需要邮箱的授权码

    怎么获取授权码?

    在 账号与安全 --安全设置--SMTP/IMAP服务 中开启服务并获取授权码

    代码:

    pojo层:

    1. package com.xu.springbootconfigfile.pojo;
    2. import org.springframework.beans.factory.annotation.Value;
    3. import org.springframework.boot.context.properties.ConfigurationProperties;
    4. import org.springframework.stereotype.Component;
    5. @Component
    6. @ConfigurationProperties(prefix = "email")
    7. public class EmailProperties {
    8. //@Value("${email.user}")
    9. //发件人邮箱
    10. public String user ;
    11. //@Value("${email.code}")
    12. //发件人邮箱授权码
    13. public String code ;
    14. //@Value("${email.host}")
    15. //发件人邮箱对应的服务器域名,如果是163邮箱:smtp.163.com qq邮箱: smtp.qq.com
    16. public String host ;
    17. //@Value("${email.auth}")
    18. //身份验证开关
    19. private boolean auth ;
    20. public String getHost() {
    21. return host;
    22. }
    23. public void setHost(String host) {
    24. this.host = host;
    25. }
    26. public boolean isAuth() {
    27. return auth;
    28. }
    29. public void setAuth(boolean auth) {
    30. this.auth = auth;
    31. }
    32. public String getUser() {
    33. return user;
    34. }
    35. public void setUser(String user) {
    36. this.user = user;
    37. }
    38. public String getCode() {
    39. return code;
    40. }
    41. public void setCode(String code) {
    42. this.code = code;
    43. }
    44. @Override
    45. public String toString() {
    46. return "EmailProperties{" +
    47. "host='" + host + '\'' +
    48. ", auth=" + auth +
    49. ", user='" + user + '\'' +
    50. ", code='" + code + '\'' +
    51. '}';
    52. }
    53. }

    service层:

    1. package com.xu.springbootconfigfile.service;
    2. public interface EmailService {
    3. boolean send(String to,String title,String content);
    4. }
    1. package com.xu.springbootconfigfile.service.impl;
    2. import com.xu.springbootconfigfile.pojo.EmailProperties;
    3. import com.xu.springbootconfigfile.service.EmailService;
    4. import com.xu.springbootconfigfile.utils.MailUtil;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. @Service
    8. public class EmailServiceImpl implements EmailService {
    9. //注入email配置信息实体类
    10. @Autowired
    11. private EmailProperties emailProperties;
    12. /**
    13. * @param to 收件人邮箱
    14. * @param title 邮件标题
    15. * @param content 邮件正文
    16. * @return
    17. */
    18. @Override
    19. public boolean send(String to, String title, String content) {
    20. //打印email配置信息
    21. System.out.println(emailProperties);
    22. //发送邮件
    23. boolean flag = MailUtil.sendMail(emailProperties,to, title, content);
    24. return flag;
    25. }
    26. }

    controller层:

    1. package com.xu.springbootconfigfile.controller;
    2. import com.xu.springbootconfigfile.service.EmailService;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import org.springframework.web.bind.annotation.RestController;
    6. @RestController
    7. public class EmailController {
    8. //注入email配置信息实体类
    9. @Autowired
    10. private EmailService emailService;
    11. //测试方法
    12. @RequestMapping("/send")
    13. public Boolean send(){
    14. //收件人信箱
    15. String to = "邮箱号";
    16. //邮件标题
    17. String title = "test";
    18. //邮件正文
    19. String content = "哈哈哈哈哈哈哈";
    20. //发送邮件
    21. boolean flag = emailService.send(to,title,content);
    22. return flag;
    23. }
    24. }

    utils层:

    1. package com.xu.springbootconfigfile.utils;
    2. import com.xu.springbootconfigfile.pojo.EmailProperties;
    3. import jakarta.mail.*;
    4. import jakarta.mail.internet.InternetAddress;
    5. import jakarta.mail.internet.MimeMessage;
    6. import java.util.Properties;
    7. public class MailUtil {
    8. /**
    9. * 发送邮件
    10. * @param emailProperties 发件人信息(发件人邮箱,发件人授权码)及邮件服务器信息(邮件服务器域名,身份验证开关)
    11. * @param to 收件人邮箱
    12. * @param title 邮件标题
    13. * @param content 邮件正文
    14. * @return
    15. */
    16. public static boolean sendMail(EmailProperties emailProperties, String to, String title, String content){
    17. MimeMessage message = null;
    18. try {
    19. Properties properties = new Properties();
    20. properties.put("mail.smtp.host", emailProperties.getHost());
    21. properties.put("mail.smtp.auth",emailProperties.isAuth());
    22. properties.put("mail.user", emailProperties.getUser());
    23. properties.put("mail.password", emailProperties.getCode());
    24. // 构建授权信息,用于进行SMTP进行身份验证
    25. Authenticator authenticator = new Authenticator() {
    26. @Override
    27. protected PasswordAuthentication getPasswordAuthentication() {
    28. return new PasswordAuthentication(emailProperties.getUser(), emailProperties.getCode());
    29. }
    30. };
    31. // 使用环境属性和授权信息,创建邮件会话
    32. Session mailSession = Session.getInstance(properties, authenticator);
    33. // 创建邮件消息
    34. message = new MimeMessage(mailSession);
    35. }catch (Exception e){
    36. e.printStackTrace();
    37. }
    38. //如果邮件创建失败,直接返回
    39. if (message==null){
    40. return false;
    41. }
    42. try {
    43. // 设置发件人
    44. InternetAddress form = new InternetAddress(emailProperties.getUser());
    45. message.setFrom(form);
    46. // 设置收件人
    47. InternetAddress toAddress = new InternetAddress(to);
    48. message.setRecipient(Message.RecipientType.TO, toAddress);
    49. // 设置邮件标题
    50. message.setSubject(title);
    51. // 设置邮件的内容体
    52. message.setContent(content, "text/html;charset=UTF-8");
    53. // 发送邮件
    54. Transport.send(message);
    55. }catch (Exception e){
    56. e.printStackTrace();
    57. }
    58. return true;
    59. }
    60. }

    application.yml

    pom.xml文件:

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <parent>
    6. <groupId>org.springframework.bootgroupId>
    7. <artifactId>spring-boot-starter-parentartifactId>
    8. <version>3.1.2version>
    9. <relativePath/>
    10. parent>
    11. <groupId>com.xugroupId>
    12. <artifactId>springboot-config-fileartifactId>
    13. <version>0.0.1-SNAPSHOTversion>
    14. <name>springboot-config-filename>
    15. <description>springboot-config-filedescription>
    16. <properties>
    17. <java.version>17java.version>
    18. properties>
    19. <dependencies>
    20. <dependency>
    21. <groupId>org.springframework.bootgroupId>
    22. <artifactId>spring-boot-starter-webartifactId>
    23. dependency>
    24. <dependency>
    25. <groupId>org.eclipse.angusgroupId>
    26. <artifactId>jakarta.mailartifactId>
    27. dependency>
    28. dependencies>
    29. <build>
    30. <plugins>
    31. <plugin>
    32. <groupId>org.springframework.bootgroupId>
    33. <artifactId>spring-boot-maven-pluginartifactId>
    34. plugin>
    35. plugins>
    36. build>
    37. project>

    运行结果:

    显示true后,检查一下邮箱,就可以收到对应的测试邮件

  • 相关阅读:
    PLSQL调整SQL字体大小
    C++实现轻量级RPC分布式网络通信框架
    学数学,要“直觉”还是要“严谨”?
    【转】传统敏感数据防护方法
    #机器学习--补充数学基础--信息论
    见缝插针游戏针不会更着上面旋转的小球运动
    2022年Java秋招面试必看的 | RabbitMQ 面试题
    318. 最大单词长度乘积
    CleanMyMac X2022软件包最新mac电脑系统清洁器
    嵌入式实操----基于RT1170 使能展频功能(二十七)
  • 原文地址:https://blog.csdn.net/jingling555/article/details/139842900