java 通過QQ郵箱發郵件
public static void main(String[] args) throws Exception {
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.qq.com");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
// 使用ssl加密傳輸,解決ssl證書報錯問題
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
final String username = "[email protected]";//發件人郵箱
final String password = "xcvbgtrejpouhl";//開啟QQ郵箱smtp功能給的授權碼,當qq郵箱密碼使用
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);//在控制檯打印發送郵件日誌資訊
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(username));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]", false));//收件人郵箱
msg.setSubject("驗證碼");//郵件標題(郵件標題儘量別用test,避免被QQ郵箱當垃圾扔進垃圾桶)
msg.setText("184698");//郵件文字內容
msg.setSentDate(new Date());
Transport.send(msg);
System.out.println("Message sent successful");
}