Java htmlemail Send mail tool class

Source: Internet
Author: User
Tags locale

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 SendMailUtil {//PRI    vate static final String smtphost = "192.168.1.70";    Private static final String from = "[email protected]";    private static final String FromName = "test Company";    private static final String CharSet = "Utf-8";    Private static final String username = "[email protected]";    Private static final String password = "123456";    private static map<string, string> Hostmap = new hashmap<string, string> ();        static {//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.live.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 ("\\[email&nbsp        ;p rotected] (\\w+) (\\.\\w+) {")";        Matcher Matcher = pattern.matcher (email);        String key = "Unsupportemail";        if (Matcher.find ()) {key = "smtp." + Matcher.group (1);        } if (Hostmap.containskey (key)) {return hostmap.get (key);        } else {throw new Exception ("Unsupportemail"); }} public static intGetsmtpport (String email) throws Exception {pattern pattern = pattern.compile ("\\[email protected" (\\w+) (\\.\        \w+} ");        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.get (key));        } else {return 25; }}/** * Send template Mail * * @param tomailaddr * Recipient address * @param subject * EMA Il theme * @param templatepath * Template address * @param map * Template Map * */public static void Sendftlmail (string tomailaddr, String subject, String TemplatePath, map<string, object> Map) {Tem        Plate template = null;        Configuration freemarkerconfig = null;        Htmlemail hemail = new Htmlemail ();            try {hemail.sethostname (GetHost (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 ())); Get template templates = Freemarkerconfig.gettemplate (GetFileName (TemplatePath), New Locale ("ZH_CN            ")," UTF-8 "); The template content is converted to string string htmltext = Freemarkertemplateutils. Processtemplateintostring (Templa            TE, 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 regular mail   * * @param TOMAILADDR * Recipient address * @param subject * Email subject * @param message * Send email message */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);            Hemail.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) {Templat    e template = null;    String htmltext = "";            try {Configuration freemarkerconfig = null;            Freemarkerconfig = new Configuration ();            Freemarkerconfig.setdirectoryfortemplateloading (New File (GetFilePath ())); Get template templates = Freemarkerconfig.gettemplate (GetFileName (TemplatePath), New Locale ("ZH_CN            ")," UTF-8 "); Template content converted to string htmltext = freemarkertemplateutils.processtemplateintostring (templates, 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);    return 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 the parameter passed in by the user is empty if (CLS = = null) throw new Java.lang.IllegalArgumentException ("Argument cannot be empty!        ");        ClassLoader loader = Cls.getclassloader ();        Get the full name of the class, including the package name String Clsname = cls.getname () + ". Class";        Obtain the package that contains the passed-in parameter, 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 ();                Here is a simple decision on whether it is a Java base Class library that prevents users from passing in the JDK's built-in class library if (Packname.startswith ("java.") | | packname.startswith ("javax.")) throw new Java.lang.IllegalArgumentException ("Do not transfer the system class!            ");            In the name of the class, remove the part of the package name and get the name of the class Clsname = Clsname.substring (packname.length () + 1); Determines whether the package name is a simple package name, and if so, converts the package name directly to the path, if (Packname.IndexOf (".") < 0) path = packname + "/";                else {//Otherwise, the package name is converted to the path int start = 0, end = 0, as part of the package name;                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, pass in the class filename containing the path information Java.net.URL URL = loader.getresource (path + clsname        );        Gets the path information from the URL object String realpath = Url.getpath ();        Remove the protocol name "file:" int pos = realpath.indexof ("file:") in the path information;        if (pos >-1) realpath = realpath.substring (pos + 5);        Remove the part of the path information that contains the class file information at the end, and get the path of the class pos = realpath.indexof (path + clsname);        Realpath = realpath.substring (0, pos-1); If the class file is packaged in a file such as a jar, remove the package file name if (realPath.endswith ("!"))        Realpath = realpath.substring (0, Realpath.lastindexof ("/"));           /*------------------------------------------------------------ClassLoader GetResource method uses the Utf-8 to encode the path information when the path         In the presence of Chinese and white space, he will convert these characters, so that the resulting is often not the real path we want, here, called the Urldecoder decode method to decode, in order to get the original Chinese and white space 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 =//SendMail.class.getClassLoader (). GetResource ("Mai    LTEMPLATE/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 ("Receiving email address");         Hemail.setfrom ("E-mail Box subway", "NetEase");         Hemail.setauthentication ("[email protected]", "Sender email 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 Contents");//String TemplatePath = "MAILTEMPLATE/TEST.FTL";//Sendftlmail ("[email&nbsp        ;p rotected] "," SendEmail test! ", TemplatePath, map);    System.out.println (GetFileName ("MAILTEMPLATE/TEST.FTL")); }}

  

Java htmlemail Send mail tool class

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.