java 发送邮件(包含附件)


import java.io.File;

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

public class SendMail {
/**
	 * 发送邮件
	 * @param hostname :邮件服务器(stmp.163.com)
	 * @param sender	: 发件人
	 * @param senderPassword :邮箱密码(有部分邮件服务器,需要验证用户信息,例如163)
	 * @param subject	: 邮件主题
	 * @param content	: 邮件内容
	 * @param emails	: 收件人邮箱数组
	 * @param accessories	: 邮件文件数组
	 */
	public static void sendMail(String hostname, String sender,
			String senderPassword, String subject, String content,
			String[] emails, File[] accessories) throws EmailException{
		
		MultiPartEmail email = new MultiPartEmail();//如果要发送带附件的邮件,需使用这个类   
		email.setHostName(hostname);	//指定要使用的邮件服务器 
		email.setAuthentication(sender, senderPassword);	//使用邮件服务器需提供已注册的用户名、密码,保证邮件正常发送
		email.setCharset("utf-8");     //设置编码格式
		StringBuffer sendEmails = new StringBuffer("");
	
		email.setFrom(sender);
        for(int i=0;i<emails.length;i++){
        	if(validateEmail(emails[i])){
        		email.addTo(emails[i]);				//设置收件人   
        		sendEmails.append(emails[i]+";");
        	}
        }

        //如果存在附件,则添加附件
        if(null !=  accessories){
	        for(int i=0;i<accessories.length;i++){
				if(accessories[i].isFile()){
					System.out.println("附件:" + accessories[i].getPath());
					EmailAttachment attachment = new EmailAttachment();
					attachment.setPath(accessories[i].getPath());       
					attachment.setName(accessories[i].getName());
					attachment.setDescription(accessories[i].getName());
					attachment.setDisposition(EmailAttachment.ATTACHMENT);		//附件的类型   
					email.attach(attachment);
				}
	    	}
        }
        
		email.setSubject(subject);//设置主题   
		email.setMsg(content);//设置邮件内容   
		email.send();
		System.out.println("主题[" + subject + "]邮件从[" + sender + "]发送到[" + sendEmails.substring(0, sendEmails.length()-1)+ "]" + ",成功");
	}

}

你可能感兴趣的:(java,apache)