001package top.cenze.utils;
002
003import freemarker.template.Configuration;
004import freemarker.template.Template;
005import org.apache.commons.mail.HtmlEmail;
006import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
007
008import java.io.File;
009import java.util.HashMap;
010import java.util.Locale;
011import java.util.Map;
012import java.util.regex.Matcher;
013import java.util.regex.Pattern;
014
015/**
016 * 发送电子邮件
017 */
018public class SendMailUtil {
019
020        // private static final String smtphost = "192.168.1.70";
021        private static final String from = "olmysoft_contact@163.com";
022        private static final String fromName = "奥软";
023        private static final String charSet = "utf-8";
024        private static final String username = "olmysoft_contact@163.com";
025        private static final String password = "1qaz2wsx";//授权码
026
027        private static Map<String, String> hostMap = new HashMap<String, String>();
028        static {
029                // 126
030                hostMap.put("smtp.126", "smtp.126.com");
031                // qq
032                hostMap.put("smtp.qq", "smtp.qq.com");
033
034                // 163
035                hostMap.put("smtp.163", "smtp.163.com");
036
037                // sina
038                hostMap.put("smtp.sina", "smtp.sina.com.cn");
039
040                // tom
041                hostMap.put("smtp.tom", "smtp.tom.com");
042
043                // 263
044                hostMap.put("smtp.263", "smtp.263.net");
045
046                // yahoo
047                hostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");
048
049                // hotmail
050                hostMap.put("smtp.hotmail", "smtp.live.com");
051
052                // gmail
053                hostMap.put("smtp.gmail", "smtp.gmail.com");
054                hostMap.put("smtp.port.gmail", "465");
055        }
056
057        public static String getHost(String email) throws Exception {
058                Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
059                Matcher matcher = pattern.matcher(email);
060                String key = "unSupportEmail";
061                if (matcher.find()) {
062                        key = "smtp." + matcher.group(1);
063                }
064                if (hostMap.containsKey(key)) {
065                        return hostMap.get(key);
066                } else {
067                        throw new Exception("unSupportEmail");
068                }
069        }
070
071        public static int getSmtpPort(String email) throws Exception {
072                Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
073                Matcher matcher = pattern.matcher(email);
074                String key = "unSupportEmail";
075                if (matcher.find()) {
076                        key = "smtp.port." + matcher.group(1);
077                }
078                if (hostMap.containsKey(key)) {
079                        return Integer.parseInt(hostMap.get(key));
080                } else {
081                        return 25;
082                }
083        }
084
085        /**
086         * 发送模板邮件
087         * 
088         * @param toMailAddr
089         *            收信人地址
090         * @param subject
091         *            email主题
092         * @param templatePath
093         *            模板地址
094         * @param map
095         *            模板map
096         */
097        public static void sendFtlMail(String toMailAddr, String subject,
098                                   String templatePath, Map<String, Object> map) {
099                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        public static String getHtmlText(String templatePath,
161                                     Map<String, Object> map) {
162                Template template = null;
163                String htmlText = "";
164                try {
165                        Configuration freeMarkerConfig = null;
166                        freeMarkerConfig = new Configuration();
167                        freeMarkerConfig.setDirectoryForTemplateLoading(new File(
168                                        getFilePath()));
169                        // 获取模板
170                        template = freeMarkerConfig.getTemplate(getFileName(templatePath),
171                                        new Locale("Zh_cn"), "UTF-8");
172                        // 模板内容转换为string
173                        htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(
174                                        template, map);
175                        System.out.println(htmlText);
176                } catch (Exception e) {
177                        e.printStackTrace();
178                }
179                return htmlText;
180        }
181
182        private static String getFilePath() {
183                String path = getAppPath(SendMailUtil.class);
184                path = path + File.separator + "mailtemplate" + File.separator;
185                path = path.replace("\\", "/");
186                System.out.println(path);
187                return path;
188        }
189
190        private static String getFileName(String path) {
191                path = path.replace("\\", "/");
192                System.out.println(path);
193                return path.substring(path.lastIndexOf("/") + 1);
194        }
195
196//      @SuppressWarnings("unchecked")
197        public static String getAppPath(Class<?> cls) {
198                // 检查用户传入的参数是否为空
199                if (cls == null) {
200                        throw new IllegalArgumentException("参数不能为空!");
201                }
202                ClassLoader loader = cls.getClassLoader();
203                // 获得类的全名,包括包名
204                String clsName = cls.getName() + ".class";
205                // 获得传入参数所在的包
206                Package pack = cls.getPackage();
207                String path = "";
208                // 如果不是匿名包,将包名转化为路径
209                if (pack != null) {
210                        String packName = pack.getName();
211                        // 此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库
212                        if (packName.startsWith("java.") || packName.startsWith("javax.")) {
213                                throw new IllegalArgumentException("不要传送系统类!");
214                        }
215                        // 在类的名称中,去掉包名的部分,获得类的文件名
216                        clsName = clsName.substring(packName.length() + 1);
217                        // 判定包名是否是简单包名,如果是,则直接将包名转换为路径,
218                        if (packName.indexOf(".") < 0) {
219                                path = packName + "/";
220                        }
221                        else {// 否则按照包名的组成部分,将包名转换为路径
222                                int start = 0, end = 0;
223                                end = packName.indexOf(".");
224                                while (end != -1) {
225                                        path = path + packName.substring(start, end) + "/";
226                                        start = end + 1;
227                                        end = packName.indexOf(".", start);
228                                }
229                                path = path + packName.substring(start) + "/";
230                        }
231                }
232                // 调用ClassLoader的getResource方法,传入包含路径信息的类文件名
233                java.net.URL url = loader.getResource(path + clsName);
234                // 从URL对象中获取路径信息
235                String realPath = url.getPath();
236                // 去掉路径信息中的协议名"file:"
237                int pos = realPath.indexOf("file:");
238                if (pos > -1) {
239                        realPath = realPath.substring(pos + 5);
240                }
241                // 去掉路径信息最后包含类文件信息的部分,得到类所在的路径
242                pos = realPath.indexOf(path + clsName);
243                realPath = realPath.substring(0, pos - 1);
244                // 如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名
245                if (realPath.endsWith("!")) {
246                        realPath = realPath.substring(0, realPath.lastIndexOf("/"));
247                }
248                /*------------------------------------------------------------ 
249                 ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径 
250                  中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要 
251                  的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的 
252                  中文及空格路径 
253                -------------------------------------------------------------*/
254                try {
255                        realPath = java.net.URLDecoder.decode(realPath, "utf-8");
256                } catch (Exception e) {
257                        throw new RuntimeException(e);
258                }
259                System.out.println("realPath----->" + realPath);
260                return realPath;
261        }
262
263        // private static File getFile(String path){
264        // File file =
265        // SendMail.class.getClassLoader().getResource("mailtemplate/test.ftl").getFile();
266        // return file;
267        // }
268        //
269
270//      public static void main(String[] args) {
271//              // HtmlEmail hemail = new HtmlEmail();
272//              // try {
273//              // hemail.setHostName("smtp.exmail.qq.com");
274//              // hemail.setCharset("utf-8");
275//              // hemail.addTo("fly.1206@qq.com");
276//              // hemail.setFrom("zhoujunfeng@et-bank.com", "周俊峰");
277//              // hemail.setAuthentication("zhoujunfeng@et-bank.com", "31415926@aa");
278//              // hemail.setSubject("sendemail test!");
279//              // hemail.setMsg("<a href=\"http://www.google.cn\">谷歌</a><br/>");
280//              // hemail.send();
281//              // System.out.println("email send true!");
282//              // } catch (Exception e) {
283//              // e.printStackTrace();
284//              // System.out.println("email send error!");
285//              // }
286//              Map<String, Object> map = new HashMap<String, Object>();
287//              map.put("subject", "测试标题");
288//              map.put("content", "测试 内容");
289//              String templatePath = "mailtemplate/test.ftl";
290//              sendFtlMail("test@163.com", "sendemail test!", templatePath, map);
291//
292//              // System.out.println(getFileName("mailtemplate/test.ftl"));
293//      }
294
295}