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

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

作者: Rebirth_914 | 来源:发表于2019-04-17 18:11 被阅读0次
    • 首先配置QQ邮箱->设置->账户->开启服务POP3/SMTP开启->获取授权码 1.png
    • 添加依赖
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    
    • 配置application.properties
    spring.mail.host=smtp.qq.com
    spring.mail.username=2324407028@qq.com  
    ##授权码
    spring.mail.password=dpupddbvxgjddjai
    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("2324407028@qq.com");//发起者
            mailMessage.setTo("1599592024@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 47 09 ? * *")
        public void proces(){
            mailService.sendMail("1599592024@qq.com","王欣雅","定时9.47发送");
            System.out.println("hello");
        }
    }
    
    

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

    • 运行结果 运行结果.png

    相关文章

      网友评论

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

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