Java教程

SpringBoot发送Email邮件-发送多人HTML邮件

本文主要是介绍SpringBoot发送Email邮件-发送多人HTML邮件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.创建项目

  • 当然也可以直接在pom文件加入依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2.在yml文件中配置Email

spring:
  mail:
    host: smtp.qq.com #邮件服务器
    username: @qq.com #发送邮件邮箱地址
    password: wzvqfidbecaj #QQ客户端授权码
    port: 587 #端口号465-smtps或587-smtp
    from: @qq.com # 发送邮件的地址,和上面username一致
    default-encoding: UTF-8
    protocol: smtp

3.创建EmailService、EmailServiceImpl

package com.cn.config.utils.email;

public interface EmailService {
    /**
     * 发送HTML邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    void sendHtmlMail(String[] to, String subject, String content);

}

/**
 * 发送邮件服务
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private JavaMailSender javaMailSender;

    //注入配置文件中配置的信息——>from
    @Value("${spring.mail.from}")
    private  String from;

    @Override
    public void sendHtmlMail(String[] to, String subject, String content) {

        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message,true);
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            message.setSubject(subject);
            messageHelper.setText(content,true);
            javaMailSender.send(message);
            System.err.println("邮件已经发送!");
        } catch (MessagingException e) {
            System.err.println("发送邮件时发生异常:"+e);
        }
    }
}


4.测试

package com.cn.test;

import com.cn.config.utils.email.EmailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
public class EmailTest {
     //这里放收信人的QQ邮箱
    private String[] to =new String[]{"@qq.com","@qq.com"};

    @Autowired
    private EmailService emailService;

    @Test
    public void sendMimeEmail(){
        String content = "<a href='https://www.cnblogs.com/Huyi-1208/'>你好,欢迎来到一只小狐疑的博客,请点击链接激活</a>";
        emailService.sendHtmlMail(to,"一只小狐疑的博客",content);
    }



}
这篇关于SpringBoot发送Email邮件-发送多人HTML邮件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!