一、首先打開QQ郵箱的SMTP服務,由於QQ郵箱對於通常的用戶都是默認關閉SMTP服務的。html
找到SMTP服務的選項,能夠看到此處默認是關閉的,點擊開啓,而後騰訊會進行一些身份驗證,身份驗證經過之後,騰訊會給出一個用於使用SMTP的16位口令,此處這個口令必定牢記,由於後面要使用SMTP功能必需要用到這個口令,沒有這個口令即便知道QQ郵箱密碼也沒有用,此處未給出口令的截圖,畢竟爲了隱私保密,否則你們均可以登陸使用個人QQ郵箱SMTP服務了。後面咱們將該口令記爲SMTP口令。 java
生成受權碼。服務器
首先,要使用Java的郵箱功能須要javax.mail這個jar包:測試
依賴:spa
<!-- email start --> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> <!-- email end -->
發送郵件代碼:.net
// 建立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);
好了,以上就能夠了。code
若是生產環境不能發送郵件,則要綁定host。orm