SpringBoot发送Email邮箱--发送多人

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 {

    /**
     * 发送文本邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    void sendSimpleMail(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 sendSimpleMail(String[] to, String subject, String content) {

        SimpleMailMessage message = new SimpleMailMessage();
        //发件人
        message.setFrom(from);
        //收件人
        message.setTo(to);
        //邮件主题
        message.setSubject(subject);
        //邮件内容
        message.setText(content);
        //发送邮件
        javaMailSender.send(message);

    }

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 sendSimpleEmail(){
        String content = "我知道,你是一个野生的程序猿";
        emailService.sendSimpleMail(to,"HelloEmail",content);
    }

}
posted @ 2022-06-22 21:06  一只小狐疑  阅读(631)  评论(0)    收藏  举报