/**
* Created by Administrator on 2020-3-19.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
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.internet.MimeMessage.RecipientType;
import javax.mail.util.ByteArrayDataSource;
import com.mchange.v2.util.PropertiesUtils;
import com.sinosoft.lis.bigdata.PropertiesUtil;
import com.sinosoft.lis.ergoServerInterf.publics.EmailData;
import com.sinosoft.lis.taskservice.TaskThread;
import com.sinosoft.utility.ExeSQL;
import com.sinosoft.utility.SSRS;
import com.sun.mail.util.MailSSLSocketFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EmailSend extends TaskThread{
String email_host = "邮件服务器地址";
String send_email_account="邮件服务器用户";
String send_email_pwd="邮件服务器密码";
/**
* 发送邮件
*
* @param to 邮件收件人地址
* @param title 邮件标题
* @param text 内容
* @param text 附件标题
* @param
*/
public void sendMsgFileDs(String to, String title, String text,String affixName, ByteArrayInputStream inputstream) {
Session session = assembleSession();
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(send_email_account));
msg.setSubject(title);
msg.setRecipients(RecipientType.TO, acceptAddressList(to));
MimeBodyPart contentPart = (MimeBodyPart) createContent(text, inputstream,affixName);//参数为正文内容和附件流
MimeMultipart mime = new MimeMultipart("mixed");
mime.addBodyPart(contentPart);
msg.setContent(mime);
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
public Address[] acceptAddressList(String acceptAddress) {
// 创建邮件的接收者地址,并设置到邮件消息中
Address[] tos = null;
try {
tos = new InternetAddress[1];
tos[0] = new InternetAddress(acceptAddress);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tos;
}
public Session assembleSession() {
Session session = null;
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
//props.setProperty("mail.smtp.port", "587");//465 587
props.setProperty("mail.smtp.host", email_host);//邮件服务器地址
props.setProperty("mail.user", send_email_account);//用户
props.setProperty("mail.user", send_email_pwd);//密码
session = Session.getInstance(props, new MyAuthenricator(send_email_account, send_email_pwd));
return session;
}
//用户名密码验证,需要实现抽象类Authenticator的抽象方法PasswordAuthentication
static class MyAuthenricator extends Authenticator {
String user = null;
String password = null;
public MyAuthenricator(String user, String password) {
this.user = user;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
}
/**
* 附件内容
* @param content
* @param inputstream
* @param affixName
* @return
*/
static Part createContent(String content, ByteArrayInputStream inputstream, String affixName) {
MimeBodyPart contentPart = null;
try {
contentPart = new MimeBodyPart();
MimeMultipart contentMultipart = new MimeMultipart("related");
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(content, "text/html;charset=gbk");
contentMultipart.addBodyPart(htmlPart);
//附件部分
MimeBodyPart excelBodyPart = new MimeBodyPart();
DataSource dataSource = new ByteArrayDataSource(inputstream, "application/excel");
DataHandler dataHandler = new DataHandler(dataSource);
excelBodyPart.setDataHandler(dataHandler);
excelBodyPart.setFileName(MimeUtility.encodeText(affixName));
contentMultipart.addBodyPart(excelBodyPart);
contentPart.setContent(contentMultipart);
} catch (Exception e) {
e.printStackTrace();
}
return contentPart;
}
@Override
public boolean dealMain() {
EmailNameList emailNameList = new EmailNameList();
EmailData emailData = emailNameList.getqtykSendData();
try {
sendMailWithExcels(emailData.getSqlStr(),emailData.getHeaders(),emailData.getToEmail(),emailData.getTitle(),emailData.getEmailContent(),emailData.getAffixNam());
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
*
* @param sqlStr 执行逻辑sql
* @param headers xsl列抬头
* @param toEmail 收件邮件地址
* @param title 邮件标题
* @param emailContent 邮件内容
* @param affixName 附件名称
* @throws IOException
*/
public void sendMailWithExcels(String sqlStr,String headers[],String toEmail,String title, String emailContent,String affixName) throws IOException {
//String[] headers = {"col1","col2","col3","col4"};
// 声明一个工作薄
HSSFWorkbook wb = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(headers[i]);
}
ExeSQL tExeSQL = new ExeSQL();
SSRS ssrs = tExeSQL.execSQL(sqlStr);
for (int j=1;j<=ssrs.getMaxRow(); j++){
row = sheet.createRow(j);
for(int i=0; i<headers.length; i++){
HSSFCell cell1 = row.createCell(i);
cell1.setCellValue(ssrs.GetText(j,i+1));
}
}
/*for(int j=0; j<3; j++){
row = sheet.createRow(rowIndex);
rowIndex++;
HSSFCell cell1 = row.createCell(0);
cell1.setCellValue(j);
cell1 = row.createCell(1);
cell1.setCellValue(j+1);
cell1 = row.createCell(2);
cell1.setCellValue(j+2);
}*/
for (int i = 0; i < headers.length; i++) {
sheet.autoSizeColumn(i);
}
ByteArrayOutputStream os = new ByteArrayOutputStream(1000);
wb.write(os);
wb.close();
ByteArrayInputStream iss = new ByteArrayInputStream(os.toByteArray());
os.close();
sendMsgFileDs(toEmail,//邮件收件人地址
title,//邮件标题
emailContent, //内容
affixName+".xlsx",//附件标题(注意:附件需要带后缀,例如上面例子,附件名称可以写 测试.xlsx)
iss );
}
public String SendHTMLMsg()
{
String tCurrentDate = "";
String message="";
message+="<html>";
message+="<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf8\"></head>\n";
message+="\n<body>";
message+="<p>大家好!</p>";
message+="<p> "+tCurrentDate+"日上报数据有误,详见附件。</p>";
message+="</body></html>";
System.out.println("message is :"+message);
return message;
}
}
<!--邮件发送pom-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>