以下是我參考GAE 修改的code, 是一個servlet 所以還要記得設定web.xml 這裡就不多說了
注意這裡 setFrom 要用GAE 開發者的gmail 不然是會寄不出去也不會有錯誤訊息
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class SendMail extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws IOException {
 req.setCharacterEncoding("UTF-8");
     Properties props = new Properties();
     Session session = Session.getDefaultInstance(props, null);
     String msgBody = "Hello ";
     try {
         Message msg = new MimeMessage(session);
         msg.setFrom(new InternetAddress("Admin@gmail.com"));
         msg.addRecipient(Message.RecipientType.TO,
                          new InternetAddress("xxx@gmail.com", "Mr. User"));
         msg.setSubject("Your Example.com account has been activated");
         msg.setText(msgBody);
         Transport.send(msg);
     } catch (AddressException e) {
         // ...
     } catch (MessagingException e) {
         // ...
     } catch (UnsupportedEncodingException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}
  System.out.println("Message sent.");
  resp.setContentType("text/plain");
  resp.getWriter().println("Message sent.");
}
}
附註 InternetAddress函式 說明
new InternetAddress("email","想要給的名稱");
詳細可以參考 GAE 的說明
 
沒有留言:
張貼留言