Csv order download, followed by email notification download, csv mail Notification

Source: Internet
Author: User

Csv order download, followed by email notification download, csv mail Notification
Preface

During feature development, a large number of order downloads are encountered, and the server's request response time is configured very short, resulting in request timeout during download.

The main idea of this article is to query data asynchronously, generate a csv file, put it in an email, and send it to the user. (This article does not describe the asynchronous part. You can configure a thread pool)

The code can be used for the test. You need to configure the mailbox settings at the bottom of the article.

Code (containing the JavaMail jar package): https://gitee.com/wangpinpin_595/reservationDownload/attach_files

 

 

Body

The Code is as follows:

Main. java

Import java. io. *; import java. util. *; public class Main {/*** csv format order download. After the download is completed, the email notification will be downloaded. * The steps are divided into three parts: step by step, in fact, it is very simple * encapsulate data --> standardize csv format and write files --> email notification ** @ author wappin */public static void main (String [] args) throws Exception {// encapsulate data // I can write test data at Will here. In the previous project, the data read from the database is replaced here. List <Student> studentList = new ArrayList <> (); studentList. add (new Student (1, "James", "male", "18011111111"); studentList. add (new Student (2, "John", "male", "18022222222"); studentList. add (new Student (3, "John", "male", "18033333333"); studentList. add (new Student (4, "Xiaohong", "female", "18044444444"); studentList. add (new Student (5, "Xiaohua", "female", "18055555555"); // standardize csv format and Write File file = signing ing. configuringCsvFormat (studentList); // email notification SendEmailUtil. sendEmail ("442042162@qq.com", file); // delete the file after sending, see personal needs to use // file. delete ();}}

 

 

Student. java

/*** Student Entity class */public class Student {private int id; // id private String name; // name private String gender; // gender private String phoneNumber; // phone number 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 ;}}

 

 

Processing. java

Import java. io. *; import java. util. arrayList; import java. util. linkedHashMap; import java. util. list; import java. util. map; /*** standardize csv format and write files * @ author wappin */public class grouping {/*** configure csv format */static File configuringCsvFormat (List <Student> studentList) {LinkedHashMap <String, String> superClassMap = new LinkedHashMap <> (); // The key corresponds to the object class parameter, and the value corresponds to the csv title superClassMap. put ("id", "Number"); superClassMap. Put ("name", "name"); superClassMap. put ("gender", "gender"); superClassMap. put ("phoneNumber", "phone number"); 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);}/*** Write File */private static <T> File writeFile (List <T> list, linkedHashMap <String, String> fieldMap) {// file storage address and name String downCsvForEmailAddress = "E: \" + System. currentTimeMillis (); File file = new File (downCsvForEmailAddress); FileOutputStream out; OutputStrea MWriter 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 version: 1.6.0 * JDK version: JDK 1.7 or later (required) * Reference document: http://blog.csdn.net/xiet Ansheng/article/details/51673073 */public class SendEmailUtil {// sender's mailbox public static String myEmailAccount = "fill in"; // authorization code> independent password> password (priority) public static String myEmailPassword = ""; // SMTP server address public static String myEmailSMTPHost = "smtp.qq.com "; /*** configure the recipient and email protocol information ** @ param receiveMailAccount recipient address * @ param attachment * @ throws Exception */public static void sendEmail (String receiveMai LAccount, File attachment) throws Exception {// 1. create a parameter configuration for connecting to the mail server. The parameter configuration Properties props = new Properties (); // The parameter configuration props. setProperty ("mail. transport. protocol "," smtp "); // The protocol used (JavaMail specification requirements) props. setProperty ("mail. smtp. host ", myEmailSMTPHost); // The SMTP server address of the sender's email address props. setProperty ("mail. smtp. auth "," true "); // The final String smtpPort =" 465 "; props. setProperty ("mail. smtp. port ", smtpP Ort); 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); // set it to debug mode. You can view the detailed sending log session. setDebug (false); // 3. create an email MimeMessage message = createMimeMessage (session, myEmailAccount, recei VeMailAccount, attachment); Transport transport = session. getTransport (); transport. connect (myEmailAccount, myEmailPassword); transport. sendMessage (message, message. getAllRecipients (); transport. close ();} /*** create a simple email containing only text ** @ param session and server interaction session * @ param sendMail sender email * @ param receiveMail recipient email * @ param attachment * @ throws Exception */public static MimeMessage createMimeMessage (Se Ssion session, String sendMail, String receiveMail, File attachment) throws Exception {// 1. create an email MimeMessage message = new MimeMessage (session); // 2. from: The sender message. setFrom (new InternetAddress (sendMail, "", "UTF-8"); // 3. to: recipient (multiple recipients, CC, and BCC can be added) message. setRecipient (MimeMessage. recipientType. TO, new InternetAddress (receiveMail, "Recipient Name", "UTF-8"); message. addHeader ("charset", "UTF-8 "); Message. setSubject ("topic"); // Add the body content Multipart multipart = new MimeMultipart (); BodyPart contentPart = new MimeBodyPart (); contentPart. setContent ("body content", "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 ("attachment name.csv"); multipart. addBodyPart (attachmentBodyPart);} message. setContent (multipart); message. setSentDate (new Date (); message. saveChanges (); return message ;}}

 

 

Mailbox Configuration

I used QQ mail to do the test. I didn't try other mailboxes. It should be similar.

Qq mail server address: smtp.qq.com

Click "Settings"> "Account", and enable POP3, SMTP, and IMAP to obtain an authorization code (corresponding to the myEmailPassword parameter ),

 

If mailbox configuration still do not know can refer to this article, write very detailed: http://blog.csdn.net/xietansheng/article/details/51673073

 

 

Coding Changes the World

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.