spring boot mail发送邮件,群发邮件

pom.xml


    org.springframework.boot
    spring-boot-starter-mail

腾讯企业邮箱配置,
端口465,配置SSL
application.properties

spring.mail.host=smtp.exmail.qq.com   
spring.mail.port=465
[email protected] #发送者邮件
spring.mail.password=xxxx   #密码,不能是管理员添加的初始密码,不然会报501错误(需要改过密码)
[email protected];[email protected] #用;分开
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enabled=true
spring.mail.properties.mail.smtp.socketFactory.port=465
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

 增加一个发送邮件的service接口

public interface MailService {
    public void sendMail(String from, String[] to, String title,String content);
}

接口实现

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.Date;

@Service
@Transactional
public class MailServiceImpl implements MailService {
    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;
    @Value("${spring.mail.toadmin}")
    private String toTmp;

    @Override
    public void sendMailByRemind(String tel) {
        String[] to = toTmp.split(";"); //目标必须字符串或数组,多接收人时必须为数组,用字府串会报异常
        sendMail(from, to, "新用户注册提醒", new Date()+"注册手机号为:"+tel);
    }

    @Override
    public void sendMail(String from, String[] to, String title, String content) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from); //腾讯的限制,发送人必须与发送邮箱相同,不同会报异常
        message.setTo(to);
        message.setSubject(title);
        message.setText(content);

        mailSender.send(message);
        System.out.println("send mail to: "+ Arrays.toString(to) +"and content: "+ content);
    }
}

 

本地测试发送一个邮件要20秒,故而改成用异步发送邮件,

添加异步接口Service

public interface AnsyService {
    public void sendMailByRemind(String tel);
}

异步实现

@Service
@Transactional
public class AnsyServiceImpl implements AnsyService{

    @Autowired
    MailService mailService;

  

    @Async
    @Override
    public void sendMailByRemind(String tel) {
        mailService.sendMailByRemind(tel);
    }


}

你可能感兴趣的:(spring,boot2.0)