Java 實現 HtmlEmail 郵件發送功能

引言html

     在日常的企業級應用開發過程當中,可能會涉及到一些資訊通知須要傳達,以及軟件使用過程當中有一些安全性的東西須要及早知道和了解,這時候在局域網之間就能夠經過發送郵件的方式了。如下就是代碼實現了: java

  1 package com.sh.xrsite.common.utils;
  2  
  3 import java.io.File;
  4 import java.util.HashMap;
  5 import java.util.Locale;
  6 import java.util.Map;
  7 import java.util.regex.Matcher;
  8 import java.util.regex.Pattern;
  9  
 10 import org.apache.commons.mail.HtmlEmail;
 11 import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
 12  
 13 import freemarker.template.Configuration;
 14 import freemarker.template.Template;
 15  
 16 /**
 17  * 發送電子郵件
 18  */
 19 public class SendMailUtil {
 20  
 21     private static final String from = "zsq@163.com";
 22     private static final String fromName = "測試公司";
 23     private static final String charSet = "utf-8";
 24     private static final String username = "zsq@163.com";
 25     private static final String password = "123456";
 26  
 27     private static Map<String, String> hostMap = new HashMap<String, String>();
 28     static {
 29         // 126
 30         hostMap.put("smtp.126", "smtp.126.com");
 31         // qq
 32         hostMap.put("smtp.qq", "smtp.qq.com");
 33  
 34         // 163
 35         hostMap.put("smtp.163", "smtp.163.com");
 36  
 37         // sina
 38         hostMap.put("smtp.sina", "smtp.sina.com.cn");
 39  
 40         // tom
 41         hostMap.put("smtp.tom", "smtp.tom.com");
 42  
 43         // 263
 44         hostMap.put("smtp.263", "smtp.263.net");
 45  
 46         // yahoo
 47         hostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");
 48  
 49         // hotmail
 50         hostMap.put("smtp.hotmail", "smtp.live.com");
 51  
 52         // gmail
 53         hostMap.put("smtp.gmail", "smtp.gmail.com");
 54         hostMap.put("smtp.port.gmail", "465");
 55     }
 56  
 57     public static String getHost(String email) throws Exception {
 58         Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
 59         Matcher matcher = pattern.matcher(email);
 60         String key = "unSupportEmail";
 61         if (matcher.find()) {
 62             key = "smtp." + matcher.group(1);
 63         }
 64         if (hostMap.containsKey(key)) {
 65             return hostMap.get(key);
 66         } else {
 67             throw new Exception("unSupportEmail");
 68         }
 69     }
 70  
 71     public static int getSmtpPort(String email) throws Exception {
 72         Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
 73         Matcher matcher = pattern.matcher(email);
 74         String key = "unSupportEmail";
 75         if (matcher.find()) {
 76             key = "smtp.port." + matcher.group(1);
 77         }
 78         if (hostMap.containsKey(key)) {
 79             return Integer.parseInt(hostMap.get(key));
 80         } else {
 81             return 25;
 82         }
 83     }
 84  
 85     /**
 86      * 發送模板郵件
 87      *
 88      * @param toMailAddr
 89      *            收信人地址
 90      * @param subject
 91      *            email主題
 92      * @param templatePath
 93      *            模板地址
 94      * @param map
 95      *            模板map
 96      */
 97     public static void sendFtlMail(String toMailAddr, String subject,
 98             String templatePath, Map<String, Object> map) {
 99         Template template = null;
100         Configuration freeMarkerConfig = null;
101         HtmlEmail hemail = new HtmlEmail();
102         try {
103             hemail.setHostName(getHost(from));
104             hemail.setSmtpPort(getSmtpPort(from));
105             hemail.setCharset(charSet);
106             hemail.addTo(toMailAddr);
107             hemail.setFrom(from, fromName);
108             hemail.setAuthentication(username, password);
109             hemail.setSubject(subject);
110             freeMarkerConfig = new Configuration();
111             freeMarkerConfig.setDirectoryForTemplateLoading(new File(
112                     getFilePath()));
113             // 獲取模板
114             template = freeMarkerConfig.getTemplate(getFileName(templatePath),
115                     new Locale("Zh_cn"), "UTF-8");
116             // 模板內容轉換爲string
117             String htmlText = FreeMarkerTemplateUtils
118                     .processTemplateIntoString(template, map);
119             System.out.println(htmlText);
120             hemail.setMsg(htmlText);
121             hemail.send();
122             System.out.println("email send true!");
123         } catch (Exception e) {
124             e.printStackTrace();
125             System.out.println("email send error!");
126         }
127     }
128  
129     /**
130      * 發送普通郵件
131      *
132      * @param toMailAddr
133      *            收信人地址
134      * @param subject
135      *            email主題
136      * @param message
137      *            發送email信息
138      */
139     public static void sendCommonMail(String toMailAddr, String subject,
140             String message) {
141         HtmlEmail hemail = new HtmlEmail();
142         try {
143             hemail.setHostName(getHost(from));
144             hemail.setSmtpPort(getSmtpPort(from));
145             hemail.setCharset(charSet);
146             hemail.addTo(toMailAddr);
147             hemail.setFrom(from, fromName);
148             hemail.setAuthentication(username, password);
149             hemail.setSubject(subject);
150             hemail.setMsg(message);
151             hemail.send();
152             System.out.println("email send true!");
153         } catch (Exception e) {
154             e.printStackTrace();
155             System.out.println("email send error!");
156         }
157  
158     }
159 
160     
161      /**
162      * 發送普通郵件
163      * @param hostIp    郵件服務器地址
164      * @param sendMailAddr  發送發郵箱地址
165      * @param sendUserName 發送方姓名
166      * @param username  郵箱用戶名
167      * @param password  郵箱密碼
168      * @param  toMailAddr  收信人郵箱地址                 
169      * @param  subject  email主題
170      * @param  message  發送email信息         
171      */
172     public static boolean sendCommonMail(String hostIp, String sendMailAddr, String sendUserName, String username, String password,String toMailAddr, String subject,
173             String message) {
174         HtmlEmail hemail = new HtmlEmail();
175         boolean flag;
176         try {
177           
178             hemail.setHostName(hostIp);
179             hemail.setSmtpPort(getSmtpPort(sendMailAddr));
180             hemail.setCharset(charSet);
181             hemail.addTo(toMailAddr);
182             hemail.setFrom(sendMailAddr, sendUserName);
183             hemail.setAuthentication(username, password);
184             hemail.setSubject(subject);
185             hemail.setMsg(message);
186             hemail.send();
187             flag=true;
188             System.out.println("email send true!");
189           
190         } catch (Exception e) {
191             e.printStackTrace();
192             flag=false;
193             System.out.println("email send error!");
194         }
195         
196        return flag;
197     }
198  
199     
200  
201     public static String getHtmlText(String templatePath,
202             Map<String, Object> map) {
203         Template template = null;
204         String htmlText = "";
205         try {
206             Configuration freeMarkerConfig = null;
207             freeMarkerConfig = new Configuration();
208             freeMarkerConfig.setDirectoryForTemplateLoading(new File(
209                     getFilePath()));
210             // 獲取模板
211             template = freeMarkerConfig.getTemplate(getFileName(templatePath),
212                     new Locale("Zh_cn"), "UTF-8");
213             // 模板內容轉換爲string
214             htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(
215                     template, map);
216             System.out.println(htmlText);
217         } catch (Exception e) {
218             e.printStackTrace();
219         }
220         return htmlText;
221     }
222  
223     private static String getFilePath() {
224         String path = getAppPath(SendMailUtil.class);
225         path = path + File.separator + "mailtemplate" + File.separator;
226         path = path.replace("\\", "/");
227         System.out.println(path);
228         return path;
229     }
230  
231     private static String getFileName(String path) {
232         path = path.replace("\\", "/");
233         System.out.println(path);
234         return path.substring(path.lastIndexOf("/") + 1);
235     }
236  
237     // @SuppressWarnings("unchecked")
238     public static String getAppPath(Class<?> cls) {
239         // 檢查用戶傳入的參數是否爲空
240         if (cls == null)
241             throw new java.lang.IllegalArgumentException("參數不能爲空!");
242         ClassLoader loader = cls.getClassLoader();
243         // 得到類的全名,包括包名
244         String clsName = cls.getName() + ".class";
245         // 得到傳入參數所在的包
246         Package pack = cls.getPackage();
247         String path = "";
248         // 若是不是匿名包,將包名轉化爲路徑
249         if (pack != null) {
250             String packName = pack.getName();
251             // 此處簡單斷定是不是Java基礎類庫,防止用戶傳入JDK內置的類庫
252             if (packName.startsWith("java.") || packName.startsWith("javax."))
253                 throw new java.lang.IllegalArgumentException("不要傳送系統類!");
254             // 在類的名稱中,去掉包名的部分,得到類的文件名
255             clsName = clsName.substring(packName.length() + 1);
256             // 斷定包名是不是簡單包名,若是是,則直接將包名轉換爲路徑,
257             if (packName.indexOf(".") < 0)
258                 path = packName + "/";
259             else {// 不然按照包名的組成部分,將包名轉換爲路徑
260                 int start = 0, end = 0;
261                 end = packName.indexOf(".");
262                 while (end != -1) {
263                     path = path + packName.substring(start, end) + "/";
264                     start = end + 1;
265                     end = packName.indexOf(".", start);
266                 }
267                 path = path + packName.substring(start) + "/";
268             }
269         }
270         // 調用ClassLoader的getResource方法,傳入包含路徑信息的類文件名
271         java.net.URL url = loader.getResource(path + clsName);
272         // 從URL對象中獲取路徑信息
273         String realPath = url.getPath();
274         // 去掉路徑信息中的協議名"file:"
275         int pos = realPath.indexOf("file:");
276         if (pos > -1)
277             realPath = realPath.substring(pos + 5);
278         // 去掉路徑信息最後包含類文件信息的部分,獲得類所在的路徑
279         pos = realPath.indexOf(path + clsName);
280         realPath = realPath.substring(0, pos - 1);
281         // 若是類文件被打包到JAR等文件中時,去掉對應的JAR等打包文件名
282         if (realPath.endsWith("!"))
283             realPath = realPath.substring(0, realPath.lastIndexOf("/"));
284         /*------------------------------------------------------------
285          ClassLoader的getResource方法使用了utf-8對路徑信息進行了編碼,當路徑
286           中存在中文和空格時,他會對這些字符進行轉換,這樣,獲得的每每不是咱們想要
287           的真實路徑,在此,調用了URLDecoder的decode方法進行解碼,以便獲得原始的
288           中文及空格路徑
289         -------------------------------------------------------------*/
290         try {
291             realPath = java.net.URLDecoder.decode(realPath, "utf-8");
292         } catch (Exception e) {
293             throw new RuntimeException(e);
294         }
295         System.out.println("realPath----->" + realPath);
296         return realPath;
297     }
298  
299     // private static File getFile(String path){
300     // File file =
301     // SendMail.class.getClassLoader().getResource("mailtemplate/test.ftl").getFile();
302     // return file;
303     // }
304     //
305  
306     public static void main(String[] args) {
307          HtmlEmail hemail = new HtmlEmail();
308          try {
309          hemail.setHostName("smtp.163.com");
310          hemail.setCharset("utf-8");
311          hemail.addTo("收件郵箱地址");
312          hemail.setFrom("發件郵箱地鐵", "網易");
313          hemail.setAuthentication("wang_yi@163.com", "發件郵箱密碼");
314          hemail.setSubject("sendemail test!");
315          hemail.setMsg("<a href=\"http://www.google.cn\">谷歌</a><br/>");
316          hemail.send();
317          System.out.println("email send true!");
318          } catch (Exception e) {
319          e.printStackTrace();
320          System.out.println("email send error!");
321          }
322 //        Map<String, Object> map = new HashMap<String, Object>();
323 //        map.put("subject", "測試標題");
324 //        map.put("content", "測試 內容");
325 //        String templatePath = "mailtemplate/test.ftl";
326 //        sendFtlMail("test@163.com", "sendemail test!", templatePath, map);
327  
328         // System.out.println(getFileName("mailtemplate/test.ftl"));
329     }
330  
331 }

    注意:要想發送郵件還必須在服務器上建立一個郵件服務器和本地安裝接收郵件客戶端 (FoxmailSetup.exe + hMailServer.exe)!spring

    具體的安裝和配置參考http://www.javashuo.com/article/p-nviqvnxb-cu.htmlapache

相關文章
相關標籤/搜索