注冊郵箱
去163郵箱(或其他郵箱)注冊一個郵箱,并開啟SMTP授權碼。
程式
需要注意的是,由于阿裡雲伺服器不讓使用預設的25端口,是以會出現Windows下測試發送郵件成功,Linux伺服器下發送郵件卻出錯的問題(broke pipe、timeout、can not connect等)。解決辦法是使用帶SSL的465端口。
package com.kuyuntech.util;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 郵件發送工具類
*/
public class EmailUtils {
/**
* 發送郵件的方法
* @param toUser :收件人
* @param title :标題
* @param content :内容
*/
public static void sendMail(String toUser,String title,String content) throws Exception {
// 你自己的郵箱和授權碼
final String username = "[email protected]";//自己的郵箱
final String password = "xxxxxxxxxx";//授權碼,需要登入163郵箱,在設定裡設定授權碼。授權碼用于替代密碼
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.163.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");// 不能使用25端口,因為阿裡雲伺服器禁止使用25端口,是以必須使用ssl的465端口
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}});
// -- 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(toUser,false));
msg.setSubject(title);
msg.setText(content);
msg.setSentDate(new Date());
Transport.send(msg);
}
public static void main(String[] args) throws Exception {
sendMail("[email protected]","标題","Hello!");
}
}