郵件發(fā)送源碼: SendMail.java package com.lzw.mail; import java.util.Arrays; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.NoSuchProviderException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import com.lzw.io.Out; /** * 郵件發(fā)送程序 * @author 李趙偉 Create: 2007-12-19 */ public class SendMail { private Session session; //會話 private Transport transport; //發(fā)送郵件 private User user; //郵件相關(guān)的帳戶信息 private MailAddress mailAddress; //收件人地址 private MailBody mailBody; //郵件內(nèi)容 private final String MAIL_SMTP_HOST = "mail.smtp.host"; private final String MAIL_SMTP_AUTH = "mail.smtp.auth"; public SendMail(User user) { this.user = user; init(); } /** * 初始化<code> Session, Transport </code> */ private void init() { Authenticator auth = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user.getUsername(), user .getPassword()); } }; Properties props = new Properties(); // 設(shè)置發(fā)送郵件的郵件服務(wù)器的屬性(這里使用網(wǎng)易的smtp服務(wù)器) props.put(MAIL_SMTP_HOST, user.getHost()); // 需要經(jīng)過授權(quán),也就是有戶名和密碼的校驗,這樣才能通過驗證(一定要有這一條) props.put(MAIL_SMTP_AUTH, "true"); // 用剛剛設(shè)置好的props對象構(gòu)建一個session session = Session.getDefaultInstance(props, auth); try { // 發(fā)送郵件 transport = session.getTransport("smtp"); // 連接服務(wù)器的郵箱 transport.connect(user.getHost(), user.getUsername(), user .getPassword()); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } Out.pln("與 " + user.getHost() + " 成功建立會話"); } /** * 設(shè)置收件人地址 * * @param mailAddress */ public void setAddress(MailAddress mailAddress) { this.mailAddress = mailAddress; } /** * 設(shè)置郵件內(nèi)容 * * @param mailBody */ public void setMailBody(MailBody mailBody) { this.mailBody = mailBody; } /** * 構(gòu)造郵件的內(nèi)容 * * @return * @throws AddressException * @throws MessagingException */ private Message createMessage() throws AddressException, MessagingException { // 用session為參數(shù)定義消息對象 MimeMessage message = new MimeMessage(session); // 加載發(fā)件人地址 message.setFrom(new InternetAddress(user.getFrom())); message.setSentDate(new Date()); // 加載收件人地址 message.addRecipients(Message.RecipientType.TO, getAddress(mailAddress .getTo())); if (mailAddress.isHasCC()) message.addRecipients(Message.RecipientType.CC, getAddress(mailAddress.getCc())); // 加載標題 message.setSubject(mailBody.getSubject()); if (mailBody.isContentFlag() || mailBody.isAffixFlag()) { // 向multipart對象中添加郵件的各個部分內(nèi)容,包括文本內(nèi)容和附件 Multipart multipart = new MimeMultipart(); if (mailBody.isContentFlag()) { // 設(shè)置郵件的文本內(nèi)容 MimeBodyPart contentPart = new MimeBodyPart(); if (mailBody.isMimeContent()) contentPart.setContent(mailBody.getContent(), "text/html;charset=GBK"); else contentPart.setText(mailBody.getContent()); multipart.addBodyPart(contentPart); } if (mailBody.isAffixFlag()) { // 添加附件 BodyPart affixBody = new MimeBodyPart(); DataSource source = new FileDataSource(mailBody.getAffix()); // 添加附件的內(nèi)容 affixBody.setDataHandler(new DataHandler(source)); // 添加附件的標題這里很重要,通過下面的Base64編碼的轉(zhuǎn)換可以保證你的 // 中文附件標題名在發(fā)送時不會變成亂碼 sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); String fileName = "=?GBK?B?" + enc.encode(mailBody.getAffixName().getBytes()) + "?="; affixBody.setFileName(fileName); multipart.addBodyPart(affixBody); } // 將multipart對象放到message中 message.setContent(multipart); } // 保存郵件 message.saveChanges(); return message; } /** * 發(fā)送郵件,包含:郵件正文、(1個附件) * * @param debug * 調(diào)試設(shè)置 */ public void send(boolean debug) { // 有了這句便可以在發(fā)送郵件的過程中在console處顯示過程信息,供調(diào)試使 // 用(你可以在控制臺(console)上看到發(fā)送郵件的過程) session.setDebug(debug); try { Message message = createMessage(); transport.sendMessage(message, message.getAllRecipients()); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } Out.pln("\n----------------------------------------------------------"); Out.pln("- 郵件成功發(fā)送!"); Out.pln("- TO : " + Arrays.toString(mailAddress.getTo())); if (mailAddress.isHasCC()) Out.pln("- CC : " + Arrays.toString(mailAddress.getCc())); Out.pln("----------------------------------------------------------\n"); } /** * 關(guān)閉資源 * * @throws MessagingException */ public void close() throws MessagingException { if (null != transport) transport.close(); } public Address[] getAddress(String[] address) throws AddressException { Address[] addrs = new InternetAddress[address.length]; for (int i = 0; i < address.length; i++) addrs[i] = new InternetAddress(address[i]); return addrs; } /** * 測試 */ public static void main(String[] args) { String host = "smtp.sina.com"; String username = ""; String password = ""; // String from = ""; String to = ""; // String cc = null; String subject = "測試"; String content = "<a href=http://www.baidu.com>baidu</a>"; boolean mimeContent = true; String affix = "d:/temp/temp.txt"; String affixName = "temp.txt"; boolean debug = false; // String userFile = "user.properties"; // String addressFile = "mailaddress.properties"; SendMail mail = null; try { try { User user = new User(host, username, password); MailAddress mailAddress = new MailAddress(to); // User user = new User(userFile); // MailAddress mailAddress = new MailAddress(SendMail.class // .getResourceAsStream(addressFile)); MailBody mailBody = new MailBody(subject, content, mimeContent, affix, affixName); mail = new SendMail(user); // for (int i = 0; i < 5; i++) { // 設(shè)置發(fā)件人地址、收件人地址和郵件標題 mail.setAddress(mailAddress); // 設(shè)置要發(fā)送附件的位置和標題 mail.setMailBody(mailBody); // 設(shè)置smtp服務(wù)器以及郵箱的賬號和密碼 mail.send(debug); // try { // Thread.sleep(1 * 1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // mailBody = new MailBody(subject + "_" + (i + 1), content); // } } finally { if (null != mail) mail.close(); } } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); } } }
使用JavaMail發(fā)送郵件需要注意的地方: 使用免費的郵件服務(wù)器發(fā)送郵件時,需要對用戶的身份做驗證;而進行身份驗證的過程又比較消耗時間,當用戶需要發(fā)送多封郵件時如果每次都做身份驗證的話時間的消耗是非常大的; 在整個郵件發(fā)送過程中Session(會話)的建立只需要一次,也就是說身份驗證也只做一次就可以了,即Session session = Session. getDefaultInstance(props, auth); 發(fā)送郵件的過程相對比較簡單,有一個需要注意的地方就是連接郵件服務(wù)器時transport.connect(user.getHost(), user.getUsername(), user.getPassword());也只需要執(zhí)行一次即可,這個過程和身份驗證一樣都需要消耗大量時間。 該程序只允許發(fā)送帶有一個附件的郵件;
|
|