21 July 2012
用Java寄MAIL不是這篇的重點,
反正主要是用JavaMail API就是了!
code 如下,就不多做說明:
            final String MAIL_HOST = "smtp.gmail.com";   // gmail的smtp
final String GMAIL_ACCOUNT = "XXXXX@gmail.com"; //gmail account
final String GMAIL_PASSWORD = "XXXXX"; // gmail pwd
final String strRecipients = "xxx@gmail.com"; // 收件人
final String strSender = "ejustmake@gmail.com"; // 寄件人名稱
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", MAIL_HOST);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");//smtp PORT 528好像也可以
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");


// Authenticate的動作
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
String account = GMAIL_ACCOUNT;
String pass = GMAIL_PASSWORD;
return new PasswordAuthentication(account, pass);
}
});


MimeMessage message = new MimeMessage(session);
message.setstrSender(new InternetAddress(strSender));
message.setSubject("Mail標題", "UTF-8");
message.setContent(strBody, "text/html;charset=utf-8");//這裡用text/html就可以傳網頁的內容!

message.setstrRecipients(Message.RecipientType.TO, InternetAddress.parse(strRecipients));
Transport.send(message);



然後這段code在任何一台host上,甚至local上都可以run,
但是打包成war搬上去ec2以後就出現AuthenticationFail問題.....
恩,主要問題是被Google擋住了!
因為我用的帳號平常是在台灣進行登入!
可是搬上去ec2以後...因為主機是在美國,
所以變成IP變成從美國登入...
會被擋住,但是GOOGLE會發一封MAIL給你,
內容如下圖,反正就是詢問這是不是你,如果是你,
就點下圖中的紅色框框,點了以後按照步驟做,
然後再用你的應用程式登入一次,就成功了!










blog comments powered by Disqus