Java Mail EJB3.0组件(POP Support)

Java Mail EJB3.0组件(POP Support)
该组件实现分为以下及部分:MailComponent(EJB3.0邮件组件接口),MailComponentBean(EJB3.0邮件组件实现),MailConfigureCacheEntity(邮件配置缓存实体),PopMainSendComponentBean(POP Mail Send Implement),JNDI_Configure.properties(缓存EJB组件配置),PopMailConfigure.properties(POP邮件配置属性文件),MailMessageBean(邮件异步发送MDB)
/*
 * MailComponent.java
 * Copyright (C) 2009  <JustinLei@gmail.com>
 *
 *        This program is free software; you can redistribute it and/or modify
 *        it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *     (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *        GNU General Public License for more details.
 *
 
*/
package  org.lambdasoft.components.mail;

import  org.lambdasoft.components.mail.param.MailSendParam;
import  org.lambdasoft.exception.MailException;

/**
 * 
 * 
@author  lei.tang (justinlei@gmail.com)
 * @date 2009-8-18
 * 
@version  1.0
 
*/
public   interface  MailComponent {
    
    
/**
     * 发送邮件
     * 
     * 
@param  mailSendParam
     * 
@throws  MailException
     
*/
    
void  send(MailSendParam mailSendParam)  throws  MailException;
    
    
/**
     * 邮件默认发送
     * 
@param  mailSendParam
     * 
@throws  MailException
     
*/
    
void  sendDefaultMail(MailSendParam mailSendParam)  throws  MailException;
    
    
/**
     * 发送邮件
     * 
     * 
@param  mailSendParam
     * 
@throws  MailException
     
*/
    
void  send(MailSendParam[] mailSendParams)  throws  MailException;
    
}

/*
 * MailComponentbean.java
 * Copyright (C) 2009  <JustinLei@gmail.com>
 *
 *        This program is free software; you can redistribute it and/or modify
 *        it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *     (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *        GNU General Public License for more details.
 *
 
*/
package  org.lambdasoft.components.mail.ejb;

import  java.util.Map;

import  javax.annotation.PostConstruct;
import  javax.ejb.Remote;
import  javax.ejb.Stateless;
import  javax.jms.QueueSession;

import  org.lambdasoft.components.cache.CacheComponent;
import  org.lambdasoft.components.log.LogComponent;
import  org.lambdasoft.components.mail.MailComponent;
import  org.lambdasoft.components.mail.param.MailSendParam;
import  org.lambdasoft.components.mail.param.MailSendType;
import  org.lambdasoft.exception.MailException;
import  org.lambdasoft.utils.EJBUtil;
import  org.lambdasoft.utils.FileUtil;

/**
 * 非SSL认证的SMTP邮件服务器发送
 * 
 * 
@author  lei.tang (justinlei@gmail.com)
 * @date 2009-8-25
 * 
@version  1.0
 
*/
@Stateless
@Remote
public   class  MailComponentBean  implements  MailComponent {
    
private  CacheComponent cacheComponent;
    
    
public   void  send(MailSendParam mailSendParam)  throws  MailException {
        
try  {
            EJBUtil.getUtil(MailComponentBean.
class ).messageSend(LogComponent.DESTINATION_MAIL, QueueSession.AUTO_ACKNOWLEDGE, mailSendParam);
        } 
catch  (Exception e) {}
    }

    
public   void  send(MailSendParam[] mailSendParams)  throws  MailException {
        
try  {
            EJBUtil.getUtil(MailComponentBean.
class ).messageSend(LogComponent.DESTINATION_MAIL, QueueSession.AUTO_ACKNOWLEDGE, mailSendParams);
        } 
catch  (Exception e) {}
    }
    
    
public   void  sendDefaultMail(MailSendParam mailSendParam)
            
throws  MailException {
        MailConfigureCacheEntity cacheEntity 
=  (MailConfigureCacheEntity) cacheComponent
                .get(
new  MailConfigureCacheEntity().getKey());
        MailSendParam sendParam 
=  (MailSendParam)cacheEntity.getEntity();
        sendParam.setContent(mailSendParam.getContent());
        sendParam.setSubject(mailSendParam.getSubject());
        sendParam.setTo(mailSendParam.getTo());
        send(sendParam);
    }

