javaMail发送邮件读取流中的数据并作为作为附件发送邮件
一、pom.xml中添加依赖
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.5</version>
</dependency>
二、//邮件标题
String mailTitle = "月度实体学校工资";
//邮件内容
String content = "集团人事老师,您好\r\n\r\n " + " 附件为"+DateUtil.getMonthStrByInteger(Integer.parseInt(beforeMonth.trim()))+"月度实体学校工资数据,如有疑问请随时沟通。\r\n" + "\r\n" + DateUtil.dateToString(new Date(), "yyyy-MM-dd");
- //读取数据
- List<StatTeacherMonthFeeBo> result = statTeacherMonthFeeDao.findExportList(Integer.parseInt(beforeMonth.trim()),schoolCode);
- if (result != null && !result.isEmpty()) {
- for (StatTeacherMonthFeeAgencyBo stat: result) {
- SignAgencyBo signAgencyBo = signAgencyDao.findSignAgencyById(stat.getRelAgencyId());
- SignDepartmentBo signDepartmentBo = signDepartmentDao.findSignDepartmentById(stat.getRelDepartmentId());
- if (signAgencyBo != null) {
- stat.setRelAgencyName(signAgencyBo.getSignAgencyName());
- }
- if (signDepartmentBo != null) {
- stat.setRelDepartmentName(signDepartmentBo.getSignDepartmentName());
- }
- }
- totalResult.add(result);
- }
- try {
- InputStream is = ClassScheduleExportHelper.exportStatTeacherMonthFeeToClient(totalResult);
- MailNotifyCore.sendSalaryMail(mailTitle, content, receive, receiveP,salarySendAccount,salarySendAccountKey,is,displayName);
- } catch (Exception e) {
- e.printStackTrace();
- }
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* 班级课程表导出工具类
*
*/
public class ClassScheduleExportHelper {
/**
* 导出实体学校工资导出到客户端,适合于Web导出
* @param result
* @param inputStream
*/
public static InputStream exportStatTeacherMonthFeeToClient(List<List<StatTeacherMonthFeeAgencyBo>> list) {
//读取薪资模板
URL url = ClassLoader.getSystemResource("templates");
File forder = new File(url.getPath() + "/stat_teacher_month_fee.xlsx");
Workbook workbook = null;
FileInputStream templete = null;
InputStream is = null;
try {
templete = new FileInputStream(forder);
workbook = new XSSFWorkbook(templete);
Sheet rootSheet = workbook.getSheetAt(0);
createStatTeacherMonthFeeAgency(workbook, rootSheet, list);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write(baos);
baos.flush();
byte[] bt = baos.toByteArray();
is = new ByteArrayInputStream(bt, 0, bt.length);
baos.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
workbook.close();
templete.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return is;
}
/**
* 实体学校工资
* @param workbook
* @param rootSheet
* @param list
*/
private static void createStatTeacherMonthFee(Workbook workbook, Sheet rootSheet,
List<List<StatTeacherMonthFeeAgencyBo>> list) {
if (list != null && !list.isEmpty()) {
int j = 0;
for (List<StatTeacherMonthFeeAgencyBo> totalResult : list) {
for (int i = 0 ; i < totalResult.size(); i++) {
StatTeacherMonthFeeAgencyBo stat = totalResult.get(i);
// 奖励、惩罚、非课时课金、总课时课金不为0,才导出
if(null != stat && (stat.getPunishFee() != 0 || stat.getRewardFee() != 0 )) {
Row dataRow = rootSheet.createRow(j+1);
dataRow.createCell(0).setCellValue(j+1);
dataRow.createCell(1).setCellValue(stat.getRelAgencyName());
dataRow.createCell(2).setCellValue(stat.getStatMonth());
dataRow.createCell(3).setCellValue(stat.getTeacherName());
dataRow.createCell(4).setCellValue(stat.getTeacherCode());
j++;
}
}
}
}
}
}
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;
public class MailNotifyCore {
public static String sendAccount = CacheMap.get(PropertyConstant.BILL_MAIL_SENDACCOUNT).toString();
public static String sendAccountP = CacheMap.get(PropertyConstant.BILL_MAIL_SENDACCOUNTPORT).toString();
public static String smtpHost = "smtp.exmail.qq.com";
public static String receiveAccount = CacheMap.get(PropertyConstant.BILL_MAIL_RECEIVEACCOUNT).toString();
public MailNotifyCore(String sendAccount, String sendAccoutP, String receiveAccount) {
}
public static void sendSalaryMail(String mailTitle, String content, String receive, String receiveP, String salarySendAccount, String salarySendAccountKey, InputStream is, String displayName) throws Exception {
//防止附件名称中文分割
System.setProperty("mail.mime.splitlongparameters","false");
// 1. 创建参数配置, 用于连接邮件服务器的参数配置
Properties props = new Properties(); // 参数配置
props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.host", smtpHost); // 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
final String smtpPort = "465";
props.setProperty("mail.smtp.port", smtpPort);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", smtpPort);
// 2. 根据配置创建会话对象, 用于和邮件服务器交互
Session session = Session.getDefaultInstance(props);
session.setDebug(false); // 设置为debug模式, 可以查看详细的发送 log
// 3. 创建一封邮件,如果attachmentFile存在则使用附件方式发送
MimeMessage message = null;
message = createSalaryMimeMessage(session, receive, receiveP, mailTitle, content,salarySendAccount,is,displayName);
// 4. 根据 Session 获取邮件传输对象
Transport transport = session.getTransport();
// 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
transport.connect(salarySendAccount, salarySendAccountKey);
// 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人,抄送人, 密送人
transport.sendMessage(message, message.getAllRecipients());
// 7. 关闭连接
transport.close();
}
private static MimeMessage createSalaryMimeMessage(Session session, String receive, String receiveP, String mailTitle, String content, String salarySendAccount, InputStream is, String displayName) throws Exception {
// 1. 创建一封邮件
MimeMessage message = new MimeMessage(session);
// 2. From: 发件人
message.setFrom(new InternetAddress(salarySendAccount, salarySendAccount, "UTF-8"));
// 3. To: 收件人(可以增加多个收件人、抄送、密送)
Address address = new InternetAddress(receive);
message.setRecipient(MimeMessage.RecipientType.TO, address);
//抄送人
Address addressP = new InternetAddress(receiveP);
message.setRecipient(MimeMessage.RecipientType.BCC, addressP);
// 4. Subject: 邮件主题
message.setSubject(mailTitle, "UTF-8");
// 5. Content: 邮件正文(可以使用html标签)
// message.setContent(content, "text/html;charset=UTF-8");
// 创建消息部分
BodyPart messageBodyPart = new MimeBodyPart();
// 消息
messageBodyPart.setText(content);
//附件
MimeMultipart mm = new MimeMultipart();
mm.setSubType("mixed"); // 混合关系
MimeBodyPart fileBody = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(is, "application/msexcel");
fileBody.setDataHandler(new DataHandler(source));
fileBody.setFileName(MimeUtility.encodeText(displayName,"UTF-8","B"));
mm.addBodyPart(fileBody);
mm.addBodyPart(messageBodyPart);
/*if(null != is && is.size() > 0) {
for (AttachmentBo attachmentBo : is) {
MimeBodyPart fileBody = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(attachmentBo.getInputStream(), "application/msexcel");
fileBody.setDataHandler(new DataHandler(source));
fileBody.setFileName(MimeUtility.encodeText(attachmentBo.getName(),"UTF-8","B"));
mm.addBodyPart(fileBody); // 如果有多个附件,可以创建多个多次添加
}
mm.addBodyPart(messageBodyPart);
}*/
message.setContent(mm);
// 6. 设置发件时间
message.setSentDate(new Date());
// 7. 保存设置
message.saveChanges();
return message;
}
}
javaMail发送邮件读取流中的数据并作为作为附件发送邮件相关推荐
- Stream流、FiLe和IO流、IO流(字节流-拷贝文件_和_字符流-读取文本中的数据写入文本文件中)9-10-11
package com.streamdemo; import java.util.ArrayList; import java.util.List; /*** 体验Stream流** 创建一个集合,存 ...
- python文件读取方法read(size)的含义是_在Python中可使用read([size])来读取文件中的数据,如果参数size省略,则读取文件中的()。(4.0分)_学小易找答案...
[单选题]文本文件存储的是(),由若干文本行组成,通常每行以换行符 '\n' 结尾.(4.0分) [单选题]()属性是返回被打开文件的访问模式.(4.0分) [单选题]重力坝是由砼或( )修筑而成的大 ...
- 使用poi读取Excel中的数据到数据库
大家好今儿给大家带来的是使用poi读取Excel中的数据到数据库 目录 大家好今儿给大家带来的是使用poi读取Excel中的数据到数据库 1.poi简单介绍 2.poi操作excel 3.代码部分(可 ...
- python文件读取方法read(size)的含义是_在Python中可使用read([size])来读取文件中的数据,如果参数size省略,则读取文件中的()。...
[单选题]李明在他所属的公司工作五年,每天都很认真地处理繁杂的事情,同事们都夸他认真,但是依然没有建树,这是因为: [多选题]品牌标志的作用表现在 [单选题]新产品开发的第一个阶段是_______. ...
- Spark读取Hive中的数据加载为DataFrame
首先要告诉SparkSql,Hive在哪.然后读取Hive中的数据,必须开启enableHiveSupport. val spark = SparkSession.builder().appName( ...
- Spark读取MySQL中的数据为DataFrame
Spark读取JDBC中的数据(以MySQL为例)为DataFrame,有两种方式. //聚合的时候默认分区是200,可以在此设置 val spark = SparkSession.builder() ...
- Spark _25.plus _使用idea读取Hive中的数据加载成DataFrame/DataSet(四)
对Spark _25 _读取Hive中的数据加载成DataFrame/DataSet(四) https://georgedage.blog.csdn.net/article/details/10309 ...
- Spark _25 _读取Hive中的数据加载成DataFrame/DataSet(四)
由于Hive不在本地,操作略显麻烦.不过细心一点,分析错误,也还好,如果你搭建的hadoop是HA,需要多注意: 这里指出一个错误,如果你报了同类错误,可以参考:https://georgedage. ...
- Spark _24 _读取JDBC中的数据创建DataFrame/DataSet(MySql为例)(三)
两种方式创建DataSet 现在数据库中创建表不能给插入少量数据. javaapi: package SparkSql;import org.apache.spark.SparkConf; impor ...
最新文章
- SpringMvc+ajax实现文件跨域上传
- 请问有办法加速TTS的反应时间吗
- 【Android 逆向】ART 脱壳 ( DexClassLoader 脱壳 | DexClassLoader 构造函数 | 参考 Dalvik 的 DexClassLoader 类加载流程 )
- oracle 效率问题,Oracle【诡异】的效率问题
- java内存问题怎么排查,java占内存高排查 java应用占用内存过高排查的解决方案...
- SecureCRT 遇到一个致命的错误且必须关闭
- Linux系统常用目录操作函数
- hashmap扩容机制_图文并茂:HashMap经典详解!
- CC版本添加 LUCI
- 光流.flo文件生成.png图片(可批量)
- MYSQL-常用函数
- Javascript特效:输入框焦点判断
- ffmpeg下载m3u8的视频流文件
- Android Studio设计用户登录界面
- 探究本质,WebGIS前端地图显示之地图比例尺换算原理
- 单片微机原理与接口技术——8051汇编指令系统与编程基础(2)数据传送指令
- 淘宝/天猫获取卖出的商品订单列表 API
- 电脑查看Windows的具体过期日期
- 吉信通短信接口(HTTP协议) java
- 推荐8个值得推荐的神器软件和网站
热门文章
- CentOS网络配置文件中UUID参数释疑
- OpenInfra Summit 2022 | 安超云用户脱颖而出 入围超级用户大奖
- Python实现ARCGIS栅格计算器con函数功能
- 怎么写实验论文的结果和分析
- SpringBoot(一):什么是SpringBoot?
- 初中计算机案例交流,初中语文与信息技术整合教学案例——《爱莲说》
- Android-适配各国语言、屏幕尺寸、系统版本及常见适配方法总结
- python位置参数ppt_argparse模块的位置参数和可选(必选)参数
- 【QQ技术】群文件报毒怎样下载?~ 变相绕过QQ复杂检验过程
- 盛大搅局手游市场:引入日系卡牌游戏_0