1、首先打開QQ郵箱的SMTP服務,因為QQ郵箱對於一般的用戶都是默認關閉SMTP服務的。
找到SMTP服務的選項,可以看到此處默認是關閉的,點擊開啟,然后騰訊會進行一些身份驗證,身份驗證通過以后,騰訊會給出一個用於使用SMTP的16位口令,此處這個口令一定牢記,因為后面要使用SMTP功能必須要用到這個口令,沒有這個口令即使知道QQ郵箱密碼也沒有用,此處未給出口令的截圖,畢竟為了隱私保密,不然大家都可以登錄使用我的QQ郵箱SMTP服務了。后面我們將該口令記為SMTP口令。
生成授權碼。
首先,要使用Java的郵箱功能需要javax.mail這個jar包:
依賴:
<!-- email start --> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> <!-- email end -->
發送郵件代碼:
// 創建Properties 類用於記錄郵箱的一些屬性 Properties props = new Properties(); // 表示SMTP發送郵件,必須進行身份驗證 props.put("mail.smtp.auth", "true"); //此處填寫SMTP服務器 props.put("mail.smtp.host", "smtp.qq.com"); //端口號,QQ郵箱給出了兩個端口,但是另一個我一直使用不了,所以就給出這一個587 props.put("mail.smtp.port", "587"); // 此處填寫你的賬號 props.put("mail.user", "xxxxxxx@qq.com"); // 此處的密碼就是前面說的16位STMP口令 props.put("mail.password", "xxxxxxxxxxxxxxxxxxx"); // 構建授權信息,用於進行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 mailSession = Session.getInstance(props, authenticator); // 創建郵件消息 MimeMessage message = new MimeMessage(mailSession); // 設置發件人 InternetAddress form = new InternetAddress( props.getProperty("mail.user")); message.setFrom(form); // 設置收件人的郵箱 InternetAddress to = new InternetAddress("xxxxxxxx@qq.com"); message.setRecipient(RecipientType.TO, to); // 設置郵件標題 message.setSubject("測試郵件"); // 設置郵件的內容體 message.setContent("這是一封測試郵件", "text/html;charset=UTF-8"); // 最后當然就是發送郵件啦 Transport.send(message);
好了,以上就可以了。
如果生產環境不能發送郵件,則要綁定host。