KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dlog4j > plugins > MailPlugin


1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 2 of the License, or
5  * (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU Library General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15  */

16 package dlog4j.plugins;
17
18 import java.io.*;
19 import java.util.*;
20
21 import javax.mail.*;
22 import javax.naming.*;
23 import javax.mail.internet.*;
24 import javax.naming.directory.*;
25 import javax.servlet.ServletException JavaDoc;
26
27 import org.apache.struts.action.*;
28 import org.apache.commons.logging.*;
29 import org.apache.struts.config.ModuleConfig;
30
31 import dlog4j.util.mail.Mailer;
32
33 /**
34  * 直接连接邮件接收者的服务器进行邮件发送
35  * 该插件在struts-config.xml中的配置如下
36     <plug-in className="dlog4j.util.mail.MailPlugin">
37         <!-- 发送者邮件地址 -->
38         <set-property property="sender" value="dlog4j@gmail.com"/>
39     </plug-in>
40  * @author Winter Lau
41  */

42 public class MailPlugin extends Mailer implements PlugIn {
43
44     private static Log log = LogFactory.getLog(MailPlugin.class);
45     
46     private String JavaDoc sender = "dlog4j@gmail.com";
47     private DirContext context;
48     
49     /* (non-Javadoc)
50      * @see org.apache.struts.action.PlugIn#init(org.apache.struts.action.ActionServlet, org.apache.struts.config.ModuleConfig)
51      */

52     public void init(ActionServlet servlet, ModuleConfig config)
53         throws ServletException JavaDoc{
54         Hashtable env = new Hashtable();
55         env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.dns.DnsContextFactory");
56         env.put(Context.PROVIDER_URL, "dns://");
57         try{
58             context = new InitialDirContext(env);
59         }catch(NamingException e){
60             log.fatal("Mail Messenger start failed.", e);
61         }
62         mailer = this;
63     }
64
65     /**
66      * 邮件发送
67      * @param sn 发送者名称
68      * @param mails
69      * @param title
70      * @param content
71      */

72     public void send(final String JavaDoc sn,
73                      final String JavaDoc[] mails,
74                      final String JavaDoc title,
75                      final String JavaDoc content)
76     {
77         new Thread JavaDoc(){
78             public void run(){
79                 for(int i=0;i<mails.length;i++){
80                     try {
81                         String JavaDoc domain = parseDomain(mails[i]);
82                         Attributes attr = context.getAttributes(domain, new String JavaDoc[]{"MX"});
83                         NamingEnumeration servers = attr.getAll();
84                         // 列出所有邮件服务器:
85
while (servers.hasMore()) {
86                             Attribute hosts = (Attribute) servers.next();
87                             for (int j = 0; j < hosts.size(); j++) {
88                                 String JavaDoc host = (String JavaDoc) hosts.get(j);
89                                 host = host.substring(host.indexOf(' ') + 1);
90                                 sendMail(sn, mails[i], title, content, host);
91                                 break;
92                             }
93                             break;
94                         }
95                     } catch (Exception JavaDoc e) {
96                         log.error("Send mail to "+mails[i],e);
97                     }
98                 }
99             }
100             
101             /**
102              * 发送邮件
103              * @param sender
104              * @param mail
105              * @param title
106              * @param content
107              * @param host
108              * @throws MessagingException
109              * @throws UnsupportedEncodingException
110              */

111             private void sendMail(String JavaDoc sn, String JavaDoc mail, String JavaDoc title, String JavaDoc content, String JavaDoc host)
112                 throws UnsupportedEncodingException, MessagingException
113             {
114                 Properties props = System.getProperties();
115                 props.put("mail.smtp.host", host);
116                 props.put("mail.smtp.port", "25");
117                 props.put("mail.smtp.auth", "false");
118                 Session mailSession = Session.getInstance(props, null);
119
120                 MimeMessage mailMessage = new MimeMessage(mailSession);
121                 
122                 MimeBodyPart bodyPart = new MimeBodyPart();
123                 bodyPart.setContent(content, "text/html;charset=GB2312");
124                 Multipart multipart = new MimeMultipart("related");
125                 multipart.addBodyPart(bodyPart);
126                 mailMessage.setContent(multipart);
127                 
128                 mailMessage.setSentDate(new Date());
129                 mailMessage.setFrom(new InternetAddress(sender, sn));
130                 mailMessage.addRecipient(Message.RecipientType.TO,new InternetAddress(mail));
131                 mailMessage.setSubject(title);
132                 
133                 Transport.send(mailMessage);
134             }
135             /**
136              * 从邮件地址中解析出域名
137              * @param email
138              * @return
139              */

140             private String JavaDoc parseDomain(String JavaDoc email){
141                 String JavaDoc domain = null;
142                 if(email!=null){
143                     int idx = email.indexOf('@');
144                     if(idx != -1){
145                         idx++;
146                         if(idx<email.length())
147                             domain = email.substring(idx);
148                     }
149                 }
150                 return domain;
151             }
152         }.start();
153     }
154
155     /*
156      * (non-Javadoc)
157      * @see org.apache.struts.action.PlugIn#destroy()
158      */

159     public void destroy() {
160         try{
161             context.close();
162         }catch(Exception JavaDoc e){
163             log.error("Mail Messenger close context failed.", e);
164         }
165     }
166
167     public String JavaDoc getSender() {
168         return sender;
169     }
170     public void setSender(String JavaDoc sender) {
171         this.sender = sender;
172     }
173 }
174
Popular Tags