首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

apache commons email 简略使用(二)

2012-09-13 
apache commons email 简单使用(二)将上次发邮件的代码写了个方法简单封装了一下,以满足需求,主要是各邮件

apache commons email 简单使用(二)
    将上次发邮件的代码写了个方法简单封装了一下,以满足需求,主要是各邮件服务商情况不一样,有时候可能会发送不成功现象,为了减少失败的概率,所以试着通过配置多个邮件服务商来按顺序发送邮件,失败了就换一个邮件服务器,成功则立即终止。请看代码:

(一)javabean封装邮件发送相关信息:

package com.basekj.entity;import java.util.ArrayList;/** * 邮件发送信息 * @author * @date 2010-08-18 */public class SendEmailInfoBean {private String emailFromInfo;//private ArrayList<EmailFromInfoBean> emailFromInfo;//邮件发送方基本信息private ArrayList<String> emailTo;//邮件接收方 private ArrayList<String> emailCc;//邮件抄送方private ArrayList<String> emailBcc;//邮件秘密抄送方private String subject; //主题private String sendMsg; //邮件内容//public ArrayList<EmailFromInfoBean> getEmailFromInfo() {//return emailFromInfo;//}//public void setEmailFromInfo(ArrayList<EmailFromInfoBean> emailFromInfo) {//this.emailFromInfo = emailFromInfo;//}public ArrayList<String> getEmailTo() {return emailTo;}public String getEmailFromInfo() {return emailFromInfo;}public void setEmailFromInfo(String emailFromInfo) {this.emailFromInfo = emailFromInfo;}public void setEmailTo(ArrayList<String> emailTo) {this.emailTo = emailTo;}public ArrayList<String> getEmailCc() {return emailCc;}public void setEmailCc(ArrayList<String> emailCc) {this.emailCc = emailCc;}public ArrayList<String> getEmailBcc() {return emailBcc;}public void setEmailBcc(ArrayList<String> emailBcc) {this.emailBcc = emailBcc;}public String getSubject() {return subject;}public void setSubject(String subject) {this.subject = subject;}public String getSendMsg() {return sendMsg;}public void setSendMsg(String sendMsg) {this.sendMsg = sendMsg;}}


(二)发送邮件类:
package com.basekj.business;import java.util.ArrayList;import org.apache.commons.lang.StringUtils;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.commons.mail.DefaultAuthenticator;import org.apache.commons.mail.EmailException;     import org.apache.commons.mail.SimpleEmail;      import com.basekj.entity.SendEmailInfoBean;import com.basekj.exception.BusinessException;import com.basekj.util.ReadProperties;/** *  * @author  * @date 2010-08-17 */ public class BaseEmailSendBiz   {      public BaseEmailSendBiz()      {                }            private static final Log logger = LogFactory.getLog(BaseEmailSendBiz.class);      /**     *      * @param emailInfo     * @return result:false表示发送失败,true表示发送成功!     * @throws BusinessException     */    public static boolean send(SendEmailInfoBean emailInfo) throws BusinessException  {      boolean result = false;    SimpleEmail email = new SimpleEmail();        //email.setDebug(true);        try           {        String emailFromInfo = emailInfo.getEmailFromInfo();        String[] fromArray = emailFromInfo.split("\\{|}");//按{或 } 分解字符串        for(int i=0; i<fromArray.length; i++) {        if(StringUtils.isNotEmpty(fromArray[i])) {        String[] from = fromArray[i].split(",");        email.setHostName(from[0]); //发送方邮件服务器            email.setFrom(from[1]); // 发送方地址            email.setAuthenticator(new DefaultAuthenticator(from[2],from[3]));            if("1".equals(from[4])) {            email.setTLS(true);//是否TLS校验,,某些邮箱需要TLS安全校验,同理有SSL校验            }            if("1".equals(from[5])) {            email.setSSL(true);              }            ArrayList<String> emailTo = emailInfo.getEmailTo();            ArrayList<String> emailCc = emailInfo.getEmailCc();            ArrayList<String> emailBcc = emailInfo.getEmailBcc();            for(int j=0; j<emailTo.size(); j++) {            email.addTo(emailTo.get(j)); // 接收方            }            for(int j=0; emailCc!=null&&j<emailCc.size(); j++) {            email.addCc(emailCc.get(j)); // 抄送方            }            for(int j=0; emailBcc!=null&&j<emailBcc.size(); j++) {            email.addBcc(emailBcc.get(j)); // 秘密抄送方            }    email.setCharset("GB2312");// 编码    email.setSubject(emailInfo.getSubject()); // 标题    email.setMsg(emailInfo.getSendMsg()); // 内容    String emailResult = email.send();    System.out.println("用"+from[1]+"邮箱来发送,发送结果:"+emailResult);    if(!StringUtils.equals("failed",emailResult)) {    return true;    }else {    email = null;    email = new SimpleEmail();    continue;    }        }                }        } catch (EmailException e) {          result = false;        if(logger.isErrorEnabled()){logger.error("发送邮件出错!");}throw new BusinessException(e.getMessage());        }         return result;    }          public static void main(String[] args)      {    ReadProperties property = new ReadProperties();    SendEmailInfoBean emailInfo = new SendEmailInfoBean();    emailInfo.setEmailFromInfo(property.readData("email_info"));    ArrayList<String> a = new ArrayList<String>();    a.add("******@qq.com");    a.add("xxx@163.com");    emailInfo.setEmailTo(a);    emailInfo.setSubject("请查收");    emailInfo.setSendMsg("这个是java程序发送邮件测试的");    try {    System.out.println("开始发送:");boolean result = send(emailInfo);System.out.println("发送结果:" + result);} catch (BusinessException e) {e.printStackTrace();}    }  }

注意:邮件发送地址是从配置文件里读取的,见后面代码介绍,我稍微改了下apache commons email 源代码,因为里面那个send方法初始化邮件信息和发送邮件会抛异常,初始化失败抛异常倒可以接受,但是因为我可能需要换个服务器重新发送,让它抛异常就不太好处理了,我想让它在某次发送失败后,继续换个发送地址重新发送,所以我将源代码里Email类的send方法,发送失败时给予返回值“failed”,代码如下:
/**     * Sends the previously created MimeMessage to the SMTP server.     *     * @return the message id of the underlying MimeMessage     * @throws EmailException the sending failed     */    public String sendMimeMessage()    {        EmailUtils.notNull(this.message, "message");        try        {            Transport.send(this.message);            return this.message.getMessageID();        }        catch (Throwable t)        {            String msg = "Sending the email to the following server failed : "                + this.getHostName()                + ":"                + this.getSmtpPort();            return "failed";        }    }


(三)读取配置文件类:
package com.basekj.util;import java.io.IOException;import java.io.InputStream;import java.util.Properties;import org.apache.commons.lang.StringUtils;/** * 读取配置文件 *  * @author  * */public class ReadProperties {/** * 读取配置文件参数 * 传入参数名,当读取错误或无 * 对应参数键值对时,返回空字符串。 * @param key * @return result */public String readData(String key) {InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("system_parameter.properties");Properties p = new Properties();String result = "";try {p.load(inputStream);} catch (Exception e1) {e1.printStackTrace();return result;} finally {if(null != inputStream)try {inputStream.close();} catch (IOException e) {e.printStackTrace();return result;}}result = p.getProperty(key);return StringUtils.isEmpty(result)?"":result;}public static void main(String[] args) {// TODO Auto-generated method stubString s = new ReadProperties().readData("email_info");String [] arr = s.split("\\{|}");for(String r:arr) {if(r != null && r.length() > 0) {System.out.println(r);}}}}

(四)静态配置文件system_parameter.properties(这里配置了2个服务器)
#6 parameters:1:email hostname,2:email from address,3:email username,4:email password,5:if tls(1:yes,0:no),6:if ssl(1:yes,0:no)#--------------------以上是注释-------------------------------------email_info={smtp.sina.com,test1@sina.cn,test1@sina.cn,pwd1,0,0}{smtp.163.com,test2@163.com,test2@163.com,pwd2,0,0}




   

热点排行