欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
  Java实现HtmlEmail邮件发送功能
 
  引言
 
  在平常的企业级应用开发过程中,可能会涉及到一些资讯通知需要传达,以及软件使用过程中有一些安全性的东西需要及早知道和了解,这时候在局域网之间就可以通过发送邮件的方式了。以下就是代码实现了:
 
  1packagecom.sh.xrsite.common.utils;
 
  2
 
  3importjava.io.File;
 
  4importjava.util.HashMap;
 
  5importjava.util.Locale;
 
  6importjava.util.Map;
 
  7importjava.util.regex.Matcher;
 
  8importjava.util.regex.Pattern;
 
  9
 
  10importorg.apache.commons.mail.HtmlEmail;
 
  11importorg.springframework.ui.freemarker.FreeMarkerTemplateUtils;
 
  12
 
  13importfreemarker.template.Configuration;
 
  14importfreemarker.template.Template;
 
  15
 
  16/**
 
  17*发送电子邮件
 
  18*/
 
  19publicclassSendMailUtil{
 
  20
 
  21privatestaticfinalStringfrom="zsq@163.com";
 
  22privatestaticfinalStringfromName="测试公司";
 
  23privatestaticfinalStringcharSet="utf-8";
 
  24privatestaticfinalStringusername="zsq@163.com";
 
  25privatestaticfinalStringpassword="123456";
 
  26
 
  27privatestaticMap<String,String>hostMap=newHashMap<String,String>();
 
  28static{
 
  29//126
 
  30hostMap.put("smtp.126","smtp.126.com");
 
  31//qq
 
  32hostMap.put("smtp.qq","smtp.qq.com");
 
  33
 
  34//163
 
  35hostMap.put("smtp.163","smtp.163.com");
 
  36
 
  37//sina
 
  38hostMap.put("smtp.sina","smtp.sina.com.cn");
 
  39
 
  40//tom
 
  41hostMap.put("smtp.tom","smtp.tom.com");
 
  42
 
  43//263
 
  44hostMap.put("smtp.263","smtp.263.net");
 
  45
 
  46//yahoo
 
  47hostMap.put("smtp.yahoo","smtp.mail.yahoo.com");
 
  48
 
  49//hotmail
 
  50hostMap.put("smtp.hotmail","smtp.live.com");
 
  51
 
  52//gmail
 
  53hostMap.put("smtp.gmail","smtp.gmail.com");
 
  54hostMap.put("smtp.port.gmail","465");
 
  55}
 
  56
 
  57publicstaticStringgetHost(Stringemail)throwsException{
 
  58Patternpattern=Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
 
  59Matchermatcher=pattern.matcher(email);
 
  60Stringkey="unSupportEmail";
 
  61if(matcher.find()){
 
  62key="smtp."+matcher.group(1);
 
  63}
 
  64if(hostMap.containsKey(key)){
 
  65returnhostMap.get(key);
 
  66}else{
 
  67thrownewException("unSupportEmail");
 
  68}
 
  69}
 
  70
 
  71publicstaticintgetSmtpPort(Stringemail)throwsException{
 
  72Patternpattern=Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
 
  73Matchermatcher=pattern.matcher(email);
 
  74Stringkey="unSupportEmail";
 
  75if(matcher.find()){
 
  76key="smtp.port."+matcher.group(1);
 
  77}
 
  78if(hostMap.containsKey(key)){
 
  79returnInteger.parseInt(hostMap.get(key));
 
  80}else{
 
  81return25;
 
  82}
 
  83}
 
  84
 
  85/**
 
  86*发送模板邮件
 
  87*
 
  88*@paramtoMailAddr
 
  89*收信人地址
 
  90*@paramsubject
 
  91*email主题
 
  92*@paramtemplatePath
 
  93*模板地址
 
  94*@parammap
 
  95*模板map
 
  96*/
 
  97publicstaticvoidsendFtlMail(StringtoMailAddr,Stringsubject,
 
  98StringtemplatePath,Map<String,Object>map){
 
  99Templatetemplate=null;
 
  100ConfigurationfreeMarkerConfig=null;
 
  101HtmlEmailhemail=newHtmlEmail();
 
  102try{
 
  103hemail.setHostName(getHost(from));
 
  104hemail.setSmtpPort(getSmtpPort(from));
 
  105hemail.setCharset(charSet);
 
  106hemail.addTo(toMailAddr);
 
  107hemail.setFrom(from,fromName);
 
  108hemail.setAuthentication(username,password);
 
  109hemail.setSubject(subject);
 
  110freeMarkerConfig=newConfiguration();
 
  111freeMarkerConfig.setDirectoryForTemplateLoading(newFile(
 
  112getFilePath()));
 
  113//获取模板
 
  114template=freeMarkerConfig.getTemplate(getFileName(templatePath),
 
  115newLocale("Zh_cn"),"UTF-8");
 
  116//模板内容转换为string
 
  117StringhtmlText=FreeMarkerTemplateUtils
 
  118.processTemplateIntoString(template,map);
 
  119System.out.println(htmlText);
 
  120hemail.setMsg(htmlText);
 
  121hemail.send();
 
  122System.out.println("emailsendtrue!");
 
  123}catch(Exceptione){
 
  124e.printStackTrace();
 
  125System.out.println("emailsenderror!");
 
  126}
 
  127}
 
  128
 
  129/**
 
  130*发送普通邮件
 
  131*
 
  132*@paramtoMailAddr
 
  133*收信人地址
 
  134*@paramsubject
 
  135*email主题
 
  136*@parammessage
 
  137*发送email信息
 
  138*/
 
  139publicstaticvoidsendCommonMail(StringtoMailAddr,Stringsubject,
 
  140Stringmessage){
 
  141HtmlEmailhemail=newHtmlEmail();
 
  142try{
 
  143hemail.setHostName(getHost(from));
 
  144hemail.setSmtpPort(getSmtpPort(from));
 
  145hemail.setCharset(charSet);
 
  146hemail.addTo(toMailAddr);
 
  147hemail.setFrom(from,fromName);
 
  148hemail.setAuthentication(username,password);
 
  149hemail.setSubject(subject);
 
  150hemail.setMsg(message);
 
  151hemail.send();
 
  152System.out.println("emailsendtrue!");
 
  153}catch(Exceptione){
 
  154e.printStackTrace();
 
  155System.out.println("emailsenderror!");
 
  156}
 
  157
 
  158}
 
  159
 
  160
 
  161/**
 
  162*发送普通邮件
 
  163*@paramhostIp邮件服务器地址
 
  164*@paramsendMailAddr发送发邮箱地址
 
  165*@paramsendUserName发送方姓名
 
  166*@paramusername邮箱用户名
 
  167*@parampassword邮箱密码
 
  168*@paramtoMailAddr收信人邮箱地址
 
  169*@paramsubjectemail主题
 
  170*@parammessage发送email信息
 
  171*/
 
  172publicstaticbooleansendCommonMail(StringhostIp,StringsendMailAddr,StringsendUserName,Stringusername,Stringpassword,StringtoMailAddr,Stringsubject,
 
  173Stringmessage){
 
  174HtmlEmailhemail=newHtmlEmail();
 
  175booleanflag;
 
  176try{
 
  177
 
  178hemail.setHostName(hostIp);
 
  179hemail.setSmtpPort(getSmtpPort(sendMailAddr));
 
  180hemail.setCharset(charSet);
 
  181hemail.addTo(toMailAddr);
 
  182hemail.setFrom(sendMailAddr,sendUserName);
 
  183hemail.setAuthentication(username,password);
 
  184hemail.setSubject(subject);
 
  185hemail.setMsg(message);
 
  186hemail.send();
 
  187flag=true;
 
  188System.out.println("emailsendtrue!");
 
  189
 
  190}catch(Exceptione){
 
  191e.printStackTrace();
 
  192flag=false;
 
  193System.out.println("emailsenderror!");
 
  194}
 
  195
 
  196returnflag;
 
  197}
 
  198
 
  199
 
  200
 
  201publicstaticStringgetHtmlText(StringtemplatePath,
 
  202Map<String,Object>map){
 
  203Templatetemplate=null;
 
  204StringhtmlText="";
 
  205try{
 
  206ConfigurationfreeMarkerConfig=null;
 
  207freeMarkerConfig=newConfiguration();
 
  208freeMarkerConfig.setDirectoryForTemplateLoading(newFile(
 
  209getFilePath()));
 
  210//获取模板
 
  211template=freeMarkerConfig.getTemplate(getFileName(templatePath),
 
  212newLocale("Zh_cn"),"UTF-8");
 
  213//模板内容转换为string
 
  214htmlText=FreeMarkerTemplateUtils.processTemplateIntoString(
 
  215template,map);
 
  216System.out.println(htmlText);
 
  217}catch(Exceptione){
 
  218e.printStackTrace();
 
  219}
 
  220returnhtmlText;
 
  221}
 
  222
 
  223privatestaticStringgetFilePath(){
 
  224Stringpath=getAppPath(SendMailUtil.class);
 
  225path=path+File.separator+"mailtemplate"+File.separator;
 
  226path=path.replace("\\","/");
 
  227System.out.println(path);
 
  228returnpath;
 
  229}
 
  230
 
  231privatestaticStringgetFileName(Stringpath){
 
  232path=path.replace("\\","/");
 
  233System.out.println(path);
 
  234returnpath.substring(path.lastIndexOf("/")+1);
 
  235}
 
  236
 
  237//@SuppressWarnings("unchecked")
 
  238publicstaticStringgetAppPath(Class<?>cls){
 
  239//检查用户传入的参数是否为空
 
  240if(cls==null)
 
  241thrownewjava.lang.IllegalArgumentException("参数不能为空!");
 
  242ClassLoaderloader=cls.getClassLoader();
 
  243//获得类的全名,包括包名
 
  244StringclsName=cls.getName()+".class";
 
  245//获得传入参数所在的包
 
  246Packagepack=cls.getPackage();
 
  247Stringpath="";
 
  248//如果不是匿名包,将包名转化为路径
 
  249if(pack!=null){
 
  250StringpackName=pack.getName();
 
  251//此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库
 
  252if(packName.startsWith("java.")||packName.startsWith("javax."))
 
  253thrownewjava.lang.IllegalArgumentException("不要传送系统类!");
 
  254//在类的名称中,去掉包名的部分,获得类的文件名
 
  255clsName=clsName.substring(packName.length()+1);
 
  256//判定包名是否是简单包名,如果是,则直接将包名转换为路径,
 
  257if(packName.indexOf(".")<0)
 
  258path=packName+"/";
 
  259else{//否则按照包名的组成部分,将包名转换为路径
 
  260intstart=0,end=0;
 
  261end=packName.indexOf(".");
 
  262while(end!=-1){
 
  263path=path+packName.substring(start,end)+"/";
 
  264start=end+1;
 
  265end=packName.indexOf(".",start);
 
  266}
 
  267path=path+packName.substring(start)+"/";
 
  268}
 
  269}
 
  270//调用ClassLoader的getResource方法,传入包含路径信息的类文件名
 
  271java.net.URLurl=loader.getResource(path+clsName);
 
  272//从URL对象中获取路径信息
 
  273StringrealPath=url.getPath();
 
  274//去掉路径信息中的协议名"file:"
 
  275intpos=realPath.indexOf("file:");
 
  276if(pos>-1)
 
  277realPath=realPath.substring(pos+5);
 
  278//去掉路径信息最后包含类文件信息的部分,得到类所在的路径
 
  279pos=realPath.indexOf(path+clsName);
 
  280realPath=realPath.substring(0,pos-1);
 
  281//如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名
 
  282if(realPath.endsWith("!"))
 
  283realPath=realPath.substring(0,realPath.lastIndexOf("/"));
 
  284/*------------------------------------------------------------
 
  285ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径
 
  286中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要
 
  287的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的
 
  288中文及空格路径
 
  289-------------------------------------------------------------*/
 
  290try{
 
  291realPath=java.net.URLDecoder.decode(realPath,"utf-8");
 
  292}catch(Exceptione){
 
  293thrownewRuntimeException(e);
 
  294}
 
  295System.out.println("realPath----->"+realPath);
 
  296returnrealPath;
 
  297}
 
  298
 
  299//privatestaticFilegetFile(Stringpath){
 
  300//Filefile=
 
  301//SendMail.class.getClassLoader().getResource("mailtemplate/test.ftl").getFile();
 
  302//returnfile;
 
  303//}
 
  304//
 
  305
 
  306publicstaticvoidmain(String[]args){
 
  307HtmlEmailhemail=newHtmlEmail();
 
  308try{
 
  309hemail.setHostName("smtp.163.com");
 
  310hemail.setCharset("utf-8");
 
  311hemail.addTo("收件邮箱地址");
 
  312hemail.setFrom("发件邮箱地铁","网易");
 
  313hemail.setAuthentication("wang_yi@163.com","发件邮箱密码");
 
  314hemail.setSubject("sendemailtest!");
 
  315hemail.setMsg("<ahref=\"http://www.google.cn\">谷歌</a><br/>");
 
  316hemail.send();
 
  317System.out.println("emailsendtrue!");
 
  318}catch(Exceptione){
 
  319e.printStackTrace();
 
  320System.out.println("emailsenderror!");
 
  321}
 
  322//Map<String,Object>map=newHashMap<String,Object>();
 
  323//map.put("subject","测试标题");
 
  324//map.put("content","测试内容");
 
  325//StringtemplatePath="mailtemplate/test.ftl";
 
  326//sendFtlMail("test@163.com","sendemailtest!",templatePath,map);
 
  327
 
  328//System.out.println(getFileName("mailtemplate/test.ftl"));
 
  329}
 
  330
 
  331}
 
  注意:要想发送邮件还必须在服务器上创建一个邮件服务器和本地安装接收邮件客户端(FoxmailSetup.exe+hMailServer.exe)!

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h56838.shtml