springboot定時發郵件
阿新 • • 發佈:2019-01-04
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); } }