java Source

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            14 Posts :: 24 Stories :: 8 Comments :: 0 Trackbacks
          該組件實現分為以下及部分: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);
              }
          }


          posted on 2009-12-18 15:40 JustinLei 閱讀(1399) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 扶沟县| 东城区| 陆丰市| 龙山县| 广宁县| 樟树市| 弥勒县| 清远市| 延安市| 太仆寺旗| 璧山县| 庆城县| 沙湾县| 枞阳县| 繁昌县| 宝山区| 石台县| 龙游县| 天台县| 阿拉善盟| 博客| 霍城县| 广安市| 石门县| 交城县| 南皮县| 甘孜县| 鄂托克旗| 金沙县| 鸡西市| 惠来县| 精河县| 易门县| 大同县| 洪江市| 新宾| 奈曼旗| 牡丹江市| 开平市| 盐亭县| 墨竹工卡县|