一、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;
}
}