001: /*
002: * This program is free software; you can redistribute it and/or modify
003: * it under the terms of the GNU General Public License as published by
004: * the Free Software Foundation; either version 2 of the License, or
005: * (at your option) any later version.
006: *
007: * This program is distributed in the hope that it will be useful,
008: * but WITHOUT ANY WARRANTY; without even the implied warranty of
009: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
010: * GNU Library General Public License for more details.
011: *
012: * You should have received a copy of the GNU General Public License
013: * along with this program; if not, write to the Free Software
014: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
015: */
016: package dlog4j.util.mail;
017:
018: import java.io.File;
019: import java.io.UnsupportedEncodingException;
020: import java.util.ArrayList;
021: import java.util.Date;
022: import java.util.Properties;
023:
024: import javax.activation.DataHandler;
025: import javax.activation.DataSource;
026: import javax.activation.FileDataSource;
027: import javax.mail.Authenticator;
028: import javax.mail.BodyPart;
029: import javax.mail.Message;
030: import javax.mail.MessagingException;
031: import javax.mail.Multipart;
032: import javax.mail.PasswordAuthentication;
033: import javax.mail.SendFailedException;
034: import javax.mail.Session;
035: import javax.mail.Transport;
036: import javax.mail.internet.InternetAddress;
037: import javax.mail.internet.MimeBodyPart;
038: import javax.mail.internet.MimeMessage;
039: import javax.mail.internet.MimeMultipart;
040:
041: import org.htmlparser.Node;
042: import org.htmlparser.Parser;
043: import org.htmlparser.tags.ImageTag;
044: import org.htmlparser.util.ParserException;
045:
046: /**
047: * 邮件发送组件,具体的使用方法参照该类的main方法
048: * @author Liudong
049: */
050: public abstract class MailSender extends Authenticator {
051:
052: private String username = null; //邮件发送帐号用户名
053: private String userpasswd = null; //邮件发送帐号用户口令
054: protected BodyPart messageBodyPart = null;
055: protected Multipart multipart = new MimeMultipart("related");
056: protected MimeMessage mailMessage = null;
057: protected Session mailSession = null;
058: protected InternetAddress mailToAddress = null;
059:
060: /**
061: * 构造函数
062: * @param smtpHost
063: * @param username
064: * @param password
065: */
066: protected MailSender(String smtpHost, String username,
067: String password) {
068: this (smtpHost, 25, username, password);
069: }
070:
071: /**
072: * 构造函数
073: * @param smtpHost
074: * @param smtpPort
075: * @param username
076: * @param password
077: */
078: protected MailSender(String smtpHost, int smtpPort,
079: String username, String password) {
080: this .username = username;
081: this .userpasswd = password;
082: Properties mailProperties = System.getProperties();
083: mailProperties.put("mail.smtp.host", smtpHost);
084: if (smtpPort > 0 && smtpPort != 25)
085: mailProperties.put("mail.smtp.port", String
086: .valueOf(smtpPort));
087: mailProperties.put("mail.smtp.auth", "true"); //设置smtp认证,很关键的一句
088: mailSession = Session.getDefaultInstance(mailProperties, this );
089: mailMessage = new MimeMessage(mailSession);
090: messageBodyPart = new MimeBodyPart();
091: }
092:
093: /**
094: * 构造一个纯文本邮件发送实例
095: * @see getTextMailSender(String smtpHost, int smtpPort, String username, String password)
096: * @param smtpHost
097: * @param username
098: * @param password
099: * @return
100: */
101: public static MailSender getTextMailSender(String smtpHost,
102: String username, String password) {
103: return getTextMailSender(smtpHost, 25, username, password);
104: }
105:
106: /**
107: * 构造一个纯文本邮件发送实例
108: * @param smtpHost SMTP服务器地址
109: * @param smtpPort SMTP服务器端口
110: * @param username SMTP邮件发送帐号
111: * @param password SMTP邮件发送帐号对应的密码
112: * @return
113: */
114: public static MailSender getTextMailSender(String smtpHost,
115: int smtpPort, String username, String password) {
116: return new MailSender(smtpHost, smtpPort, username, password) {
117: public void setMailContent(String mailContent)
118: throws MessagingException {
119: messageBodyPart.setText(mailContent);
120: multipart.addBodyPart(messageBodyPart);
121: }
122: };
123: }
124:
125: /**
126: * 构造一个超文本邮件发送实例
127: * @see getHtmlMailSender(String smtpHost, int smtpPort, String username, String password)
128: * @param smtpHost
129: * @param username
130: * @param password
131: * @return
132: */
133: public static MailSender getHtmlMailSender(String smtpHost,
134: String username, String password) {
135: return getHtmlMailSender(smtpHost, 25, username, password);
136: }
137:
138: /**
139: * 构造一个超文本邮件发送实例
140: * @param smtpHost SMTP服务器地址
141: * @param smtpPort SMTP服务器端口
142: * @param username SMTP邮件发送帐号
143: * @param password SMTP邮件发送帐号对应的密码
144: * @return
145: */
146: public static MailSender getHtmlMailSender(String smtpHost,
147: int smtpPort, String username, String password) {
148: return new MailSender(smtpHost, smtpPort, username, password) {
149: private ArrayList arrayList1 = new ArrayList();
150: private ArrayList arrayList2 = new ArrayList();
151:
152: public void setMailContent(String mailContent)
153: throws MessagingException {
154: String htmlContent = getContent(mailContent);
155: messageBodyPart.setContent(htmlContent, CONTENT_TYPE);
156: multipart.addBodyPart(messageBodyPart);
157: //调用处理html文件中的图片方法
158: processHtmlImage(mailContent);
159: }
160:
161: //处理html页面上的图片方法如下:
162: private void processHtmlImage(String mailContent)
163: throws MessagingException {
164: for (int i = 0; i < arrayList1.size(); i++) {
165: messageBodyPart = new MimeBodyPart();
166: DataSource source = new FileDataSource(
167: (String) arrayList1.get(i));
168: messageBodyPart.setDataHandler(new DataHandler(
169: source));
170: String contentId = "<" + (String) arrayList2.get(i)
171: + ">";
172: messageBodyPart.setHeader("Content-ID", contentId);
173: messageBodyPart.setFileName((String) arrayList1
174: .get(i));
175: multipart.addBodyPart(messageBodyPart);
176: }
177: }
178:
179: //处理要发送的html文件,主要是针对html文件中的图片
180: private String getContent(String mailContent) {
181: try {
182: Parser parser = Parser.createParser(new String(
183: mailContent.getBytes(), ISO8859_1));
184: Node[] images = parser
185: .extractAllNodesThatAre(ImageTag.class);
186: for (int i = 0; i < images.length; i++) {
187: ImageTag imgTag = (ImageTag) images[i];
188: if (!imgTag.getImageURL().toLowerCase()
189: .startsWith("http://"))
190: arrayList1.add(imgTag.getImageURL());
191: }
192: } catch (UnsupportedEncodingException e1) {
193: } catch (ParserException e) {
194: }
195: String afterReplaceStr = mailContent;
196: //在html文件中用"cid:"+Content-ID来替换原来的图片链接
197: for (int m = 0; m < arrayList1.size(); m++) {
198: arrayList2.add(createRandomStr());
199: String addString = "cid:"
200: + (String) arrayList2.get(m);
201: afterReplaceStr = mailContent.replaceAll(
202: (String) arrayList1.get(m), addString);
203: }
204: return afterReplaceStr;
205: }
206:
207: //产生一个随机字符串,为了给图片设定Content-ID值
208: private String createRandomStr() {
209: char[] randomChar = new char[8];
210: for (int i = 0; i < 8; i++) {
211: randomChar[i] = (char) (Math.random() * 26 + 'a');
212: }
213: String replaceStr = new String(randomChar);
214: return replaceStr;
215: }
216:
217: private final static String CONTENT_TYPE = "text/html;charset=GB2312";
218: private final static String ISO8859_1 = "8859_1";
219: };
220: }
221:
222: /**
223: * 用于实现邮件发送用户验证
224: * @see javax.mail.Authenticator#getPasswordAuthentication
225: */
226: protected PasswordAuthentication getPasswordAuthentication() {
227: return new PasswordAuthentication(username, userpasswd);
228: }
229:
230: /**
231: * 设置邮件标题
232: * @param mailSubject
233: * @throws MessagingException
234: */
235: public void setSubject(String mailSubject)
236: throws MessagingException {
237: mailMessage.setSubject(mailSubject);
238: }
239:
240: /**
241: * 所有子类都需要实现的抽象方法,为了支持不同的邮件类型
242: * @param mailContent
243: * @throws MessagingException
244: */
245: public abstract void setMailContent(String mailContent)
246: throws MessagingException;
247:
248: /**
249: * 设置邮件发送日期
250: * @param sendDate
251: * @throws MessagingException
252: */
253: public void setSendDate(Date sendDate) throws MessagingException {
254: mailMessage.setSentDate(sendDate);
255: }
256:
257: /**
258: * 设置邮件发送附件
259: * @param attachmentName
260: * @throws MessagingException
261: */
262: public void setAttachments(String attachmentName)
263: throws MessagingException {
264: messageBodyPart = new MimeBodyPart();
265: DataSource source = new FileDataSource(attachmentName);
266: messageBodyPart.setDataHandler(new DataHandler(source));
267: int index = attachmentName.lastIndexOf(File.separator);
268: String attachmentRealName = attachmentName.substring(index + 1);
269: messageBodyPart.setFileName(attachmentRealName);
270: multipart.addBodyPart(messageBodyPart);
271: }
272:
273: /**
274: * 设置发件人地址
275: * @param mailFrom
276: * @throws MessagingException
277: * @throws UnsupportedEncodingException
278: */
279: public void setMailFrom(String mailFrom, String sender)
280: throws UnsupportedEncodingException, MessagingException {
281: if (sender != null)
282: mailMessage.setFrom(new InternetAddress(mailFrom, sender));
283: else
284: mailMessage.setFrom(new InternetAddress(mailFrom));
285: }
286:
287: /**
288: * 设置收件人地址,收件人类型为to,cc,bcc(大小写不限)
289: * @param mailTo 邮件接收者地址
290: * @param mailType 值为to,cc,bcc
291: * @author Liudong
292: */
293: public void setMailTo(String[] mailTo, String mailType)
294: throws Exception {
295: for (int i = 0; i < mailTo.length; i++) {
296: mailToAddress = new InternetAddress(mailTo[i]);
297: if (mailType.equalsIgnoreCase("to")) {
298: mailMessage.addRecipient(Message.RecipientType.TO,
299: mailToAddress);
300: } else if (mailType.equalsIgnoreCase("cc")) {
301: mailMessage.addRecipient(Message.RecipientType.CC,
302: mailToAddress);
303: } else if (mailType.equalsIgnoreCase("bcc")) {
304: mailMessage.addRecipient(Message.RecipientType.BCC,
305: mailToAddress);
306: } else {
307: throw new Exception("Unknown mailType: " + mailType
308: + "!");
309: }
310: }
311: }
312:
313: /**
314: * 开始发送邮件
315: * @throws MessagingException
316: * @throws SendFailedException
317: */
318: public void sendMail() throws MessagingException,
319: SendFailedException {
320: if (mailToAddress == null)
321: throw new MessagingException("请你必须你填写收件人地址!");
322: mailMessage.setContent(multipart);
323: Transport.send(mailMessage);
324: }
325:
326: /**
327: * 邮件发送测试
328: * @param args
329: */
330: public static void main(String args[]) {
331: String mailHost = "smtp.163.com"; //发送邮件服务器地址
332: String mailUser = "user1"; //发送邮件服务器的用户帐号
333: String mailPassword = "password1"; //发送邮件服务器的用户密码
334: String[] toAddress = { "user1@163.com" };
335: //使用超文本格式发送邮件
336: MailSender sendmail = MailSender.getHtmlMailSender(mailHost,
337: mailUser, mailPassword);
338: //使用纯文本格式发送邮件
339: //MailSender sendmail = MailSender.getTextMailSender(mailHost, mailUser,mailPassword);
340: try {
341: sendmail.setSubject("邮件发送测试");
342: sendmail.setSendDate(new Date());
343: String content = "<H1>你好,中国</H1><img src=\"http://www.javayou.com/images/logo.gif\">";
344: //请注意如果是本地图片比如使用斜杠作为目录分隔符,如下所示
345: content += "<img src=\"D:/EclipseM7/workspace/JDlog/dlog/images/rss200.png\"/>";
346: sendmail.setMailContent(content); //
347: sendmail.setAttachments("E:\\TOOLS\\pm_sn.txt");
348: sendmail.setMailFrom("user1@163.com", "发送者");
349: sendmail.setMailTo(toAddress, "to");
350: //sendmail.setMailTo(toAddress, "cc");//设置抄送给...
351: //开始发送邮件
352: System.out.println("正在发送邮件,请稍候.......");
353: sendmail.sendMail();
354: System.out.println("恭喜你,邮件已经成功发送!");
355: } catch (Exception ex) {
356: ex.printStackTrace();
357: }
358: }
359:
360: }
|