Java實作QQ郵件發送
首先我們需要兩個jar包,點選下面即可下載下傳這兩個包:
- JavaMail mail.jar 1.4.5
- JAF(版本 1.1.1) activation.jar
我們這裡采用QQ郵箱發送郵件為例,代碼如下:
package ddd;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.sun.mail.util.MailSSLSocketFactory;
public class SendEmail {
public static void main(String[] args) {
try {
//設定發件人
String from = "[email protected]";
//設定收件人
String to = "[email protected]";
//設定郵件發送的伺服器,這裡為QQ郵件伺服器
String host = "smtp.qq.com";
//擷取系統屬性
Properties properties = System.getProperties();
//SSL加密
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
//設定系統屬性
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
//擷取發送郵件會話、擷取第三方登入授權碼
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "第三方登入授權碼");
}
});
Message message = new MimeMessage(session);
//防止郵件被當然垃圾郵件處理,披上Outlook的馬甲
message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
//郵件标題
message.setSubject("This is the subject line!");
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setText("我發送了檔案給你");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart);
//附件
bodyPart = new MimeBodyPart();
String fileName = "檔案路徑";
DataSource dataSource = new FileDataSource(fileName);
bodyPart.setDataHandler(new DataHandler(dataSource));
bodyPart.setFileName("檔案顯示的名稱");
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("mail transports successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
}
QQ郵箱發送郵件記得要在設定裡面開啟POP3/SMTP服務,然後擷取第三方登入的授權碼。
上面的代碼中啟用了SSL加密,網上很多人說QQ發送郵件不加上SSL加密會報錯,樓主這裡不加也是可以發送的不知道為什麼,但是為了資料安全還是加上了。
有些人發送的郵件會被當做垃圾郵件處理,這裡我也進行了處理,給郵件頭披上Outlook的馬甲,當然也可以将郵件内容以HTML格式發送,以防止被當成垃圾郵件。
上述就是一個簡單的java發送QQ帶附件的郵件的代碼。