SpringBoot (ten) send email

send email

 

1. Open the mail service

Here we take QQ mailbox as an example. other email

First log in to the QQ mailbox >>> after successful login, find the setting >>> then find the mailbox setting >>> click the account >>> find the POP3|SMTP service >>> click to open (opening requires verification, after successful verification, there will be a string of authorization codes For sending emails)>>>Verification is successful and write down the authorization code prompted by the QQ mailbox . This authorization code is the password required when sending emails.

2. Introduce dependencies

<!--发送邮件依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

3. application.yml configuration

Write the configuration information for sending emails in the configuration file application.yml

spring:
  #邮箱基本配置
  mail:
    #配置smtp服务主机地址
    # qq邮箱为smtp.qq.com          端口号465或587
    # sina    smtp.sina.cn
    # aliyun  smtp.aliyun.com
    # 163     smtp.163.com       端口号465或994
    host: smtp.qq.com
    #发送者邮箱
    username: [email protected]
    #配置密码,注意不是真正的密码,而是刚刚申请到的授权码
    password: dniigyabntufcaef
    #端口号465或587
    port: 587
    #默认的邮件编码为UTF-8
    default-encoding: UTF-8
    #其他参数
    properties:
     mail:
        #配置SSL 加密工厂
      smtp:
        ssl:
          #本地测试,先放开ssl
          enable: false
          required: false
        #开启debug模式,这样邮件发送过程的日志会在控制台打印出来,方便排查错误
      debug: true

4. Write the method of sending mail

@Controller
public class MailController {
    /**
     * 注入邮件工具类,这是是引入jar包的那个类
     */
    @Autowired
    private JavaMailSenderImpl javaMailSender;
    /**
     * 发送纯文本邮件 /sendMail
     * @param to 邮件收信人
     * @param title 邮件标题
     * @param text 邮件内容
     */
    @PostMapping("/sendMail")
    public void sendTextMailMessage(String to,String title,String text){
        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(),true);
            //邮件发信人
            mimeMessageHelper.setFrom("[email protected]");
            //邮件收信人  1或多个    [email protected],[email protected]
            mimeMessageHelper.setTo(to.split(","));
            //邮件标题
            mimeMessageHelper.setSubject(title);
            //邮件内容
            mimeMessageHelper.setText(text);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());
            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            System.out.println("发送邮件成功:");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送邮件失败:"+e.getMessage());
        }
    }
}

Guess you like

Origin blog.csdn.net/m0_65992672/article/details/130421746