-
pom添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
-
properties配置
#mail
spring.mail.host=smtp.163.com
spring.mail.username=xxxx@163.com
#163的授权码
spring.mail.password=xxxx
spring.mail.default-encoding=UTF-8
-
发送邮件工具类:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
public class MailServiceUtils{
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender mailSender;
/**
* @param from 发送人
* @param to 接收人
* @param subject 主题
* @param content 内容
*/
public void sendMail(String from,String to, String subject, String content){
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
try {
mailSender.send(message); logger.info("邮件成功发送!");
} catch (MailException e) {
logger.error("发送邮件错误:",e);
}
}
}
-
启动类添加注解定时任务注解@EnableScheduling
-
测试使用
public class Test {
int i = 0;
@Resource
private MailServiceUtils mailServiceUtils;
@Scheduled(fixedRate = 4000)//定时任务4秒执行一次
//@Scheduled(cron="0/4 * * * * ? "),cron表达式,同样表示每4秒执行一次
public void test(){
mailServiceUtils.sendMail("from_user@163.com","to_user@qq.com","主题"+i,"你好鸭!");
i++;
}
}