搜尋此網誌

2013年9月25日 星期三

【Java】實作透過Gmail SMTP Server 發送信件(利用javamail API)

連線加密方式有三種:
  1. None(不加密)
  2. TLS , port number:587
  3. SSL , port number:465 (參考網址)
這裡實作以SSL加密寄送信件。
需要包裝javamail API到lib,下例用JavaMail 1.4.2進行包裝。

注意: 若發送信件內容,不只是純文字,而有用到html、CSS。
經過測試後,確定gmail 不支援部分block css內容,若可行,請寫inline css。
其他html email設計的要素,參考:
  1. Guide to CSS support in email 
  2. How HTML email works, basic concepts, best practices, tips and tricks

package option;

import java.text.DateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Email {

 String subject;
 String content;
 String receiver;

 Email() {
  subject = "";
  content = "";
  receiver = "";
 }

 public void setSubject(String subject) {
  this.subject = subject;
 }

 public void setContents(String content) {
  this.content = content;
 }

 public void setReceiverAddress(String address) {
  this.receiver = address;
 }

 static Properties generateRequireProp() {

  final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
  
  // set up gmail information
  Properties props = new Properties();
  props.setProperty("mail.smtp.host", "smtp.gmail.com");
  props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
  props.setProperty("mail.smtp.socketFactory.fallback", "false");
  props.setProperty("mail.smtp.socketFactory.port", "465");
  props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  props.setProperty("mail.smtp.auth", "true");
  props.setProperty("mail.smtp.port", "465");

  return props;
 }

 boolean send() {
  if (receiver.equals("")) {
   System.out.println("Email Receiver is empty.");
   return false;
  }

  Properties props = generateRequireProp();
  final String username = "sender@gmail.com";
  final String password = "sender password";

  // build the new session service
  Session session = Session.getInstance(props, new Authenticator() {
   protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(username, password);
   }
  });

  try {   
   Message message = new MimeMessage(session);
   
   //build the mail of sender , receiver and subject info 
   message.setFrom(new InternetAddress(username));
   message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver, false));
   message.setSubject(subject);
   
   // set mime content
   MimeMultipart multipart = new MimeMultipart();
   MimeBodyPart messageBodyPart = new MimeBodyPart();
   messageBodyPart.setContent(content, "text/html;charset=utf-8");
   multipart.addBodyPart(messageBodyPart);
   message.setContent(multipart);

   Transport.send(message);
   System.out.println("Done");

  } catch (Exception e) {
   throw new RuntimeException(e);
  }
  return true;

 }

 public static void main(String args[]) {

  Email email = new Email();
  email.setSubject("Test mail "+DateFormat.getDateTimeInstance().format(new Date(System.currentTimeMillis())));
  email.setContents("This is a test e-mail by javamail library");
  email.setReceiverAddress("receiver@mail");

  if (email.send())
   System.out.println("Sending is successing");

  else
   System.out.println("Error");

 }
}

沒有留言: