?java中使用qq進行郵件發送郵件的時候,需要在qq郵箱中開啟smtp,獲取授權碼,具體詳情可以登錄http://service.mail.qq.com/cgi-bin/help?id=28進行查看
盡量不要使用qq郵箱進行發送郵件。比較麻煩,后期持續更新qq發送
? ? ? 注意:本教程在mac下進行操作的,倒入jar的同時不會像windows那樣的麻煩,不需要手動把mail.jar和activation.jar文件添加到您的 CLASSPATH 中。要是windows別忘記添加路徑!
使用163進行發送郵件:
第一步:導入activation.jar、mail.jar包到工程中
您可以從 Java 網站下載最新版本的JavaMail,打開網頁右側有個Downloads鏈接,點擊它下載。
您可以從 Java 網站下載最新版本的JAF(版本 1.1.1)。
你也可以使用本站提供的下載鏈接:
第二步:上代碼
packageEmploee;
importjava.io.*;
importjava.net.PasswordAuthentication;
importjava.util.*;
importjavax.mail.*;
importjavax.mail.internet.*;
importsun.security.util.Password;
importjavax.activation.*;
publicclassEmploee {
publicEmploee() {
//TODOAuto-generated constructor stub
}
publicstaticvoidmain(String[]args) {
//TODOAuto-generated methodstu
Stringto="對方的郵箱賬戶";//對方的郵箱賬戶
Stringfrome="自己的@163.com";
Stringpsd="密碼";
// 指定發送郵件的主機為localhost
Stringhost="smtp.163.com";
// 獲取系統屬性
Propertiesproperties= System.getProperties();
// 設置郵件服務器
properties.setProperty("mail.smtp.host",host);
properties.put("mail.smtp.auth","true") ;//是否設置驗證碼
MyAuthenticatormyauth=newMyAuthenticator(frome,psd);
// 獲取默認session對象
Sessionsession= Session.getDefaultInstance(properties,myauth);
try{
// 創建默認的 MimeMessage 對象
MimeMessagemessage=newMimeMessage(session);
// Set From: 頭部頭字段
message.setFrom(newInternetAddress(frome));
// Set To: 頭部頭字段
message.addRecipient(Message.RecipientType.TO,
newInternetAddress(to));
// Set Subject: 頭部頭字段
message.setSubject("這個是重要的郵件");
// 設置消息體
message.setText("我靠,qq郵箱好像需要進行驗證!!!夜晚去鄭大打球,我新學會一個姿勢");
// 發送消息
Transport.send(message);
System.out.println("已發送!");
}catch(MessagingExceptionmex) {
mex.printStackTrace();
}
}
staticclassMyAuthenticator
extendsjavax.mail.Authenticator {
publicStringstrUser;
publicStringstrPwd;
publicMyAuthenticator(Stringuser, Stringpassword) {
this.strUser=user;
this.strPwd=password;
}
protectedjavax.mail.PasswordAuthentication getPasswordAuthentication() {
returnnewjavax.mail.PasswordAuthentication(strUser,strPwd);
}
}
}