必須下載sun公司的JavaMail API包,地址爲:http://java.sun.com/products/javamail/ 並將相關包(jar文件)加到CLASSPATH中。
或者如果安裝j2ee則將j2ee.jar加入classpath即可。
源程序如下,替換紅色部分即可使用。
對您有幫助或有問題請來信討論:[email protected]
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
/**
* <p>Title: java mail</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author petehero
* @version 1.0
*/
public class SendMail
{
public SendMail()
{
}
public void send(){
try
{
Properties props = new Properties();
Session sendMailSession;
Store store;
Transport transport;
props.put("mail.smtp.auth","true");
props.put("mail.smtp.host", "smtp.yourmail.com"); //smtp主機名。
props.put("mail.smtp.user","[email protected]"); //發送方郵件地址。
props.put("mail.smtp.password","888888"); //郵件密碼。
PopupAuthenticator popA=new PopupAuthenticator();//郵件安全認證。
PasswordAuthentication pop = popA.performCheck("username","888888"); //填寫用戶名及密碼
sendMailSession = Session.getInstance(props, popA);
Message newMessage = new MimeMessage(sendMailSession);
newMessage.setFrom(new InternetAddress("[email protected]"));
newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); //接收方郵件地址
newMessage.setSubject("郵件主題");
newMessage.setSentDate(new Date());
String mailContent;
mailContent="你好!/n/n";
mailContent+="/t郵件正文/n/n";
mailContent+=new Date().toLocaleString();
newMessage.setText(mailContent); //郵件正文
transport = sendMailSession.getTransport("smtp");
transport.send(newMessage);
}
catch (MessagingException ex)
{
ex.printStackTrace();
}
}
public static void main(String[] args)
{
SendMail sml = new SendMail();
sml.send();
}
public class PopupAuthenticator extends Authenticator{
String username=null;
String password=null;
public PopupAuthenticator(){}
public PasswordAuthentication performCheck(String user,String pass){
username = user;
password = pass;
return getPasswordAuthentication();
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
}