利用apache commons-email发送邮件

本文利用apaceh commons-email发送邮件,记录一下,赶紧总结完下班了哦。。哈哈

所需要引入的包:commons-email-1.2.jar(apache官网下载),mail.jar(sun官网下载),activation.jar(sun官网下载,如果你使用的jdk是1.6以上,这个包就可以不下载了,因为jdk1.6已经包括了)

直接上代码吧。

PropertiesUtils类:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 *@author liudonggan Email:[email protected]
 *@date 2011-7-20 上午11:29:14
 *@version v1.0
 **/
public class PropertiesUtils {

	private static InputStream inputStream=null;

	public static String getProperties(String propertyName) throws Exception
	{
		String _propertyName="";
		inputStream=PropertiesUtils.class.getClassLoader().getResourceAsStream("config.properties");
		Properties p = new Properties();   
		try {   
			p.load(inputStream);   
		} catch (IOException e1) {
			inputStream.close();
		}
		_propertyName=p.get(propertyName).toString();
  		inputStream.close();
  		return _propertyName;
	}
}

 

MailUtils类:

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.MultiPartEmail;

import com.ys.product.bean.UserEmail;
/**
 *@author liudonggan Email:[email protected]
 *@date 2011-7-20 上午10:49:41
 *@version v1.0
 **/
public class MailUtils {

	/**
	  * sendMail 方法
	  * <p>方法说明:</p>
	  * @param path附件路迳
	  * @param subject邮件主题
	  * @param msg邮件内容
	  * @throws Exception
	  * @return void
	  * @author liudonggan Email:[email protected]
	  * @date 2011-7-20 上午11:39:37
	*/
	public void sendMail(String path,List<UserEmail> emails,String subject,String msg) throws Exception
	{
		MultiPartEmail email = new MultiPartEmail();
		//SimpleEmail email = new SimpleEmail();
		// 设置邮件编码
		email.setCharset("UTF-8");
		// 设置邮件服务器
		email.setHostName(PropertiesUtils.getProperties("mail.smtp"));
		// 设置登录邮件服务器用户名和密码
		email.setAuthentication(PropertiesUtils.getProperties("mail.email"), PropertiesUtils.getProperties("mail.pwd"));
		// 添加收件人
		for(UserEmail _email:emails)
		{
			email.addTo(_email.getEmailName(), _email.getTitle());
		}
		// 设置发件人
		email.setFrom(PropertiesUtils.getProperties("mail.email"), "liudonggan");
		// 设置邮件标题
		email.setSubject(subject);
		// 设置邮件正文内容
		email.setMsg(msg);
		// 要发送的附件
		EmailAttachment attachment = new EmailAttachment();
		File file = new File(path);
		attachment.setPath(file.getPath());
		attachment.setName(file.getName());
		// 设置附件描述
		attachment.setDescription(subject);
		// 设置附件类型
		attachment.setDisposition(EmailAttachment.ATTACHMENT);
		// 添加附件
		email.attach(attachment);
		// 发送邮件
		email.send();
	}
	public static void main(String[] arg) throws Exception
	{
		MailUtils mail=new MailUtils();
		UserEmail _email=new UserEmail();
		_email.setEmailName("[email protected]");
		_email.setTitle("XX标题");
		List<UserEmail> emails=new ArrayList<UserEmail>();
		emails.add(_email);
		mail.sendMail("c:\\test.pdf",emails,"XX标题","内容");
	}
}

  

你可能感兴趣的:(apache commons)