    @PostConstruct
    
public   void  initialBean() {
        cacheComponent 
=  (CacheComponent) EJBUtil.getUtil(MailComponentBean. class ).getRemoteEJB(
                
" CacheMemcachedComponentBean/remote " );
        String rootPath 
=   " /org/lambdasoft/components/mail/ejb/PopMailConfigure.properties " ;
        
try  {
            Map
< String, String >  mailConfigure  =  FileUtil.getPropertiesMap(MailComponentBean. class , rootPath);
            MailSendParam mailSendParam 
=   new  MailSendParam();
            mailSendParam.setFrom(mailConfigure.get(
" MAIL.USER.FROM " ));
            mailSendParam.setMailSendType(MailSendType.POP3);
            mailSendParam.setSmtpHost(mailConfigure.get(
" MAIL.SERVER.HOST " ));
            mailSendParam.setSmtpPasswd(mailConfigure.get(
" MAIL.USER.PASSWORD " ));
            mailSendParam.setSmtpUser(mailConfigure.get(
" MAIL.USER.SMTP " ));
            MailConfigureCacheEntity cacheEntity 
=   new  MailConfigureCacheEntity(mailSendParam);
            cacheComponent.add(cacheEntity);
        } 
catch  (Exception e) {
            
return ;
        }
    }
}


/*
 * MailConfigureCacheEntity.java
 * Copyright (C) 2009  <JustinLei@gmail.com>
 *
 *        This program is free software; you can redistribute it and/or modify
 *        it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *     (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *        GNU General Public License for more details.
 *
 
*/
package  org.lambdasoft.components.mail.ejb;

import  org.lambdasoft.components.cache.CacheEntity;
import  org.lambdasoft.components.mail.param.MailSendParam;
import  org.lambdasoft.exception.CacheException;

/**
 * 
@author  lei.tang (justinlei@gmail.com)
 * @date 
 * 
@version
 
*/
public   class  MailConfigureCacheEntity  implements  CacheEntity{
    
private   static   final   long  serialVersionUID  =   1L ;
    
private  MailSendParam mailSendParam;
    
    
public  MailConfigureCacheEntity() {
    }
    
    
public  MailConfigureCacheEntity(MailSendParam mailSendParam) {
        
this .mailSendParam  =  mailSendParam;
    }
    
    
public   void  check()  throws  CacheException {
        
//  TODO Auto-generated method stub
    }
    
    
public   void  setEntity(MailSendParam mailSendParam) {
        
this .mailSendParam  =  mailSendParam;
    }

    
public  Object getEntity() {
        
return  mailSendParam;
    }

    
public  String getKey() {
        
return   " CACHE.MAIL.SEND.CONFIGURE " ;
    }

    
public   void  setEntity(Object obj) {
        
this .mailSendParam  =  (MailSendParam)obj;
    }

    
public   void  setKey(String key) {
        
return ;
    }
}


/*
 * PopMainSendComponentBean.java
 * Copyright (C) 2009  <JustinLei@gmail.com>
 *
 *        This program is free software; you can redistribute it and/or modify
 *        it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *     (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *        GNU General Public License for more details.
 *
 
*/
package  org.lambdasoft.components.mail.ejb;

import  java.util.Date;
import  java.util.Enumeration;
import  java.util.Properties;

import  javax.activation.DataHandler;
import  javax.activation.FileDataSource;
import  javax.ejb.Local;
import  javax.ejb.Stateless;
import  javax.mail.Authenticator;
import  javax.mail.Message;
import  javax.mail.MessagingException;
import  javax.mail.Multipart;
import  javax.mail.PasswordAuthentication;
import  javax.mail.Session;
import  javax.mail.Transport;
import  javax.mail.internet.InternetAddress;
import  javax.mail.internet.MimeBodyPart;
import  javax.mail.internet.MimeMessage;
import  javax.mail.internet.MimeMultipart;
import  javax.mail.internet.MimeUtility;

import  org.lambdasoft.components.mail.MailComponent;
import  org.lambdasoft.components.mail.param.MailSendParam;
import  org.lambdasoft.exception.MailException;

