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);
}
}