美文网首页
.使用spring task方法实现定时发送简单邮件

.使用spring task方法实现定时发送简单邮件

作者: 蜜思1013 | 来源:发表于2019-04-17 20:02 被阅读0次
    • 首先配置QQ邮箱->设置->账户->开启服务POP3/SMTP开启->获取授权码


      image.png

      要记住保存开启后的密码

    • 在pom文件中添加依赖
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    
    • 配置application.properties
    spring.mail.host=smtp.qq.com
    spring.mail.username=2413890705@qq.com  
    ##授权码
    spring.mail.password=开启服务后的密码
    spring.mail.default-encoding=UTF-8
    
    
    ##如果不加下面3句,会报530错误
    spring.mail.properties.mail.smtp.auth=true
    spring.mail.properties.mail.smtp.starttls.enable=true
    spring.mail.properties.mail.smtp.starttls.required=true
    
    • Service接口
    public interface MailService {
        /**
         * 发送简单邮件
         */
        void sendMail(String to,String subject,String content);
    
    }
    
    • 实现Service接口
    package com.soft1721.jianyue.api.service.impl;
    
    import com.soft1721.jianyue.api.service.MailService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.stereotype.Service;
    
    @Service("mailService")
    public class MailServiceImpl implements MailService {
        @Autowired
        private JavaMailSender mailSender;
        @Override
        public void sendMail(String to, String subject, String content) {
            SimpleMailMessage mailMessage=new SimpleMailMessage();
            mailMessage.setFrom("......@qq.com");//发起者
            mailMessage.setTo(".......@qq.com");//接受者
            mailMessage.setSubject(subject);
            mailMessage.setText(content);
            try {
                mailSender.send(mailMessage);
                System.out.println("发送邮件成功");
            }catch (Exception e){
                System.out.println("发送邮件失败");
            }
        }
    }
    
    • 写定时任务
    package com.soft1721.jianyue.api.service;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Service;
    
    @Service
    //@Async
    public class TaskService {
        @Autowired
        private MailService mailService;
    
        @Scheduled(cron = "0 00 08 ? * *")
        public void proces(){
            mailService.sendMail("......@qq.com","王欣雅","定时9.47发送");
            System.out.println("hello");
        }
    }
    

    icon表达式https://www.jianshu.com/p/2abe2fe4ad32

    • 运行结果


      image.png

    相关文章

      网友评论

          本文标题:.使用spring task方法实现定时发送简单邮件

          本文链接:https://www.haomeiwen.com/subject/ikjywqtx.html