JAVA MAIL是利用現有的郵件賬戶發送郵件的工具,比如說,我在網易註冊一個郵箱賬戶,通過JAVA Mail的操控,我可以不親自登錄網易郵箱,讓程序自動的使用網易郵箱發送郵件。這一機制被廣泛的用在註冊激活和垃圾郵件的發送等方面。
JavaMail可以到http://www.oracle.com/technetwork/java/javamail/index-138643.html進行下載,並將mail.jar添加到classpath即可。如果你使用的是JAVA
EE SDK,則可以在C:\glassfishv3\glassfish\modules\mail.jar找到所需的jar包,同樣需要添加的classpath。
JAVA郵件發送的大致過程是這樣的的:
1、構建一個繼承自javax.mail.Authenticator的具體類,並重寫裏面的getPasswordAuthentication()方法。此類是用作登錄校驗的,以確保你對該郵箱有發送郵件的權利。
2、構建一個properties文件,該文件中存放SMTP服務器地址等參數。
3、通過構建的properties文件和javax.mail.Authenticator具體類來創建一個javax.mail.Session。Session的創建,就相當於登錄郵箱一樣。剩下的自然就是新建郵件。
4、構建郵件內容,一般是javax.mail.internet.MimeMessage對象,並指定發送人,收信人,主題,內容等等。
5、使用javax.mail.Transport工具類發送郵件。
下面是我封裝的代碼,註釋也比較詳細。呼呼~~
1、首先是繼承自javax.mail.Authenticator的一個具體類。getPasswordAuthentication()方法也就是構建一個PasswordAuthentication對象並返回,有點費解JAVA Mail這樣的設計意圖,可能是javax.mail.Authenticator爲我們提供了附加的保證安全的驗證措施吧。
package
com.mzule.simplemail; |
import
javax.mail.Authenticator; |
import
javax.mail.PasswordAuthentication; |
public
class MailAuthenticator extends
Authenticator { |
public
MailAuthenticator(String username, String password) {
|
this .username = username;
|
this .password = password;
|
protected
PasswordAuthentication getPasswordAuthentication() {
|
return
new PasswordAuthentication(username, password);
|
public
void setPassword(String password) {
|
this .password = password;
|
public
void setUsername(String username) {
|
this .username = username;
|
2、郵件發送類,剩下的步驟都是在這個類實現的。代碼中的SimpleMail是封裝了郵件主題和內容的一個POJO。覺得在一個方法參數中既包含主題又包含內容,不太合適,故重載了此方法。還有就是因爲大多數郵箱的SMTP服務器地址都是可以通過郵箱地址算出來,簡單起見,提供了一個不需要SMTP服務器地址的構造器。
package
com.mzule.simplemail; |
import
java.util.Properties; |
import
javax.mail.MessagingException; |
import
javax.mail.Session; |
import
javax.mail.Transport; |
import
javax.mail.internet.AddressException; |
import
javax.mail.internet.InternetAddress; |
import
javax.mail.internet.MimeMessage; |
import
javax.mail.internet.MimeMessage.RecipientType; |
public
class SimpleMailSender { |
private
final transient
Properties props = System.getProperties(); |
private
transient MailAuthenticator authenticator;
|
private
transient Session session;
|
public
SimpleMailSender( final
String smtpHostName, final
String username, |
init(username, password, smtpHostName);
|
* 發送郵件的用戶名(地址),並以此解析SMTP服務器地址
|
public
SimpleMailSender( final
String username, final
String password) { |
final
String smtpHostName = "smtp."
+ username.split( "@" )[ 1 ];
|
init(username, password, smtpHostName);
|
private
void init(String username, String password, String smtpHostName) {
|
props.put( "mail.smtp.auth" ,
"true" );
|
props.put( "mail.smtp.host" , smtpHostName);
|
authenticator =
new MailAuthenticator(username, password);
|
session = Session.getInstance(props, authenticator);
|
* @throws AddressException
|
* @throws MessagingException
|
public
void send(String recipient, String subject, Object content)
|
throws
AddressException, MessagingException { |
final
MimeMessage message = new
MimeMessage(session); |
message.setFrom( new
InternetAddress(authenticator.getUsername())); |
message.setRecipient(RecipientType.TO,
new InternetAddress(recipient));
|
message.setSubject(subject);
|
message.setContent(content.toString(),
"text/html;charset=utf-8" );
|
* @throws AddressException
|
* @throws MessagingException
|
public
void send(List<String> recipients, String subject, Object content)
|
throws
AddressException, MessagingException { |
final
MimeMessage message = new
MimeMessage(session); |
message.setFrom( new
InternetAddress(authenticator.getUsername())); |
final
int num = recipients.size();
|
InternetAddress[] addresses =
new InternetAddress[num];
|
for
( int
i = 0 ; i < num; i++) {
|
addresses[i] =
new InternetAddress(recipients.get(i));
|
message.setRecipients(RecipientType.TO, addresses);
|
message.setSubject(subject);
|
message.setContent(content.toString(),
"text/html;charset=utf-8" );
|
* @throws AddressException
|
* @throws MessagingException
|
public
void send(String recipient, SimpleMail mail)
|
throws
AddressException, MessagingException { |
send(recipient, mail.getSubject(), mail.getContent());
|
* @throws AddressException
|
* @throws MessagingException
|
public
void send(List<String> recipients, SimpleMail mail)
|
throws
AddressException, MessagingException { |
send(recipients, mail.getSubject(), mail.getContent());
|
3、調用上面的郵箱發送器,可以構建一個工廠類,工廠類可以封裝創建的過程,所以通過讀配置文件獲取郵箱用戶名,密碼都會變得十分方便。下面的代碼是我在寫觀察者模式的時候寫的,只是簡單演示了工廠類。
package
com.mzule.dp.observer.factory; |
import
com.mzule.dp.observer.constant.MailSenderType; |
import
com.mzule.simplemail.SimpleMailSender; |
public
class MailSenderFactory { |
private
static SimpleMailSender serviceSms =
null ; |
public
static SimpleMailSender getSender(MailSenderType type) {
|
if
(type == MailSenderType.SERVICE) { |
if
(serviceSms == null ) {
|
4、發送郵件,還是觀察者模式DEMO裏面的代碼,呼呼。
package
com.mzule.dp.observer.observer; |
import
java.util.ArrayList; |
import
java.util.Observable; |
import
java.util.Observer; |
import
javax.mail.MessagingException; |
import
javax.mail.internet.AddressException; |
import
com.mzule.dp.observer.constant.MailSenderType; |
import
com.mzule.dp.observer.factory.MailSenderFactory; |
import
com.mzule.dp.observer.po.Product; |
import
com.mzule.simplemail.SimpleMailSender; |
public
class ProductPriceObserver implements
Observer { |
public
void update(Observable obj, Object arg) {
|
if
(obj instanceof
Product) { |
if
(arg instanceof
Float) { |
Float price = (Float) arg;
|
Float decrease = product.getPrice() - price;
|
SimpleMailSender sms = MailSenderFactory
|
.getSender(MailSenderType.SERVICE);
|
List<String> recipients =
new ArrayList<String>();
|
for
(String recipient : recipients) { |
sms.send(recipient,
"價格變動" , "您關注的物品" |
+ product.getName() +
"降價了,由" |
+ product.getPrice() +
"元降到" + price +
"元,降幅達" |
+ decrease +
"元人民幣。趕快購物吧。" );
|
}
catch (AddressException e) {
|
}
catch (MessagingException e) {
|
5、剩下的就是去查看郵件是否發送成功了。呼呼~~