csv格式订单下载,完成后伴随邮件通知下载
前言
功能开发中会遇到大量订单下载,而服务器的请求响应时间又配置的很短,导致下载时候请求超时。
这篇文章主要思路:异步查询数据,生成csv文件,放入email中并发送给用户。(异步部分本文不做介绍,配置个线程池就可以)
代码亲测可以使用,邮箱的设置稍微需要配置一下 文章底部会说明。
代码下载地址(包含JavaMail jar包):https://gitee.com/wangpinpin_595/reservationDownload/attach_files
正文
代码如下:
Main.java
import java.io.*; import java.util.*; public class Main { /** * csv格式订单下载,完成后伴随邮件通知下载 * 步骤分三部,一步一步的看,其实很简单 * 封装数据-->规范csv格式及写入文件-->邮件通知 * * @author wappin */ public static void main(String[] args) throws Exception { //封装数据 //我这里随便写点测试数据,上项目的时候,这里换成数据库读的数据。 List<Student> studentList = new ArrayList<>(); studentList.add(new Student(1, "小明", "男", "18011111111")); studentList.add(new Student(2, "小王", "男", "18022222222")); studentList.add(new Student(3, "小张", "男", "18033333333")); studentList.add(new Student(4, "小红", "女", "18044444444")); studentList.add(new Student(5, "小花", "女", "18055555555")); //规范csv格式及写入文件 File file = Configuring.configuringCsvFormat(studentList); //邮件通知 SendEmailUtil.sendEmail("442042162@qq.com", file); //发送结束后删除文件,看个人需求使用 //file.delete(); } }
Student.java
/** * 学生实体类 */ public class Student { private int id; //id private String name; //姓名 private String gender; //性别 private String phoneNumber;//电话号码 Student(int id, String name, String gender, String phoneNumber) { this.id = id; this.name = name; this.gender = gender; this.phoneNumber = phoneNumber; } int getId() { return id; } String getName() { return name; } String getGender() { return gender; } String getPhoneNumber() { return phoneNumber; } void setId(int id) { this.id = id; } void setName(String name) { this.name = name; } void setGender(String gender) { this.gender = gender; } void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } }
Configuring.java
import java.io.*; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * 规范csv格式及写入文件 * @author wappin */ public class Configuring { /** * 配置csv格式 */ static File configuringCsvFormat(List<Student> studentList) { LinkedHashMap<String, String> superClassMap = new LinkedHashMap<>(); //key对应实体类参数,value对应csv标题 superClassMap.put("id", "编号"); superClassMap.put("name", "姓名"); superClassMap.put("gender", "性别"); superClassMap.put("phoneNumber", "电话号码"); List<String> list = new ArrayList<>(); StringBuilder sb = new StringBuilder(); for (Student stu : studentList) { sb.append(stu.getId()).append("\t,"). append(stu.getName() != null ? stu.getName() : "").append("\t,"). append(stu.getGender() != null ? stu.getGender() : "").append("\t,"). append(stu.getPhoneNumber() != null ? stu.getPhoneNumber() : "").append("\t"); list.add(sb.toString()); sb.delete(0, sb.length()); } return writeFile(list, superClassMap); } /** * 写入文件 */ private static <T> File writeFile(List<T> list, LinkedHashMap<String, String> fieldMap) { //文件存放地址及名称 String downCsvForEmailAddress = "E:\\" + System.currentTimeMillis(); File file = new File(downCsvForEmailAddress); FileOutputStream out; OutputStreamWriter osw = null; BufferedWriter bw = null; try { out = new FileOutputStream(file); osw = new OutputStreamWriter(out, "GBK"); bw = new BufferedWriter(osw); if (fieldMap != null) { StringBuilder head = new StringBuilder(); for (Map.Entry<String, String> stringStringEntry : fieldMap.entrySet()) { head.append(",").append(((Map.Entry) stringStringEntry).getValue() != null ? (String) ((Map.Entry) stringStringEntry).getValue() : ""); } head = new StringBuilder(head.substring(1, head.length())); bw.append(head.toString()).append("\r"); } for (T aList : list) { bw.append(aList.toString()).append("\r"); } } catch (Exception e) { e.printStackTrace(); } finally { if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } if (osw != null) { try { osw.close(); } catch (IOException e) { e.printStackTrace(); } } } return file; } }
SendEmailUtil.java
import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.*; import java.io.File; import java.util.Date; import java.util.Properties; /** * JavaMail 版本: 1.6.0 * JDK 版本: JDK 1.7 以上(必须) * 参考文档: http://blog.csdn.net/xietansheng/article/details/51673073 */ public class SendEmailUtil { //发件人邮箱 public static String myEmailAccount = "自己填"; //授权码 > 独立密码 > 密码(优先级) public static String myEmailPassword = "自己填"; //SMTP 服务器地址 public static String myEmailSMTPHost = "smtp.qq.com"; /** * 配置收件人及邮件协议信息 * * @param receiveMailAccount 收件人地址 * @param attachment 附件 * @throws Exception */ public static void sendEmail(String receiveMailAccount, File attachment) throws Exception { // 1. 创建参数配置, 用于连接邮件服务器的参数配置 Properties props = new Properties(); // 参数配置 props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求) props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 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); Session session = Session.getInstance(props); // 设置为debug模式, 可以查看详细的发送 log session.setDebug(false); // 3. 创建一封邮件 MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount, attachment); Transport transport = session.getTransport(); transport.connect(myEmailAccount, myEmailPassword); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } /** * 创建一封只包含文本的简单邮件 * * @param session 和服务器交互的会话 * @param sendMail 发件人邮箱 * @param receiveMail 收件人邮箱 * @param attachment 附件 * @throws Exception */ public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, File attachment) throws Exception { // 1. 创建一封邮件 MimeMessage message = new MimeMessage(session); // 2. From: 发件人 message.setFrom(new InternetAddress(sendMail, "", "UTF-8")); // 3. To: 收件人(可以增加多个收件人、抄送、密送) message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "收件人姓名", "UTF-8")); message.addHeader("charset", "UTF-8"); message.setSubject("主题"); //添加正文内容 Multipart multipart = new MimeMultipart(); BodyPart contentPart = new MimeBodyPart(); contentPart.setContent("正文内容", "text/html;charset=UTF-8"); multipart.addBodyPart(contentPart); //附件 if (attachment != null) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); attachmentBodyPart.setDataHandler(new DataHandler(source)); attachmentBodyPart.setFileName(MimeUtility.encodeText("附件名称.csv")); multipart.addBodyPart(attachmentBodyPart); } message.setContent(multipart); message.setSentDate(new Date()); message.saveChanges(); return message; } }
邮箱配置
我用QQ邮箱做的测试,其他邮箱没有试,应该大同小异。
QQ邮箱服务器地址:smtp.qq.com
点击设置–帐号,开启POP3/SMTP/IMAP会得到一个授权码(对应myEmailPassword参数),如图:
如果邮箱配置还有不太懂得可以参考这篇文章,写的很详细:http://blog.csdn.net/xietansheng/article/details/51673073