Java 邮件发送

这里采用的时候apache的组建首先依赖 commons-email-1.2.jar、mail.jar、activation.jar(这个貌似不加也可以)这三个包

下面是操作代码

import java.io.IOException;

import java.net.MalformedURLException;
import java.net.URL;

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



public class Mail {
	//这个是你自己申请的账号,用来发送邮件的
	static final String FROM_USER_NAME = "[email protected]"; //邮箱用户名
	static final String FROM_USER = "xxxxxx";//
	static final String FROM_USER_PASSWORD="xxxxx";//登陆密码
	/**
	 * 
	 * @param to  收信人地址 
	 * @param subject  主题 
	 * @param body  内容 
	 * @throws MalformedURLException 
	 */
	public static void send(String to,String subject, String body ) throws MalformedURLException {
		try { 
			HtmlEmail email = new HtmlEmail();
			email.setHostName("smtp.163.com");// 设置发信的smtp服务器
			email.setFrom(FROM_USER_NAME, FROM_USER);// 设置发信的邮件帐号和发信人
			email.setAuthentication(FROM_USER_NAME,FROM_USER_PASSWORD);// 如果smtp服务器需要认证的话,在这里设置帐号、密码
			
			//附件 可以有多个
			EmailAttachment ea = new EmailAttachment();
		//	ea.setPath("c:/a.xls");
		//  email.attach(new File("c:/a.xls"));
			ea.setURL(new URL("http://www.7160.com//uploads/allimg/130901/7-130Z1144312.jpg"));
			ea.setName("图片.jpg"); //这里加后缀
			ea.setDescription("美女图片");
			email.attach(ea);
			 
			
			
			email.addTo(to);
	   //	email.addBcc("[email protected]"); 抄送
			email.setSubject(subject);
			email.setCharset("utf-8");
			email.setHtmlMsg(body); //发送含有html字符的
			
			email.send();
		} catch (EmailException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) throws IOException {
		try {
			send("[email protected]", "titile", "<a href='http://www.baidu.com'>百度</a>");
		} catch (MalformedURLException e) {
			e.printStackTrace(); 
		}
	}
}



你可能感兴趣的:(c3p0,邮件,email,smtp,邮箱)