SpringBoot uses JavaMailSender to send mail, yml configuration

Foreword, using springboot's JavaMailSender interface to send mail is actually very simple, but there is a problem that you need to configure the cc sender when sending, otherwise it will report an exception org.springframework.mail.MailSendException: Failed messages: com.sun .mail.smtp.SMTPSendFailedException: 554 DT: SPM 163

1. Configure maven, which is actually a starter to add springboot mail, it is easy to remember, this is also the benefit of springboot integration

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

2.ymll

mail:
    host: smtp.163.com
    username: ****@163.com #自己的邮箱账号
    password: *******  #这个不是登录密码而是163授权登录的密码
    default-encoding: UTF-8

Obtaining the password authorized by 163 is also very simple, just go to the web page of 163 and turn on the two switches
Insert picture description here

3. Functional test

Because the mail sending function is simple, I will use the controller to test it briefly

@Autowired
    private JavaMailSender javaMailSender;
	
	//发送普通文本邮件
    @RequestMapping(value = "/sendMail")
    public String sendMail(Model model) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("654321***@163.com"); //发送者
        message.setTo("123456***@qq.com");  //接受者
        message.setCc("654321***@163.com"); //抄送,填发送者的邮箱即可
        message.setSubject("今天天气真好");	//主题
        message.setText("你好你好你好!");	//内容
        try {
            javaMailSender.send(message);
            System.out.println("简单邮件已经发送");
        } catch (Exception e) {
            System.out.println("发送简单邮件时发生异常!"+e.toString());
        }
        model.addAttribute("msg", "");
        return "login";
    }
    
 //也可以html邮件   
 @RequestMapping("/sendHtmlMail")
    public void sendHtmlMail() {
        String content="<html>\n" +
                "<body>\n" +
                "    <h3>你好你好你好!</h3>\n" +
                "</body>\n" +
                "</html>";
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom("654321***@163.com");
            messageHelper.setTo("123456***@qq.com");
            messageHelper.setSubject("今天天气真好");
            messageHelper.setText(content, true);
            javaMailSender.send(message);
            System.out.println("邮件成功发送");
        } catch (MessagingException e) {
            System.out.println("发送邮件时发生异常!"+e.toString());
        }
    }

4. Sent successfully

Insert picture description here

Published 25 original articles · praised 4 · visits 1516

Guess you like

Origin blog.csdn.net/weixin_39025362/article/details/105382088