最近做项目的时候遇到了这样一个问题,微信内置的浏览器把下载这个功能屏蔽了。唉,,,折腾了一天,从网上各种找资料,但是给的解决方案都不是我想要的(也不知道谁复制的谁的,基本都一样)。
在快下班的时候,我请教了一位朋友,我问他是怎么解决的,他说:很简单,发邮件就可以了。
为方便大家开发,下面附上代码。此代码包括发送邮件和生成表格。
/**
* @author h_debug
* @date 2018年7月21日 上午9:13:25
* @Copyright: 2018 . All rights reserved.
* @version V1.0
*/
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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.util.ByteArrayDataSource;
import javax.servlet链接
import javax.servlet链接
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.tomcat.util链接
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.sun.mail.util.MailSSLSocketFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@RequestMapping("/sendmail")
@Controller
public class SendMailUtil {
/*
* 发送邮件到指定邮箱
*/
@SuppressWarnings("deprecation")
@RequestMapping(value = "/moremail", method = RequestMethod.POST)
public static void send(HttpServletRequest request,@RequestParam(value = "emails", required = true) String emails,@RequestParam(value = "contents", required = true) String contents,@RequestParam(value = "mores", required = true) String mores,HttpServletResponse resp) throws Exception{
// // 未填写邮箱地址的供货商列表
// ListvendorsList = new ArrayList();
String path = request.getRealPath("WEB-INF/excel/aaa.xls");
ByteArrayOutputStream byteOS = new ByteArrayOutputStream();
@SuppressWarnings("resource")
FileInputStream fis = new FileInputStream(path);
byte[] by = new byte[512];
int t = fis.read(by,0,by.length);
while(t>0){ byteOS.write(by, 0, 512); //这里别写成t,写够512,呵呵,SB的方法对付SB的java API
t = fis.read(by,0,by.length);
}
byteOS.close();
InputStream byteIS = new ByteArrayInputStream(byteOS.toByteArray());
HSSFWorkbook workBook = new HSSFWorkbook(byteIS);
// 获取第一个sheet页
HSSFSheet sheet=workBook.getSheetAt(0);
/******************************设置表头*****************************/
String sheetTitle = contents+"--进出库详情";
// 单元格合并
// 四个参数分别是:起始行,起始列,结束行,结束列
sheet.addMergedRegion(new CellRangeAddress(0,1,0,4));
// 创建表头并赋值
HSSFRow rowTitle = sheet.createRow(0);
HSSFCell cellTitle = rowTitle.createCell(0);
cellTitle.setCellValue(sheetTitle);
// 创建剧中样式
HSSFCellStyle cellStyle = workBook.createCellStyle();
// 垂直居中
cellStyle.setAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 水平居中
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 创建字体
HSSFFont cellFont = workBook.createFont();
cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
cellFont.setFontHeight((short) 300);
cellStyle.setFont(cellFont);
cellTitle.setCellStyle(cellStyle);
/**********************遍历物料,并将物料列表显示到模板中,作为邮件的附件***********************/
JSONArray jsonss=JSONArray.fromObject(mores);
// 行号下标,从0开始
int rowIndex = 2 ;
for(int j=0;jrowIndex++;
// 创建行
HSSFRow row=sheet.createRow(rowIndex);
// 根据下标创建单元格
// 设置物料序号
row.createCell(0).setCellValue(j+1);
// 设置IMPA编码
if(null != jsonss.getJSONObject(j).getString("sname")){
row.createCell(1).setCellValue(jsonss.getJSONObject(j).getString("sname"));
}else {
row.createCell(1).setCellValue("");
}
// 设置物料中文名称
if(null != jsonss.getJSONObject(j).getString("conts")){
row.createCell(2).setCellValue(jsonss.getJSONObject(j).getString("conts"));
}else {
row.createCell(2).setCellValue("");
}
// 设置物料英文名称
if(null != jsonss.getJSONObject(j).getString("iconts")){
row.createCell(3).setCellValue(jsonss.getJSONObject(j).getString("iconts"));
}else {
row.createCell(3).setCellValue("");
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
workBook.write(baos);
baos.flush();
byte[] bt = baos.toByteArray();
InputStream is = new ByteArrayInputStream(bt, 0, bt.length);
baos.close();
boolean s = sendMail(sheetTitle, emails, "aa" , is);
System.out.println(s+"00000");
JSONObject Json = new JSONObject();
JSONArray JsonArray = new JSONArray();
if(s) {
Json.put("status", "1");
Json.put("data", s);
Json.put("contents", "导出成功");
}else {
Json.put("status", "0");
Json.put("data", s);
Json.put("contents", "导出失败");
}
JsonArray.add(Json);
try {
resp.setCharacterEncoding("UTF-8");
resp.getWriter().print(Json);
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean sendMail(String subject, String to, String content, InputStream is) throws GeneralSecurityException, IOException {
boolean isFlag = false;
// 收件人电子邮箱
//String to = "收件人电子邮箱";
// 发件人电子邮箱
String from = "发件人电子邮箱";
// 指定发送邮件的主机为 smtp.qq.com
String host = "smtp.qq.com"; //QQ 邮件服务器
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
// 获取默认session对象
Session session = Session.getDefaultInstance(properties,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("发件人电子邮箱", "发件人电子邮箱密码"); //发件人邮件用户名、密码
}
});
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(subject);
// 设置消息体
// 创建消息部分
BodyPart messageBodyPart = new MimeBodyPart();
// 消息
messageBodyPart.setText(subject);
// 创建多重消息
Multipart multipart = new MimeMultipart();
// 设置文本消息部分
multipart.addBodyPart(messageBodyPart);
// 附件部分
messageBodyPart = new MimeBodyPart();
String filename = subject+".xls";
DataSource source = new ByteArrayDataSource(is, "application/msexcel");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// 发送完整消息
message.setContent(multipart);
// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....from runoob.com");
isFlag = true;
}catch (MessagingException mex) {
mex.printStackTrace();
isFlag = false;
}
return isFlag;
//return false;
}
}
转自LCSDNY的博客