Send Mail

Read XML (Using XMLConfiguration)

需 import 下列 jar:

commons-email-1.2.jar

mail.jar

程式位置結構如下列:

image

Mail.java



import java.util.Iterator;
import java.util.List;

import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.SimpleEmail;

public class Mail
{
	private static final String CHAR_SET = "utf-8";
	private static final String HOST_NAME = "xxx.yyy.com.tw";
	
	public static void sendSimpleMail(String subject, String from, List toList, String content) throws EmailException
	{
		Email email = new SimpleEmail();
		email.setCharset(CHAR_SET);
		email.setHostName(HOST_NAME);
		email.setFrom(from);
		email.setSubject(subject);
		for(Iterator iter = toList.iterator(); iter.hasNext(); )
		{
			email.addTo((String)iter.next());
		}
		email.setMsg(content);
		
		email.send();
	}
	
	public static void sendHtmlMail(String subject, String from, List toList, String content) throws EmailException
    {
        HtmlEmail email = new HtmlEmail();
        email.setCharset(CHAR_SET);
        email.setHostName(HOST_NAME);
        email.setFrom(from);
        email.setSubject(subject);
        for(Iterator iter = toList.iterator(); iter.hasNext(); )
        {
            email.addTo((String)iter.next());
        }
        email.setHtmlMsg(content);
        
        email.send();
    }
}

DemoMain.java



import java.util.ArrayList;
import org.apache.commons.mail.EmailException;

public class DemoMain 
{
	public static void main(String[] args)
	{
		ArrayList<String> mailToList = new ArrayList<String>();
		mailToList.add("mark@xxx.com");
		mailToList.add("jeff@xxx.com");
		
		String mailSubject = "TEST Notice";
		String mailFrom    = "xxx@yyy.com";
		String mailHtmlContent = "<p><b>使用者您好,</b></p><br/>" +
				                 "<font size=5 color=#FF0000>Hello World!</font>";
		String mailSimpleContent = "Hello World!";
		try 
		{
			Mail.sendHtmlMail  (mailSubject, mailFrom, mailToList, mailHtmlContent);   //支援 HTML 格式內容
			Mail.sendSimpleMail(mailSubject, mailFrom, mailToList, mailSimpleContent); //不支援 HTML 格式內容
		}
		catch (EmailException ex1) 
		{
			System.out.println(ex1.getMessage());
		}
		catch (Exception ex2) 
		{
			System.out.println(ex2.getMessage());
		}
	}
}