ajie

Java天下社区 http://www.javatx.cn 欢迎大家上来交流Java技术
posts - 4, comments - 8, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

利用Java Mail API 开发邮件通知服务

Posted on 2005-12-18 00:38 ajie 阅读(2679) 评论(2)  编辑  收藏
  1/**
  2 * 该类演示了Java Mail的应用
  3 * 版权 本文版权属Java天下
  4 * @author ljfan
  5 * @version 2.0, Created on 2005/08/10
  6 * 
  7 */

  8
  9package cn.javatx.util;
 10
 11import java.io.FileInputStream;
 12import java.text.SimpleDateFormat;
 13import java.util.Collection;
 14import java.util.Collections;
 15import java.util.Date;
 16import java.util.Properties;
 17import java.util.concurrent.ArrayBlockingQueue;
 18import java.util.concurrent.ThreadPoolExecutor;
 19import java.util.concurrent.TimeUnit;
 20
 21import javax.mail.Address;
 22import javax.mail.Message;
 23import javax.mail.MessagingException;
 24import javax.mail.Part;
 25import javax.mail.SendFailedException;
 26import javax.mail.Session;
 27import javax.mail.Transport;
 28import javax.mail.URLName;
 29import javax.mail.internet.AddressException;
 30import javax.mail.internet.InternetAddress;
 31import javax.mail.internet.MimeBodyPart;
 32import javax.mail.internet.MimeMessage;
 33import javax.mail.internet.MimeMultipart;
 34import javax.mail.internet.MimeUtility;
 35
 36public class Mail {
 37
 38    private String host;
 39
 40    private int port;
 41
 42    private String username;
 43
 44    private String password;
 45
 46    ThreadPoolExecutor executor = null;
 47
 48    private static Mail mail = new Mail();
 49
 50    public static Mail getInstance() {
 51        return mail;
 52    }

 53
 54    private Mail() {
 55        try {
 56            Properties prop = new Properties();
 57            FileInputStream fis = new FileInputStream("H:\\Tomcat5\\webapps\\ROOT\\WEB-INF\\classes\\mail.properties");
 58            prop.load(fis);
 59
 60            this.host = prop.getProperty("mail.smtp.host");
 61            this.port = Integer.parseInt(prop.getProperty("mail.smtp.port"));
 62            this.username = prop.getProperty("mail.smtp.username");
 63            this.password = prop.getProperty("mail.smtp.password");
 64            
 65            System.out.println("host:"+host);
 66            System.out.println("port:"+port);
 67
 68        }
 catch (Exception e) {
 69            System.out.println(e.getMessage());
 70        }

 71        
 72        executor = new ThreadPoolExecutor(1, Integer.MAX_VALUE, 60,
 73                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5));
 74    }

 75
 76    private Session session = null;
 77
 78    /**
 79     * Creates a Javamail session.
 80     */

 81    private synchronized void createSession() {
 82        if (host == null{
 83            throw new IllegalArgumentException("Host cannot be null.");
 84        }

 85
 86        Properties mailProps = new Properties();
 87        mailProps.setProperty("mail.smtp.host", host);
 88        mailProps.setProperty("mail.smtp.port", String.valueOf(port));
 89        mailProps.setProperty("mail.smtp.sendpartial""true");
 90        if (username != null{
 91            mailProps.put("mail.smtp.auth""true");
 92        }

 93        session = Session.getInstance(mailProps, null);
 94    }

 95
 96    public MimeMessage createMimeMessage() {
 97        if (session == null{
 98            createSession();
 99        }

100        return new MimeMessage(session);
101    }

102
103    /**
104     * 发送邮件
105     * 
106     * @param fromName
107     *            发件人姓名
108     * @param fromEmail
109     *            发件人地址
110     * @param ToEmail
111     *            收件人地址
112     * @param CcEmail
113     *            抄送人地址
114     * @param subject
115     *            邮件主题
116     * @param textBody
117     *            邮件内容
118     * @param htmlBody
119     *            邮件内容(html形式)
120     */

121    public void sendMessage(String fromName, String fromEmail, String ToEmail,
122            String CcEmail, String subject, String textBody, String htmlBody) {
123        try {
124            String encoding = MimeUtility.mimeCharset("gb2312");
125            MimeMessage message = createMimeMessage();
126            
127            String sTo[] = ToEmail.split(",");
128            String sCc[] = CcEmail.split(",");
129            
130            //收件人地址
131            Address to[] = new Address[sTo.length];
132            for (int i = 0; i < sTo.length; i++{
133                to[i] = new InternetAddress(sTo[i], "", encoding);
134            }

135            
136            //抄送人地址
137            Address cc[] = new Address[sCc.length];
138            for (int i = 0; i < sTo.length; i++{
139                cc[i] = new InternetAddress(sCc[i], "", encoding);
140            }

141            
142            Address from = null;
143
144            if (fromName != null{
145                from = new InternetAddress(fromEmail, fromName, encoding);
146            }
 else {
147                from = new InternetAddress(fromEmail, "", encoding);
148            }

149
150            SimpleDateFormat format = new SimpleDateFormat(
151                    "EEE, dd MMM yyyy HH:mm:ss Z", java.util.Locale.US);
152
153            message.setHeader("Date", format.format(new Date()));
154            message.setHeader("Content-Transfer-Encoding""8bit");
155            message.setRecipients(Message.RecipientType.TO, to);
156            if (!(CcEmail.equals("")) || (CcEmail == null)) {
157                message.setRecipients(Message.RecipientType.CC, cc);
158            }

159            message.setFrom(from);
160            message.setSubject(subject, encoding);
161            // Create HTML, plain-text, or combination message
162            if (textBody != null && htmlBody != null{
163                MimeMultipart content = new MimeMultipart("alternative");
164                // Plain-text
165                MimeBodyPart text = new MimeBodyPart();
166                text.setText(textBody, encoding);
167                text.setDisposition(Part.INLINE);
168                content.addBodyPart(text);
169                // HTML
170                MimeBodyPart html = new MimeBodyPart();
171                html.setContent(htmlBody, "text/html");
172                html.setDisposition(Part.INLINE);
173                content.addBodyPart(html);
174                // Add multipart to message.
175                message.setContent(content);
176                message.setDisposition(Part.INLINE);
177                addToTask(message);
178            }
 else if (textBody != null{
179                MimeBodyPart bPart = new MimeBodyPart();
180                bPart.setText(textBody, encoding);
181                bPart.setDisposition(Part.INLINE);
182                MimeMultipart mPart = new MimeMultipart();
183                mPart.addBodyPart(bPart);
184                message.setContent(mPart);
185                message.setDisposition(Part.INLINE);
186                addToTask(message);
187            }
 else if (htmlBody != null{
188                MimeBodyPart bPart = new MimeBodyPart();
189                bPart.setContent(htmlBody, "text/html");
190                bPart.setDisposition(Part.INLINE);
191                MimeMultipart mPart = new MimeMultipart();
192                mPart.addBodyPart(bPart);
193                message.setContent(mPart);
194                message.setDisposition(Part.INLINE);
195                addToTask(message);
196            }

197        }
 catch (Exception e) {
198            System.out.println(e.getMessage());
199        }

200    }

201
202    private void addToTask(MimeMessage message) {
203        if (message != null{
204            sendMessages(Collections.singletonList(message));
205        }
 else {
206            System.out.println("Cannot add null email message to queue.");
207        }

208
209    }

210
211    public void sendMessages(Collection<MimeMessage> messages) {
212        if (messages.size() == 0{
213            return;
214        }

215        executor.execute(new EmailTask(messages));
216    }

217
218    /**
219     * Task to send one or more emails via the SMTP server.
220     */

221    private class EmailTask implements Runnable {
222
223        private Collection<MimeMessage> messages;
224
225        public EmailTask(Collection<MimeMessage> messages) {
226            this.messages = messages;
227        }

228
229        public void run() {
230            try {
231                sendMessages();
232            }
 catch (MessagingException me) {
233                System.out.println(me.getMessage());
234            }

235        }

236
237        public void sendMessages() throws MessagingException {
238            Transport transport = null;
239            try {
240                URLName url = new URLName("smtp", host, port, "", username,
241                        password);
242                transport = new com.sun.mail.smtp.SMTPTransport(session, url);
243                transport.connect(host, port, username, password);
244                //System.out.println(messages.size());
245                for (MimeMessage message : messages) {
246                    try {
247                        transport.sendMessage(message, message
248                                .getRecipients(MimeMessage.RecipientType.TO));
249                    }
 catch (AddressException ae) {
250                        System.out.println(ae.getMessage());
251                    }
 catch (SendFailedException sfe) {
252                        System.out.println(sfe.getMessage());
253                    }

254                }

255            }
 finally {
256                if (transport != null{
257                    try {
258                        transport.close();
259                    }
 catch (MessagingException e) /* ignore */
260                    }

261                }

262            }

263        }

264    }

265}

266


Java天下社区
http://www.javatx.cn
欢迎大家上来交流Java技术。

评论

# re: 利用Java Mail API 开发邮件通知服务   回复  更多评论   

2007-11-14 11:14 by aguai
H:\\Tomcat5\\webapps\\ROOT\\WEB-INF\\classes\\mail.properties

mail.properties配置文件里 的内容是什么呀?








# re: 利用Java Mail API 开发邮件通知服务   回复  更多评论   

2009-03-31 10:19 by 淡然一笑
在代码中是不应该出现服务器的路径的
H:\\Tomcat5\\webapps\\ROOT\\WEB-INF\\classes\\mail.properties

这样安全性不好

只有注册用户登录后才能发表评论。


网站导航: