qq郵箱提供smtp服務分兩種,一種是企業郵箱(默認是開啓的);另外一種是個人郵箱(需要自己開啓,並且獲得認證碼)
如下代碼實現,這個是默認是基於企業郵箱的實現:
package com.test;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.Date;
import java.util.Properties;
public class TestSendMail {
public static void main(String[] args) throws Exception {
String protocol = "smtp";
String userName = "****@***.cn";//你的郵箱地址
//qq 企業郵箱的鏈接方式
String smtpServer ="smtp.exmail.qq.com";
String password = "*****";
//qq 個人郵箱鏈接方式
//String password = "*********"; qq個人郵箱需要自己開啓 smtp服務,需要發短信驗證,開啓完成會給你一個認證碼
//String smtpServer = "smtp.qq.com"; qq個人郵箱服務
String from ="******@*****.cn";
String to = "*******@***.com";
Properties props = new Properties();
props.setProperty("mail.transport.protocol", protocol);
props.setProperty("mail.host", smtpServer);
props.setProperty("mail.smtp.auth", "true");
props.put("mail.user", userName);
props.put("mail.password", password);
// 構建授權信息,用於進行SMTP進行身份驗證
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(props, authenticator);
session.setDebug(true);//可以看調適信息
//創建代表郵件的MimeMessage對象
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSentDate(new Date());
String subject = "測試郵件";
String body = "authenticator 測試";
// 使用指定的base64方式編碼,並指定編碼內容的字符集是gb2312
message.setSubject(MimeUtility.encodeText(subject)); //B爲base64方式
message.setText(body); //B爲base64方式
//保存並且生成郵件對象
message.saveChanges();
//建立發送郵件的對象
Transport.send(message);
}
}