直接使用java來調用mail.jar的API應用實例

直接使用java來調用mail.jar的API應用實例
/** 修改歷史
* 日期 作者 修改內容
* -----------------------------------------------------------------------------
* 2008-11-10 李小強 創建CLASS
*/
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
/**
* <p>Title:領頭鳥科技全球信息諮詢服務與解決方案提供商自主研發產品,直接使用java來調用mail.jar的API應用實例</p>
* <p>Copyright: Copyright (c) 2008</p>
* <p>Company: 領頭鳥科技全球信息諮詢服務與解決方案提供商</p>
* @author 李小強
* <p>author E-Mail: [email protected]
* <p>http://leaderbird.blogcn.com
* <p>@version 2.1</p>
*
*/
public class JavaMailTest {
public static void main (String args[]) throws Exception {

String host = "mail.163.com"; //發件人使用發郵件的電子信箱服務器
String from = "[email protected]"; //發郵件的出發地(發件人的信箱)
String to = "[email protected]"; //發郵件的目的地(收件人信箱), Get system properties
Properties props = System.getProperties(); // Setup mail server
props.put("mail.smtp.host", host); // Get session
props.put("mail.smtp.auth", "true"); //這樣才能通過驗證
MyAuthenticator myauth = new MyAuthenticator("myname", "mypwd");
Session session = Session.getDefaultInstance(props, myauth);
// session.setDebug(true);
// Define message
MimeMessage message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress(from));
// Set the to address
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set the subject
message.setSubject("測試程序!");
// Set the content
message.setText("這是用java寫的發送電子郵件的測試程序!");
message.saveChanges();
Transport.send(message);
}
}

//校驗發信人權限的方法
// package com.hyq.test;
//
// import javax.mail.PasswordAuthentication;

class MyAuthenticator extends javax.mail.Authenticator {
private String strUser;
private String strPwd;
public MyAuthenticator(String user, String password) {
this.strUser = user;
this.strPwd = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(strUser, strPwd);
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章