思路:Java创建Excel,返回一个ByteArrayOutputStream 流 ==> sendEmail()接受ByteArrayOutputStream 流以附件的形式发送出去
创建Excel表格:
public class CreatExcel {
public static ByteArrayOutputStream creatExcel(String[] title, JSONArray all) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//创建一个表格
Workbook workbook = new XSSFWorkbook();
// 创建一个工作薄对象
XSSFSheet sheet = (XSSFSheet) workbook.createSheet("sheet1");
//设置首行
XSSFRow row0 = sheet.createRow(0);
for(int i=0;i
Java 邮件发送附件:
public class SendEmail {
public static boolean sendEmail(String to,ByteArrayOutputStream baos) {
// 发件人电子邮箱
String from = "*****@qq.com";
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器 ->QQ 邮件服务器
properties.setProperty("mail.smtp.host", "smtp.qq.com");
properties.put("mail.smtp.auth", "true");
// 获取默认session对象
Session session = Session.getDefaultInstance(properties,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("*******@qq.com", "******"); //发件人邮件用户名、授权码
}
});
try{
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// Set From: 头部头字段
message.setFrom(new InternetAddress(from));
// Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
// Set Subject: 头部头字段
message.setSubject("This is the Subject Line!");
/*添加附件*/
Multipart multipart = new MimeMultipart();
if(baos != null) {
MimeBodyPart fileBody = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(baos.toByteArray(), "application/msexcel");
fileBody.setDataHandler(new DataHandler(source));
// 中文乱码问题
fileBody.setFileName(MimeUtility.encodeText("ww.xlsx"));
multipart.addBodyPart(fileBody);
}
message.setContent(multipart);
// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....from runoob.com");
}catch (MessagingException mex) {
mex.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
JSONArray all = new JSONArray();
String[] title = {"哈哈","hahahah"};
ByteArrayOutputStream baos = CreatExcel.creatExcel(title, all);
SendEmail.sendEmail("******@qq.com",baos);
}
}