好處是你只要有一個有提供外部SMTP的信箱,
不用自己架伺服器,
缺點是在發信的時候需要一些時間,
以下我是使用GMAIL為例
try{
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.gmail.com"); //設定使用GMAIL的SMTP
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465"); //465是GMAIL提供的SMTP PORT
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
String username = GMAIL帳號
String password = GMAIL密碼
Session sendMailSession;
Store store;
Transport transport;
sendMailSession = Session.getInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username ,password );
}});
// -- Create a new message --
Message msg = new MimeMessage(sendMailSession);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress("寄件者信箱"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("收件者信箱",false));
msg.setSubject("標題");
msg.setText("內容");
msg.setSentDate(new Date());
Transport.send(msg);
// system.out.println("Message sent.");
// -- Set the FROM and TO fields --
}
catch(MessagingException m)
{
out.println(m.toString());
}
沒有留言:
張貼留言