JAVA 数据写入excel并发送邮件
写这个的时候PLM系统还没有开发好,开发这个系统的外包团队每次开会都会被骂,感觉他们快顶不住了,估计完成不了了,烂尾之后应该会有很多需求扔给我。新领导上任之后说这边能不能发邮件,先熟悉一下怎么发邮件吧,这个功能大概率给我来做了
流程:
先导包 => 邮箱开启配置 => java写好配置类 => 测试发送 => 数据写入excel => 邮件带附件发送
邮箱jar包
<dependencies>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
邮箱开启配置
我这个是163的,开启之后会生成授权码,记得复制粘贴到自己的项目配置文件里面去
邮箱配置类
public final class JavaMailUtil {
//文件地址 上面是linux地址,下面是我自己本地测试用的
//public final static String FILEPATH = "/wenjie/javaProject/bomexcelfiles";
public final static String FILEPATH = "e:/Users/liuwenj/Desktop/";
private JavaMailUtil() {
}
public static Session createSession() {
//账号信息
String username = "";//邮箱发送账号
String password = "";//邮箱授权码
//创建一个配置文件,并保存
Properties props = new Properties();
//SMTP服务器连接信息
//126——smtp.126.com
//163——smtp.163.com
props.put("mail.smtp.host", "smtp.126.net");//SMTP主机名
//126——25
//163——645 如果645一直连不上,可以换成25试一试
props.put("mail.smtp.port", "25");// 主机端口号
props.put("mail.smtp.auth", "true");// 是否需要用户认证
props.put("mail.smtp.starttls.enable", "true");// 启用TlS加密
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// TODO Auto-generated method stub
return new PasswordAuthentication(username, password);
}
});
//控制台打印调试信息
session.setDebug(true);
return session;
}
}
测试发送纯文本
//创建Session会话
Session session = JavaMailUtil.createSession();
//创建邮件对象
MimeMessage message = new MimeMessage(session);
message.setSubject("主题");
message.setFrom(new InternetAddress("发送者邮箱"));
//发送给一个人
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("接收者邮箱"));
//发送给多个人
//message.setRecipients(MimeMessage.RecipientType.CC, new InternetAddress[] {new InternetAddress("接收者邮箱")});
//纯文本信息
message.setText("文本信息:来自于公司PLM系统测试");
//发送
Transport.send(message);
数据写入excel,并生成文件
先导jar
<!-- Apache POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
写入数据到excel
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Bom");
//第一行的数据名
List<String> labelList = Arrays.asList("物料编码", "描述");
Row row = sheet.createRow(0);
for (int i = 0; i < labelList.size(); i++) {
row.createCell(i).setCellValue(labelList.get(i));
}
int rowNo = 1;
//获取数据然后放入Excel
List<Map<String, Object>> bomList = plmDataService.getBomNotPerfect();
for (Map<String, Object> bom : bomList) {
String no = (String) bom.get("ITEM_NUMBER");
String desc = (String) bom.get("DESCRIPTION");
Row tempRow = sheet.createRow(rowNo);
rowNo++;
tempRow.createCell(0).setCellValue(no);
tempRow.createCell(1).setCellValue(desc);
}
// 写入数据到Excel
try (FileOutputStream outputStream = new FileOutputStream(JavaMailUtil.FILEPATH + fileName)) {
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
workbook.close(); //关闭工作簿
} catch (IOException e) {
e.printStackTrace();
}
}
一切准备就绪之后就可以发送邮件了
发送邮件(带附件)
//创建会话
Session session = JavaMailUtil.createSession();
//创建邮件对象
MimeMessage message = new MimeMessage(session);
message.setSubject("主题");
message.setFrom(new InternetAddress("发送者邮箱"));
//发送给一个人
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("接收者邮箱"));
//发送给多个人
//message.setRecipients(MimeMessage.RecipientType.CC, new InternetAddress[] {new InternetAddress("接收者邮箱")});
//邮件主体
BodyPart textPart = new MimeBodyPart();
textPart.setContent("文本信息:来自于公司PLM系统测试", "text/html;charset=utf-8");
//邮件附件
BodyPart filePart = new MimeBodyPart();
filePart.setFileName(fileName);
//提交附件文件
filePart.setDataHandler(new DataHandler(new ByteArrayDataSource(Files.readAllBytes(Paths.get(JavaMailUtil.FILEPATH + fileName)), "application/octet-stream")));
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(textPart);
multipart.addBodyPart(filePart);
//将邮件装入信封
message.setContent(multipart);
//发送
Transport.send(message);
如果有发送一些特殊需求,比如需要内嵌图片HTML
发送邮件(内嵌图片HTML)
PS: 没有试过,copy的代码,贴上去以后如果有需求了再验证
Session session = JavaMailUtils.createSession(); //创建session对象
MimeMessage message = new MimeMessage(session); //创建message对象
message.setSubject("测试邮件"); //设置邮件标题
message.setFrom(new InternetAddress("[email protected]")); //设置发送方地址
message.setRecipient(RecipientType.TO, new InternetAddress("[email protected]")); //设置接收方地址
message.setRecipients(RecipientType.CC, new InternetAddress[] {new InternetAddress("[email protected]"),new InternetAddress("[email protected]")}); //群发(抄送多人)
//正文
BodyPart textPart=new MimeBodyPart();
StringBuilder contentText=new StringBuilder();
contentText.append("<h3>网易邮箱/h3>");
contentText.append("<p>给QQ邮箱发消息了!</p>");
contentText.append("<img src=\"cid:xxx\"/>");
textPart.setContent(contentText.toString(),"text/html;charset=utf-8");
//附件
BodyPart imagePart=new MimeBodyPart();
imagePart.setDataHandler(new DataHandler(
new ByteArrayDataSource(Files.readAllBytes(Paths.get("D://test//1.jpg")), "application/octet-stream"))); //
imagePart.setHeader("Content-ID", "xxx"); //图片的内容ID
Multipart multipart=new MimeMultipart(); //创建multipart对象
multipart.addBodyPart(textPart); //将textPart对象放入multipart
multipart.addBodyPart(filePart); //将filePartt对象放入multipart
message.setContent(multipart); //将multipart对象放入邮件
Transport.send(message); //发送邮件