這裏的Demo簡單來,希望給第一次試用的你幫助。
. 1,試用網易郵箱發送郵件:
//網易
public static Session getNetEasySession() {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.host", "smtp.163.com");
props.setProperty("mail.smtp.port", "25");
props.setProperty("mail.smtp.auth", "true");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM, "panda0920");
}
});
return session;
}
. 2,google郵箱發送郵件:
public static Session getGMailSession() {
Properties props = new Properties();
// props.put("mail.smtp.host", "smtp.gmail.com");
// props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// props.put("mail.smtp.socketFactory.fallback", "false");
// props.put("mail.smtp.port", "465");
// props.put("mail.smtp.socketFactory.port", "465");
// props.put("mail.smtp.auth", "true");
//當前用這種方式。
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM, "panda0920");
}
});
return session;
}
來一個main測試下
private static final String FROM = "[email protected]";
public static void sendAccountActivateEmail(String email,String vaildCode)throws Exception {
Session session = getGMailSession();
MimeMessage message = new MimeMessage(session);
message.setSubject("test");
message.setSentDate(new Date());
message.setFrom(new InternetAddress(FROM)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
// message.setContent("test11111",","text/html;charset=utf-8"); // 發送郵件
Transport.send(message);
}
public static void main(String args[]){
try { sendAccountActivateEmail("[email protected]","test");
} catch (Exception e) {
e.printStackTrace();
}
}
注意項:不管是網易還是谷歌郵箱都需要登錄郵箱設置安全登錄之類的,比如: