Java implementation Send mail can be multiple attachments inline picture-commons-email use

Source: Internet
Author: User

Objective

Java implementation of the E-mail function, in fact, Sun in the Java EE Development package provides us with the relevant tools, using Mail.jar and Activation.jar can achieve this function, n years ago, including my first internship when the project was also implemented with sun provided package, to achieve a more cumbersome trouble, today we use Apache Toolkit Commons-email package to send with mail and embedded image function, it is the former made the next seal It is easier and easier to use, so we use Commons-email to send mail, we must also introduce Mail.jar, Activation.jar2 a dependency package, myeclipse is self-contained, so if you do not know Commons-email.jar also need to rely on this 2 package, once the project into other development environment, there may be classnotfund exception, do not know you may still be depressed , here to provide you with this three jar package for free: Java Mail function jar package free download, good nonsense, not to say, directly into the code, the code I commented very detailed, do not make redundant explanations, we see it.

Description

because of the time tight, has been busy project closed development, so first directly posted implementation code and test code, temporarily do not make layout and the various functions of the code description and attention, but the code comments are very detailed, we will understand, and so there will be time for the post to do further repair color and typesetting, The description of the code to the aspects of everyone better understanding and grasp, if there are any questions or suggestions, welcome message!


Implementation code:
Package Sendemail;import Java.net.malformedurlexception;import Java.net.url;import java.util.map;import Javax.mail.messagingexception;import Org.apache.commons.mail.emailattachment;import Org.apache.commons.mail.emailexception;import Org.apache.commons.mail.htmlemail;import Org.apache.commons.mail.imagehtmlemail;import Org.apache.commons.mail.resolver.datasourceurlresolver;public Class Email {//mailbox server login user name private static string Username= "[email protected]";//mailbox server password private static string Password= "zhangchen713115";//Mailbox server SMTP host, which uses its own QQ mailbox as the mail server private static String smtphost= "smtp.qq.com"; Sender's mailbox (must be the login user name for the mailbox server) private static string Fromemail= "[email protected]";//Sender name private static string Fromusername= "xxx Company";//message content encoding, prevent garbled private static String charset= "UTF-8";/** *java Send mail-commons-email * @param  Nameandaddrmap user name and corresponding mailbox map * @param subject Mail subject or Title * @param htmlcontent message content HTML format * @throws emailexception * @throws Messagingexception * @author chenleixing */public Static void SendEmail (map<string,string> nameandaddrmap,string subject,string htmlcontent) throws Emailexception, messagingexception{//simpleemail email = new Simpleemail ()//create Simple mail, not attachments, HTML text, etc.//multipartemail email = new Mult  Ipartemail ();//create mail with attachments, multiple, Web attachments/*imagehtmlemail:html text messages, inline images via 2 code, 1.3 New, but I'm also testing unsuccessfully Imagehtmlemail Online are official online examples and the official online example is more ambiguous imagehtmlemail email=new imagehtmlemail (); */htmlemail email = new Htmlemail ();// Create a message that can add HTML text to an attachment, HTML inline picture but must use SETHTMLMSG () to send the message content//email.setdebug (TRUE);//whether to turn on debugging by default does not turn on Email.setsslonconnec T (true);//Turn on SSL encryption email.setstarttlsenabled (TRUE);//Turn on TLS encryption//Set SMTP host, here use own QQ mailbox as mail server E        Mail.sethostname (Email.smtphost);        Login mail server username and password (ensure mail server POP3/SMTP service on) email.setauthentication (Email.username, Email.password); Email.setfrom (email.fromemail,email.fromusername);//Sender for (map.entry<string, string> Map: Nameandaddrmap.entryset ()) {//Mapemail.addto (map) that iterates through the user name and the corresponding mailbox address.GetValue (), Map.getkey ());//receiver mailbox and user name}//EMAIL.ADDCC ("[email protected]");//CC//EMAIL.ADDBCC ("[email  Protected], or//Secret CC Email.setcharset (Email.charset);//Set the message's character set to UTF-8 prevent garbled email.setsubject (subject);// Theme Email.sethtmlmsg (htmlcontent);//message content: <font color= ' red ' > Test Simple Mail delivery! </font>/*htmlemail, Imagehtmlemail have Sethtmlmsg () method, and can be directly inline picture, can be engaged in the Internet so complex say no, such as * I test Sina, Sohu, QQ mailbox and so on can show * * */*//If you use Setmsg () to pass the message content, then htmlemail the method URL of the embedded picture          url = new URL ("http://www.jianlimuban.com/picture");          String cid = email.embed (URL, "name"); Email.sethtmlmsg (" Test Simple Mail sending function! </font> "," UTF-8 "); */Email.send ();//Send Mail}}
Test code:
Package Sendemail;import Java.util.map;import Org.junit.test;import Com.google.common.collect.maps;public class emailtest {@Testpublic void Testsendsimpleemail () {//user name and corresponding mailbox map<string,string> nameandaddrmap= Maps.newhashmap ();//Create a new Mapnameandaddrmap.put ("Zhang San", "chen***** @sina. com"); Nameandaddrmap.put ("John Doe", "leixing***** @163.com "), Nameandaddrmap.put (" Pock "," chenxing***** @qq. com "); String htmlcontent= "<font color= ' red ' > Test Simple Mail Send function! </font> ";//message content string subject=" good New Year! ";//Theme or title try {email.sendemail (nameandaddrmap,subject,htmlcontent);//test send mail function} catch (Exception e) { System.out.println ("Mail Send failed! ");//logger.setmessage (E.getmessage ());}}}

reprint Please indicate-java my life (Chen Leixing) Original source: http://blog.csdn.net/chenleixing/article/details/44708533

Finally, seriously read the netizens, the great gods, if there is a feeling I this program ape has a place to say wrong or wrong or you have a good proposal or suggestions or ideas, but also look You kindness alms n seconds to leave your valuable text (message), so that you, I, and the vast number of programs apes grow and Progress faster ....



Java implementation Send mail can be multiple attachments inline picture-commons-email use

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.