/**
 * 
 * 
@author  lei.tang (justinlei@gmail.com)
 * @date 2009-8-25
 * 
@version  1.0
 
*/
@Stateless
@Local
public   class  PopMainSendComponentBean  implements  MailComponent {
    
public   void  send(MailSendParam mailSendParam)  throws  MailException {
        Session session 
=  getSession(mailSendParam);
        
// 发送邮件
         try  {
            Transport.send(getMessage(mailSendParam, session));
            System.out.println(
" 邮件发送成功 ! " );
        } 
catch  (MessagingException e) {
            
throw   new  MailException( " 邮件发送失败:  "   +  e);
        }
    }

    
public   void  send(MailSendParam[] mailSendParams)  throws  MailException {
        
    }
    
    
public   void  _send(MailSendParam[] mailSendParams)  throws  MailException {
        
for  ( final  MailSendParam mailSendParam : mailSendParams) {
            
try  {
                
new  Thread( new  Runnable() {
                    
public   void  run() {
                        send(mailSendParam);
                    }
                }).run();
            } 
catch  (Exception e) {
                
continue ;
            }
        }
    }
    
    
private  MimeMessage getMessage(MailSendParam mailSendParam,Session session)  throws  MessagingException {
            
// 构造MimeMessage 并设定基本的值
            MimeMessage msg  =   new  MimeMessage(session);
            msg.setFrom(
new  InternetAddress(mailSendParam.getFrom()));
            InternetAddress[] address 
=  { new  InternetAddress(mailSendParam.getTo())};
            msg.setRecipients(Message.RecipientType.TO, address);
            String subject 
=  transferChinese(mailSendParam.getSubject());
            msg.setSubject(subject);
          
// 构造Multipart
            Multipart mp  =   new  MimeMultipart();
          
// 向Multipart添加正文
            MimeBodyPart mbpContent  =   new  MimeBodyPart();
           
//  mbpContent.setText(mailSendParam.getContent());
            mbpContent.setDataHandler( new  DataHandler(mailSendParam.getContent(), " text/html;charset=GB2312 " )); //  网页格式 
            
// 向MimeMessage添加(Multipart代表正文)
            mp.addBodyPart(mbpContent);
          
// 向Multipart添加附件
            Enumeration < String >  efile  =  mailSendParam.getFiles().elements();
            
while  (efile.hasMoreElements()) {
                MimeBodyPart mbpFile 
=   new  MimeBodyPart();
                String filename 
=  efile.nextElement().toString();
                FileDataSource fds 
=   new  FileDataSource(filename);
                mbpFile.setDataHandler(
new  DataHandler(fds));
                mbpFile.setFileName(fds.getName());
                
// 向MimeMessage添加(Multipart代表附件)
                mp.addBodyPart(mbpFile);
            }
            mailSendParam.getFiles().removeAllElements();
            
// 向Multipart添加MimeMessage
            msg.setContent(mp);
            msg.setSentDate(
new  Date());
            
return  msg;
    }
    
    
private  Session getSession(MailSendParam mailSendParam) {
        Properties props 
=  System.getProperties();
        props.put(
" mail.smtp.host " , mailSendParam.getSmtpHost());
        props.put(
" mail.smtp.auth " " true " );
        Session session 
=  Session.getDefaultInstance(props,
                
new  MailAuthenticator(mailSendParam.getSmtpUser(),
                        mailSendParam.getSmtpPasswd()));
        
return  session;
    }
    
    
private  String transferChinese(String strText) {
        
try  {
            strText 
=  MimeUtility.encodeText( new  String(strText.getBytes(),  " UTF-8 " ),  " GB2312 " " B " );
        } 
catch  (Exception e) {
            e.printStackTrace();
        }
        
return  strText;
    }
    
// Mail Authenticator Implement=======================================
     private   static   class  MailAuthenticator  extends  Authenticator {
        
private  String name;
        
private  String passwd;

        
public  MailAuthenticator(String name, String passwd) {
            
this .name  =  name;
            
this .passwd  =  passwd;
        }
        
        @Override
        
protected  PasswordAuthentication getPasswordAuthentication() {
            
return   new  PasswordAuthentication(name, passwd);
        }
    }
    
public   void  sendDefaultMail(MailSendParam mailSendParam)
            
throws  MailException {
        send(mailSendParam);
    }
}


/*
 * LogMessageBean.java
 * Copyright (C) 2009  <JustinLei@gmail.com>
 *
 *        This program is free software; you can redistribute it and/or modify
 *        it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *     (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *        GNU General Public License for more details.
 *
 
*/
package  org.lambdasoft.mdb;

