springboot定时发邮件

1、发邮件,得先将邮件开启smtp,才可以发邮件
思路:先将数据库的数据下载保存到excel中,然后将附件的形式发送,其中利用到数据流

package com.example;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.mail.internet.MimeMessage;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.jboss.logging.Logger;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.example.entity.SelectPhoneAndTid;
import com.example.service.SelectPhoneAndTidService;
@SpringBootApplication
//开启事务
@EnableTransactionManagement
//扫包
@MapperScan("com.example.dao.SelectPhoneAndTidDao")

@EnableScheduling 
public class PoiExcellApplication {
	@Autowired
    private JavaMailSender mailSender; //自动注入的Bean
	@Autowired
	private SelectPhoneAndTidService stService;
    @Value("${spring.mail.username}")
    private String Sender; //读取配置文件中的参数
     
	@Scheduled(cron = "00 00 09 * * ?") 
	public void contextLoads() throws IOException {
        String[] headers = { "手机号码", "订单编号"};//导出的Excel头部
        List<SelectPhoneAndTid> dataset = stService.findAll();//查询出来的数据
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet();
        // 设置表格默认列宽度为20个字节
        sheet.setDefaultColumnWidth((short) 20);
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        //遍历集合数据,产生数据行
        Iterator<SelectPhoneAndTid> it = dataset.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            SelectPhoneAndTid t = (SelectPhoneAndTid) it.next();
            //利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
            Field[] fields = t.getClass().getDeclaredFields();
            for (short i = 0; i < fields.length; i++) {
                HSSFCell cell = row.createCell(i);
                Field field = fields[i];
                String fieldName = field.getName();
                String getMethodName = "get"
                        + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                try {
                    Class tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName,new Class[]{});
                    Object value = getMethod.invoke(t, new Object[]{});
                    String textValue = null;
                    if (value instanceof Date)
                    {
                        Date date = (Date) value;
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        textValue = sdf.format(date);
                    }else{
                        //其它数据类型都当作字符串简单处理
                        textValue = value.toString();
                    }       
	                    HSSFRichTextString richString = new HSSFRichTextString(textValue);
	                    HSSFFont font3 = workbook.createFont();
	                    font3.setColor(HSSFColor.BLACK.index);//定义Excel数据颜色
	                    richString.applyFont(font3);
	                    cell.setCellValue(richString);
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        
      Date d=new Date();
      SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd");
      String fn= f.format(d);
      //文件名称防止文件名含有中文乱码
      String filedisplay =fn+".xls";
      filedisplay = new String( filedisplay.getBytes("gb2312"), "ISO8859-1" );
      //文件导入的地方
       FileOutputStream fileOut = null;    
        try{                
            fileOut = new FileOutputStream("D:\\每天传送的表格数据\\"+filedisplay);    
            workbook.write(fileOut);     
        }catch(Exception e){    
            e.printStackTrace();    
        }finally{    
            if(fileOut != null){    
                try {    
                    fileOut.close();    
                } catch (IOException e) {       
                    e.printStackTrace();    
                }    
            } 
            
        //发邮件
   		 MimeMessage message = null;
   	        try {
   	            message = mailSender.createMimeMessage();
   	            MimeMessageHelper helper = new MimeMessageHelper(message, true);
   	         
	   	       helper.setTo("发送的地址");
	   	       
   	            helper.addTo("增加的地址");
   	           	helper.setSubject("主题:带附件的邮件");
   	           	helper.setText("带附件的邮件内容");
   	            //注意项目路径问题,自动补用项目路径
   	            FileSystemResource file = new FileSystemResource(new File("D:\\每天传送的表格数据\\"+fn+".xls"));
   	            //加入邮件
   	            helper.addAttachment(fn+".xls", file);
   	        } catch (Exception e){
   	            e.printStackTrace();
   	        }
   	        mailSender.send(message);
        }   
		
	}
	
	public static void main(String[] args) {
		SpringApplication.run(PoiExcellApplication.class, args);
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值