Guest User

Untitled

a guest
Nov 19th, 2017
391
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. import java.util.Properties;
  2.  
  3. import javax.mail.Authenticator;
  4. import javax.mail.Message;
  5. import javax.mail.MessagingException;
  6. import javax.mail.PasswordAuthentication;
  7. import javax.mail.Session;
  8. import javax.mail.Transport;
  9. import javax.mail.internet.InternetAddress;
  10. import javax.mail.internet.MimeMessage;
  11.  
  12. public class Email {
  13.  
  14. public static void main(String[] args) throws MessagingException {
  15.  
  16. String host = "smtp.gmail.com";
  17. int port = 465;
  18. final String username = "jason19951003@gmail.com";//smtp帳號
  19. final String password = "***";//smtp密碼
  20.  
  21. Properties props = new Properties();
  22. props.put("mail.smtp.host", host);
  23. props.put("mail.smtp.auth", "true");
  24. props.put("mail.smtp.socketFactory.port", "465");
  25. props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  26. props.put("mail.smtp.port", port);
  27.  
  28. Session session = Session.getInstance(props, new Authenticator() {
  29. protected PasswordAuthentication getPasswordAuthentication() {
  30. return new PasswordAuthentication(username, password);
  31. }
  32. });
  33.  
  34. Message message = new MimeMessage(session);
  35. message.setFrom(new InternetAddress("jason19951003@gmail.com"));//設定寄件人帳號
  36. message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("b19951003@gmail.com"));//設定收件人帳號
  37. message.setSubject("測試HTML寄信.");//設定主旨
  38. //message.setText("test");//寄送純文字
  39. message.setContent("<h1>This is a test</h1>", "text/html; charset=utf-8");//寄送html格式的email
  40.  
  41. Transport transport = session.getTransport("smtp");
  42. transport.connect(host, port, username, password);
  43.  
  44. Transport.send(message);
  45. transport.close();
  46. System.out.println("寄送email結束.");
  47. }
  48.  
  49. }
Add Comment
Please, Sign In to add comment