JavaMail定时发送邮件

    package com.cn.controller;    
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Properties;
    import java.util.Timer;
    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.NoSuchProviderException;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;

    //定时器(定时循环发送)
        public class MyTimerTask implements ServletContextListener{
            private Timer timer = null;
            public void contextDestroyed(ServletContextEvent event) {
                 timer.cancel();
                 event.getServletContext().log("定时器销毁");
            }  
            public void contextInitialized(ServletContextEvent event) {
                 //在这里初始化监听器,在tomcat启动的时候监听器启动,可以在这里实现定时器功能
                 timer = new Timer(true);
                 event.getServletContext().log("定时器已启动");//添加日志,可在tomcat日志中查看到
                 //调用exportHistoryBean,0表示任务无延迟,60*1000表示每隔1分钟执行一次
                 timer.schedule(new SendMail(event.getServletContext()),0,60*1000);
            }
        }


    class SendMail extends java.util.TimerTask  {
            
            private ServletContext context = null;
            public SendMail(ServletContext context)
            {
             this.context = context;
            }

            public void run() {
            Properties prop = new Properties();  
            prop.put("mail.host","smtp.163.com");//发件人使用发邮件的电子信箱服务器我使用的是163的服务器
            prop.put("mail.transport.protocol", "smtp");//发送邮件协议名称
                prop.put("mail.smtp.auth","true"); //这样才能通过验证
              
            try {
                //使用JavaMail发送邮件的5个步骤  
                //1、创建session  
                Session session = Session.getInstance(prop);  
                //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态  
                session.setDebug(true);  
                //2、通过session得到transport对象  
                Transport ts = session.getTransport();  
                //3、使用邮箱的用户名和密码(开启step服务后的授权码)连上邮件服务器,  
                ts.connect("smtp.163.com", "邮箱账号", "授权码");
                /*  
                4、创建邮件(只包含文本)  
                Message message = createSimpleMail(session);
                 */
                //4、创建邮件(带附件)  
                Message message = createAttachMail(session);  
                //5、发送邮件  
                ts.sendMessage(message, message.getAllRecipients());  
                ts.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
            
            
            }    
          
        
        //创建一封只包含文本的邮件  
        public static   MimeMessage createSimpleMail(Session session) throws Exception {  
            
            //创建邮件对象  
            MimeMessage message = new MimeMessage(session);  
            //指明邮件的发件人  
            message.setFrom(new InternetAddress("发件人邮箱地址@163.com"));  
            //指明邮件的收件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress("xxxxxxx@qq.com"));  
            //邮件的标题  
            message.setSubject("测试邮件");  
              
            //邮件的文本内容,为了避免邮件正文中文乱码问题,需要使用charset=UTF-8指明字符编码  
            //需要注意的是如果收件人是qq邮箱极有可能被当作垃圾邮件而不会提醒有新邮件
            message.setContent("都说了这不是垃圾邮件!", "text/html;charset=UTF-8");  
              
            //返回创建好的邮件对象  
            System.out.println(message);  
            return message;  
        }  
        
        //创建一封包含附件的邮件  
        public static MimeMessage createAttachMail(Session session) throws Exception {  
            //创建邮件对象  
            MimeMessage message = new MimeMessage(session);  
            //指明邮件的发件人  
            message.setFrom(new InternetAddress("发件人邮箱地址@163.com"));
            //指明邮件的收件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress("xxxxxxx@qq.com"));  
            //邮件的标题  
            message.setSubject("日志文件");  
              
            //创建邮件正文,为了避免邮件正文中文乱码问题,需要使用charset=UTF-8指明字符编码  
            MimeBodyPart text = new MimeBodyPart();  
            String mailText = "请尽快回复!";  
            text.setContent(mailText, "text/html;charset=UTF-8");  
            //创建邮件附件  
            MimeBodyPart attach = new MimeBodyPart();  
            DataHandler dh = new DataHandler(new FileDataSource("C:\\Users\\john\\Desktop\\rz.txt"));  
            attach.setDataHandler(dh);  
            attach.setFileName(dh.getName());  
              
              
            //创建容器描述数据关系
            MimeMultipart mp = new MimeMultipart();  
            mp.addBodyPart(text);  
            mp.addBodyPart(attach);  
            mp.setSubType("mixed");
            message.setContent(mp);
            message.saveChanges();  
              
            //返回创建好的邮件对象  
            System.out.println(message);  
            return message;  
       
        }  
    }


    还有最后一步就是在web.xml中配置监听器,在服务启动时运行该类
     <listener>
 	  <listener-class>com.cn.controller.MyTimerTask</listener-class>
     </listener>
    
   
        

 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Spring Boot提供了一个简单而强大的方式来定时发送邮件。下面是使用Spring Boot定时发送邮件的步骤: 1. 添加依赖:在`pom.xml`文件中添加Spring Boot的邮件依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 2. 配置邮件信息:在`application.properties`或`application.yml`文件中配置邮件服务器的相关信息,例如: ```properties spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=your-email@example.com spring.mail.password=your-email-password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` 3. 创建邮件服务类:创建一个邮件服务类,用于发送邮件。可以使用Spring Boot提供的`JavaMailSender`接口来发送邮件。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service public class EmailService { @Autowired private JavaMailSender mailSender; public void sendEmail(String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); mailSender.send(message); } } ``` 4. 创建定时任务类:创建一个定时任务类,用于定时发送邮件。可以使用Spring Boot提供的`@Scheduled`注解来定义定时任务的执行时间。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class EmailScheduler { @Autowired private EmailService emailService; @Scheduled(cron = "0 0 8 * * ?") // 每天早上8点执行 public void sendDailyEmail() { String to = "recipient@example.com"; String subject = "Daily Report"; String text = "This is the daily report email."; emailService.sendEmail(to, subject, text); } } ``` 5. 启动应用程序:运行Spring Boot应用程序,定时任务将在指定的时间自动执行,并发送邮件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值