搜尋此網誌

2013年9月26日 星期四

【Java】實作透過Gmail SMTP Server 發送信件 版本二

本實作是改寫上篇透過SSL加密寄信;新增TLS以及None的方法。
因為Gmail已經不提供None(不加密)的寄信,所以在執行None方法時,會出現問題。

這部分除了改寫原本code以外,新增一個class放置gmail secure設定以及對應的port number。

Email.java


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;

import option.GmailSetting.*;

public class Email {

	String subject;
	String content;
	String receiver;
	SecureType secureType;

	Email(SecureType secureType) {
		subject = "";
		content = "";
		receiver = "";
		this.secureType = secureType;
	}

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

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

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

	Properties generateRequireProp() {

		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		String portNumber = GmailSetting.PORT_NUMBER.get(secureType.value()).toString();

		// set up gmail smtp information
		Properties props = new Properties();
		props.setProperty("mail.smtp.host", "smtp.gmail.com");
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.smtp.port", portNumber);

		if (this.secureType != SecureType.None) {
			if (this.secureType == secureType.TLS)
				props.setProperty("mail.smtp.starttls.enable", "true");
			else {
				props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
				props.setProperty("mail.smtp.socketFactory.fallback", "false");
				props.setProperty("mail.smtp.socketFactory.port", portNumber);
				props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			}
		}
		return props;
	}

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

		System.out.println("Start to send email");
		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 + "by " + secureType.value() + " connection.", "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(SecureType.SSL);
		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.sendMail())
			System.out.println("Success to send email!");

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

	}
}


GmailSetting.java

package option;

import java.util.HashMap;
import java.util.Map;

public class GmailSetting {
	SecureType secureType;

	public GmailSetting() {
		// TODO Auto-generated constructor stub
	}

	public enum SecureType {
		None, SSL, TLS;

		public String value() {
			return name();
		}

		public static SecureType fromValue(String v) {
			return valueOf(v);
		}
	}

	static final Map<String, Integer> PORT_NUMBER = new HashMap<String, Integer>() {
		private static final long serialVersionUID = -5199045595923410899L;
		{
			put("None", 25);
			put("SSL", 465);
			put("TLS", 587);
		}
	};

}

沒有留言: