Java HtmlEmail and htmlemail tools

Source: Internet
Author: User

Java HtmlEmail and htmlemail tools

Package com. sh. xrsite. common. utils; import java. io. file; import java. util. hashMap; import java. util. locale; import java. util. map; import java. util. regex. matcher; import java. util. regex. pattern; import org. apache. commons. mail. htmlEmail; import org. springframework. ui. freemarker. freeMarkerTemplateUtils; import freemarker. template. configuration; import freemarker. template. template;/*** send email */public class Sen DMailUtil {// private static final String smtphost = "192.168.1.70"; private static final String from = "test@163.com"; private static final String fromName = "test Company "; private static final String charSet = "UTF-8"; private static final String username = "home@163.com"; private static final String password = "123456"; private static Map <String, string> hostMap = new HashMap <String, String> (); stati C {// 126 hostMap. put ("smtp.126", "smtp.126.com"); // qq hostMap. put ("smtp. qq "," smtp.qq.com "); // 163 hostMap. put ("smtp.163", "smtp.163.com"); // sina hostMap. put ("smtp. sina "," smtp.sina.com.cn "); // tom hostMap. put ("smtp. tom "," smtp.tom.com "); // 263 hostMap. put ("smtp.263", "smtp.263.net"); // yahoo hostMap. put ("smtp. yahoo "," smtp.mail.yahoo.com "); // hotmail hostMap. put ("smtp. hotmail "," smtp. l Ive.com "); // gmail hostMap. put ("smtp. gmail "," smtp.gmail.com "); hostMap. put ("smtp. port. gmail "," 465 ");} public static String getHost (String email) throws Exception {Pattern pattern = Pattern. compile ("\ w + @ (\ w + )(\\. \ w +) {1, 2} "); Matcher matcher = pattern. matcher (email); String key = "unSupportEmail"; if (matcher. find () {key = "smtp. "+ matcher. group (1);} if (hostMap. containsKey (key) {retur N hostMap. get (key) ;}else {throw new Exception ("unSupportEmail") ;}} public static int getSmtpPort (String email) throws Exception {Pattern pattern = Pattern. compile ("\ w + @ (\ w + )(\\. \ w +) {1, 2} "); Matcher matcher = pattern. matcher (email); String key = "unSupportEmail"; if (matcher. find () {key = "smtp. port. "+ matcher. group (1);} if (hostMap. containsKey (key) {return Integer. parseInt (hostMap. g Et (key) ;}else {return 25 ;}} /*** send template email ** @ param toMailAddr * Recipient address * @ param subject * email subject * @ param templatePath * template address * @ param map * template map */public static void sendFtlMail (String toMailAddr, string subject, String templatePath, Map <String, Object> map) {Template template = null; Configuration freeMarkerConfig = null; HtmlEmail hemail = new HtmlEmail (); try {hemail. setHostName (get Host (from); hemail. setSmtpPort (getSmtpPort (from); hemail. setCharset (charSet); hemail. addTo (toMailAddr); hemail. setFrom (from, fromName); hemail. setAuthentication (username, password); hemail. setSubject (subject); freeMarkerConfig = new Configuration (); freeMarkerConfig. setDirectoryForTemplateLoading (new File (getFilePath (); // obtain the template = freeMarkerConfig. getTemplate (getFileName (templatePath), New Locale ("Zh_cn"), "UTF-8"); // The template content is converted to string String htmlText = FreeMarkerTemplateUtils. processtemplateworkflow string (template, map); System. out. println (htmlText); hemail. setMsg (htmlText); hemail. send (); System. out. println ("email send true! ");} Catch (Exception e) {e. printStackTrace (); System. out. println (" email send error! ");}} /*** Send a common email ** @ param toMailAddr * recipient's address * @ param subject * email subject * @ param message * Send email information */public static void sendCommonMail (String toMailAddr, string subject, String message) {HtmlEmail hemail = new HtmlEmail (); try {hemail. setHostName (getHost (from); hemail. setSmtpPort (getSmtpPort (from); hemail. setCharset (charSet); hemail. addTo (toMailAddr); hemail. setFrom (from, fromName); he Mail. setAuthentication (username, password); hemail. setSubject (subject); hemail. setMsg (message); hemail. send (); System. out. println ("email send true! ");} Catch (Exception e) {e. printStackTrace (); System. out. println (" email send error! ") ;}} Public static String getHtmlText (String templatePath, Map <String, Object> map) {Template template = null; String htmlText =" "; try {Configuration freeMarkerConfig = null; freeMarkerConfig = new Configuration (); freeMarkerConfig. setDirectoryForTemplateLoading (new File (getFilePath (); // obtain the template = freeMarkerConfig. getTemplate (getFileName (templatePath), new Locale ("Zh_cn"), "UTF-8 "); // The template content is converted to string htmlText = FreeMarkerTemplateUtils. processtemplateworkflow string (template, map); System. out. println (htmlText);} catch (Exception e) {e. printStackTrace ();} return htmlText;} private static String getFilePath () {String path = getAppPath (SendMailUtil. class); path = path + File. separator + "mailtemplate" + File. separator; path = path. replace ("\", "/"); System. out. println (path); r Eturn path;} private static String getFileName (String path) {path = path. replace ("\", "/"); System. out. println (path); return path. substring (path. lastIndexOf ("/") + 1);} // @ SuppressWarnings ("unchecked") public static String getAppPath (Class <?> Cls) {// check whether user-passed parameters are null if (cls = null) throw new java. lang. IllegalArgumentException ("the parameter cannot be blank! "); ClassLoader loader = cls. getClassLoader (); // obtain the full name of the class, including the package name String clsName = cls. getName () + ". class "; // Package pack = cls. getPackage (); String path = ""; // if it is not an anonymous package, convert the package name to the path if (pack! = Null) {String packName = pack. getName (); // determine whether it is a Java base class library. This prevents users from passing in the JDK built-in class library if (packName. startsWith ("java. ") | packName. startsWith ("javax. ") throw new java. lang. illegalArgumentException ("do not transfer the system class! "); // In the class name, remove the package name and obtain the class name clsName = clsName. substring (packName. length () + 1); // determines whether the package name is a simple package name. if yes, the package name is directly converted to the path, if (packName. indexOf (". ") <0) path = packName +"/"; else {// otherwise, convert the package name to the path int start = 0, end = 0 according to the package name component; end = packName. indexOf (". "); while (end! =-1) {path = path + packName. substring (start, end) + "/"; start = end + 1; end = packName. indexOf (". ", start);} path = path + packName. substring (start) + "/" ;}// call the getResource method of ClassLoader and pass in the class file name containing path information java.net. URL url = loader. getResource (path + clsName); // obtain the path information from the URL object String realPath = url. getPath (); // remove the protocol name "file:" int pos = realPath. indexOf ("file:"); if (pos>-1) realPath = r EalPath. substring (pos + 5); // remove the path information that finally contains the class file information and obtain the class path pos = realPath. indexOf (path + clsName); realPath = realPath. substring (0, pos-1); // if the class file is packaged into a JAR or other file, remove the corresponding JAR and other packaging file names if (realPath. endsWith ("! ") RealPath = realPath. substring (0, realPath. lastIndexOf ("/");/* ---------------------------------------------------------- the getResource method of ClassLoader uses UTF-8 to encode the path information. When the path contains Chinese characters and spaces, he will convert these characters. In this way, we do not often get the actual path we want. Here, we call the decode method of URLDecoder for decoding, in order to obtain the original path ------------------------------------------------------------- */try {realPath = java.net. URLDecoder. decode (realPath, "UTF-8");} catch (Exception e) {throw new RuntimeException (e);} System. out. println ("realPath ----->" + realPath); return realPath;} // private static File getFile (String path) {// File file File = // SendMail. class. getClassLoader (). getResource ("mailtemplate/test. ftl "). getFile (); // return file; //} // public static void main (String [] args) {HtmlEmail hemail = new HtmlEmail (); try {hemail. setHostName ("smtp.163.com" ); Hemail. setCharset ("UTF-8"); hemail. addTo ("email address"); hemail. setFrom ("sender mail subway", "Netease"); hemail. setAuthentication ("wang_yi@163.com", "sender password"); hemail. setSubject ("sendemail test! "); Hemail. setMsg ("<a href = \" http://www.google.cn \ "> Google </a> <br/>"); hemail. send (); System. out. println ("email send true! ");} Catch (Exception e) {e. printStackTrace (); System. out. println (" email send error! ") ;}// Map <String, Object> map = new HashMap <String, Object> (); // map. put ("subject", "test title"); // map. put ("content", "test content"); // String templatePath = "mailtemplate/test. ftl "; // sendFtlMail (" test@163.com "," sendemail test! ", TemplatePath, map); // System. out. println (getFileName (" mailtemplate/test. ftl "));}}

  

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.