Apusic上用JavaMail發郵件
Apusic上用JavaMail發郵件
0. JavaMail基本介紹
?JavaMail是屬于J2EE框架中的一部分,主要是為簡化Mail部分開發工作。使用JavaMail發送郵件需要以下步驟:
?1)初始化Session實例;
?在初始化Session實例中有兩種方式:使用JNDI初始化和在代碼中自行完成初始化。
?★ 如果SMTP不需要認證,則不再做其他工作;
?★ 如果SMTP需要認證,則確定在Session中提供嵌入認證信息,還是由3)Transport完成認證過程。
?2)初始化Message實例,填充相關信息;
?3)初始化Transport實例,連接到遠程SMTP服務器,發送郵件。
?在初始化Transport實例時也有兩種情況:
?★ 如果SMTP不需要認證,可以直接調用send()函數發送郵件,應用服務器會在后臺調用connect()函數完成誰,進行郵件發送;
?★ 如果SMTP需要認證,需要調用connect()函數,并提供認證需要的用戶名/密碼,才可以正確發送郵件。
?
1. javax.mail.Session的初始化
1.1. 使用JNDI初始化(配置JavaMail的JNDI)
在Apusic的J2EE應用中找到apusic-application.xml文件,增加<mail-session>部分,示例如下:
<apusic-application>
?<module uri="web.war">
??<web />
?</module>
?<mail-session>
??<jndi-name>javamail/myMail</jndi-name>
??<property name="mail.transport.protocol" value="smtp" />
??<property name="mail.smtp.host" value="smtp.163.com" />
??<property name="mail.smtp.user" value="user" />
??<property name="mail.smtp.password" value="password" />
??<property name="mail.smtp.auth" value="true" />
??<property name="mail.from" value="user@163.com" />
?</mail-session>
</apusic-application>
1.1.1. 通過JNDI找到JavaMail
1.1.1.1. 使用遠程訪問獲得JavaMail
?Hashtable env=new Hashtable();
?env.put(Context.INITIAL_CONTEXT_FACTORY,"com.apusic.naming.jndi.CNContextFactory");
?env.put(Context.PROVIDER_URL,"iiop://localhost:6888");
?//插入相關驗證信息
?env.put(Context.SECURITY_CREDENTIALS,"admin" ) ;
?env.put(Context.SECURITY_PRINCIPAL,"admin");
?Context initCtx=new InitialContext(env);
?System.out.println(initCtx.PROVIDER_URL);
?//通過RMI 取得
?Session myMailSession = (Session) initCtx.lookup("javamail/myMailNoAuth");
1.1.1.2. 使用Apusic默認方式獲得JavaMail
?Context initCtx = new InitialContext();
?Session myMailSession = (Session) initCtx.lookup("javamail/myMailNoAuth");
?System.out.println(myMailSession.getProperty("mail.smtp.host"));
?
1.1.2. 通過資源注入配置JavaMail
?@Resource(mappedName = "javamail/myMailAuth", type = javax.mail.Session.class, shareable = true, authenticationType = Resource.AuthenticationType.CONTAINER, description = "my email with auth")
?private Session myAuthMailSession;
或者
?@Resource(mappedName = "javamail/myMailAuth")
?private Session myAuthMailSession;
1.2. 在代碼中初始化
1.2.1. 無須認證的初始化
?final Properties props = new Properties();
?props.put("mail.transport.protocol", "smtp");
?props.put("mail.smtp.auth", "false");
?props.put("mail.smtp.host", "localhost");
?Session myMailSession = Session.getInstance(props);
1.2.2. 需要認證的初始化(Session實例構造時提供認證支持)
?final Properties props = new Properties();
?props.put("mail.transport.protocol", "smtp");
?props.put("mail.smtp.auth", "true");
?props.put("mail.smtp.host", "smtp.163.com");
?Session myMailSession = Session.getInstance(props, new Authenticator() {
??public PasswordAuthentication getPasswordAuthentication() {
???return new PasswordAuthentication("user", "password");}?});
1.2.3. 需要認證的初始化(Session配置參數提供認證支持)
?myMailSession.setPasswordAuthentication(
??new URLName(props.getProperty("mail.transport.protocol")+"://"+??
???????????????? props.getProperty("mail.smtp.user")+"@"+??
???????????????? props.getProperty("mail.smtp.host")),??
??????? new PasswordAuthentication(props.getProperty("mail.smtp.user"),??
???????????????? props.getProperty("mail.smtp.password")));??
1.2.4. 需要認證的初始化(Transport配置參數提供認證支持)
??// 發送郵件
??javax.mail.Transport myTransport = myMailSession.getTransport("smtp");
??myTransport.connect("smtp.163.com", "user", "password");
??myTransport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
??myTransport.close();
???
1.4. 對Session調試的配置
●?可以在mail-session中加入<property name="mail.debug" value="true" />
●?可以在Session初始化前加入props.put("mail.debug", "true");
●?可以在Session初始化后,通過代碼控制myMailSession.setDebug(true);
1.5. Properties的解釋
◆?mail.store.protocol:用于檢索郵件的協議
◆?mail.transport.protocol:用于傳送郵件的協議
◆?mail.host:默認的主機名,默認是本地計算機。
◆?mail.user:默認的用戶名。
◆?mail.from:默認的返回地址。
◆?mail.debug:是否輸出DEBUG信息。默認為False。
◆?mail.protocol.host:指定協議的主機名,沒有指定就用mail.host。例如:mail.smtp.host=smtp.163.com
◆?mail.protocol.user:指定協議的用戶名,沒有指定就用mail.user。例如:mail.smtp.user=user
◆?mail.protocol.from:指定協議的返回地址,沒有指定就用mail.from。例如:mail.smtp.from=user@163.com
◆?mail.smtp.auth:如果是True,就會登錄SMTP服務器,獲得授權才能發送郵件。默認為False。
2. 通過JavaMail發送郵件
2.1. 通過無須認證的SMTP發郵件
??final Properties props = new Properties();
??props.put("mail.transport.protocol", "smtp");
??props.put("mail.smtp.auth", "false");
??props.put("mail.smtp.host", "localhost");
??try {
???Session myMailSession = Session.getInstance(props);
???myMailSession.setDebug(true); // 打開DEBUG模式
???Message msg = new MimeMessage(myMailSession);
???msg.setFrom(new InternetAddress("user@163.com"));
???msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("zhuyuanxiang@apusic.com"));
???msg.setContent("I have a email test!", "text/plain");
???msg.setSentDate(new java.util.Date());
???msg.setSubject("Test");
???msg.setText("This is a test!\n");
???System.out.println("1.Please wait for sending one...");
???// 發送郵件
???// javax.mail.Transport.send(msg); // 與下面四行的功能一樣
???javax.mail.Transport myTransport = myMailSession.getTransport("smtp");
???myTransport.connect();
???myTransport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
???myTransport.close();
???
???System.out.println("2.Your message had send!");
??} catch (Exception error) {
???System.out.println("*.I am sorry to tell you the fail for " + error);
??}
注:測試可以使用Microsft IIS SMTP 服務,安裝好啟動服務后,還需要進入“IIS管理器”,增加一個“遠程域”,對于“遠程域”的“出站安全性”需要把用戶名和密碼加上(就是平時發郵件時登錄用的用戶名/密碼),否則郵件發不出去。
2.2. 通過需要認證的SMTP發郵件
2.2.1. 需要認證的初始化(Session實例構造時提供認證支持)
?final Properties props = new Properties();
?props.put("mail.transport.protocol", "smtp");
?props.put("mail.smtp.auth", "true");
?props.put("mail.smtp.host", "smtp.163.com");
?try {
??Session myMailSession = Session.getInstance(props, new Authenticator() {
???public PasswordAuthentication getPasswordAuthentication() {
????return new PasswordAuthentication("user", "password");
???}
??});
??myMailSession.setDebug(true);?// 打開DEBUG模式
??InternetAddress address = new InternetAddress("user@163.com");
??String message = "I have a email test!";
??Message msg = new MimeMessage(myMailSession);
??msg.setFrom(address);
??msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("zhuyuanxiang@apusic.com"));
??msg.setContent(message, "text/plain");
??msg.setSentDate(new java.util.Date());
??msg.setSubject("Test");
??msg.setText("This is a test!\n");
??out.println("1.Please wait for sending...");
??
??// 發送郵件
??javax.mail.Transport myTransport = myMailSession.getTransport("smtp");
??myTransport.connect();
??myTransport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
??myTransport.close();
??// javax.mail.Transport.send(msg);?// 注釋上四行,打開這行代碼,功能一樣
??out.println("2.Your message had send!");
?} catch (Exception error) {
??out.println("*.I am sorry to tell you the fail for " + error);
?}
2.2.2. 需要認證的初始化(Session配置參數提供認證支持)
?final Properties props = new Properties();
?props.put("mail.transport.protocol", "smtp");
?props.put("mail.smtp.auth", "true");
?props.put("mail.smtp.host", "smtp.163.com");
?try {
??Session myMailSession = Session.getInstance(props);
??myMailSession.setDebug(true);?// 打開DEBUG模式
??myAuthMailSession.setPasswordAuthentication(
???new URLName("smtp://user@host", new PasswordAuthentication("user","password"));?
??InternetAddress address = new InternetAddress("user@163.com");
??String message = "I have a email test!";
??Message msg = new MimeMessage(myMailSession);
??msg.setFrom(address);
??msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("zhuyuanxiang@apusic.com"));
??msg.setContent(message, "text/plain");
??msg.setSentDate(new java.util.Date());
??msg.setSubject("Test");
??msg.setText("This is a test!\n");
??out.println("1.Please wait for sending...");
??
??// 發送郵件
??javax.mail.Transport myTransport = myMailSession.getTransport("smtp");
??myTransport.connect();
??myTransport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
??myTransport.close();
??// javax.mail.Transport.send(msg);?// 注釋上四行,打開這行代碼,功能一樣
??out.println("2.Your message had send!");
?} catch (Exception error) {
??out.println("*.I am sorry to tell you the fail for " + error);
?}
2.2.3. 需要認證的初始化(Transport配置參數提供認證支持)
??final Properties props = new Properties();
??props.put("mail.transport.protocol", "smtp");
??props.put("mail.smtp.auth", "true");
??try {
???Session myMailSession = Session.getInstance(props);
???myMailSession.setDebug(true); // 打開DEBUG模式
???Message msg = new MimeMessage(myMailSession);
???msg.setFrom(new InternetAddress("user@163.com"));
???msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("zhuyuanxiang@apusic.com"));
???msg.setContent("I have a email test!", "text/plain");
???msg.setSentDate(new java.util.Date());
???msg.setSubject("Test");
???msg.setText("This is a test!\n");
???System.out.println("1.Please wait for sending two...");
???// 發送郵件
???javax.mail.Transport myTransport = myMailSession.getTransport("smtp");
???myTransport.connect("smtp.163.com", "user", "password");
???myTransport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
???myTransport.close();
???// javax.mail.Transport.send(msg); // 這行不能使用。
???System.out.println("2.Your message had send!");
??} catch (Exception error) {
???System.out.println("*.I am sorry to tell you the fail for " + error);
??}
?}
注:資源注入的Session發送郵件時:
無須認證的SMTP,可以參考2.1.
需要認證的SMTP,可以參考2.2.1.
參考:
http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
http://commons.apache.org/email/userguide.html
http://m.tkk7.com/Unmi/archive/2007/06/07/124179.html
http://unmi.blogcn.com/diary,117630488.shtml
Apusic Stduio打包的示例工程。
http://zhuyuanxiang.javaeye.com/topics/download/d6f5c3a9-9cd9-30be-9b64-9e311900b304
備注:本文耗時1周完成。
posted on 2008-09-04 12:11 zYx.Tom 閱讀(1650) 評論(7) 編輯 收藏 所屬分類: 1.Java世界