import  javax.ejb.ActivationConfigProperty;
import  javax.ejb.MessageDriven;
import  javax.jms.Message;
import  javax.jms.MessageListener;
import  javax.jms.ObjectMessage;
import  javax.naming.InitialContext;

import  org.lambdasoft.components.mail.MailComponent;
import  org.lambdasoft.components.mail.param.MailSendParam;
import  org.lambdasoft.components.mail.param.MailSendType;

/**
 * 日志添加消息
 * 
 * 
@author  lei.tang (justinlei@gmail.com)
 * @date 2009-9-17
 * 
@version  1.0
 
*/
@MessageDriven(activationConfig 
=  {
        @ActivationConfigProperty(propertyName 
=   " destinationType " , propertyValue  =  MessageConstant.DESTINATIONTYPE_QUEUE),
        @ActivationConfigProperty(propertyName 
=   " acknowledgeMode " , propertyValue  =  MessageConstant.ACKNOWLEDGEMODE_AUTO),
        @ActivationConfigProperty(propertyName 
=   " destination " , propertyValue  =  MessageConstant.DESTINATION_MAIL) })
public   class  MailMessageBean  implements  MessageListener{
    
public   void  onMessage(Message message) {
        
if ( ! (message  instanceof  ObjectMessage))
            
return ;
        ObjectMessage objectMessage 
=  (ObjectMessage)message;
        
try  {
            
if ( ! (objectMessage.getObject()  instanceof  MailSendParam))
                
return ;
            MailSendParam mailSendParam 
=  (MailSendParam)objectMessage.getObject();
            InitialContext context 
=   new  InitialContext();
            MailComponent mailComponent 
=   null ;
            
if  (mailSendParam  ==   null )
                
return ;
            
if  (mailSendParam.getMailSendType().equals(MailSendType.POP3)) {
                mailComponent 
=  (MailComponent)context.lookup( " PopMainSendComponentBean/local " );
                mailComponent.send(mailSendParam);
            } 
else  {
                
return ;
            }
        } 
catch  (Exception e) {
            e.printStackTrace();
            
return ;
        }
    }
}

JNDI_Configure.properties
Context.INITIAL_CONTEXT_FACTORY  =  org.jnp.interfaces.NamingContextFactory
Context.URL_PKG_PREFIXES 
=  org.jboss.naming:org.jnp.interfaces
Context.PROVIDER_URL 
=  jnp://localhost: 1099
Service.Quartz.Naming 
=  Quartz


PopMailConfigure.properties
MAIL.SERVER.HOST  =  xxx.xx.x.xxx
MAIL.USER.FROM 
=  xxx@xxx.xx
MAIL.USER.SMTP 
=  xxxxxxxxx@xxx.xxx
MAIL.USER.PASSWORD 
=  xxxxxx




测试代码(Junit3 Code):
/*
 * TestSendMail.java
 * Copyright (C) 2009  <JustinLei@gmail.com>
 *
 *        This program is free software; you can redistribute it and/or modify
 *        it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *     (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *        GNU General Public License for more details.
 *
 
*/
package  test.org.lambdasoft.mail;

import  org.lambdasoft.components.mail.MailComponent;
import  org.lambdasoft.components.mail.param.MailSendParam;

import  test.org.lambdasoft.BaseTest;
import  test.org.lambdasoft.EJBUtil1;

/**
 * 
@author  lei.tang (justinlei@gmail.com)
 * @date 
 * 
@version
 
*/
public   class  TestSendMail  extends  BaseTest{
    
private  MailComponent mailComponent;
    
public   void  testSend() {
        mailComponent 
=  (MailComponent)EJBUtil1.getUtil().getRemoteEJB( " MailComponentBean/remote " );
        MailSendParam mailSendParam 
=   new  MailSendParam();
        mailSendParam.setContent(
" <html><body><b>测试邮件</b></body></html> " );
        mailSendParam.setSubject( " 测试邮件test " );
        mailSendParam.setTo(
"xxx @xx.com " );
        mailComponent.sendDefaultMail(mailSendParam);
    }
}


你可能感兴趣的:(Java Mail EJB3.0组件(POP Support))