所需jar包:下载地址
代码如下
package cn.bestchance.util;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
public class MailUtilByChance {
// 这里是SMTP发送服务器的协议
public static final String HOST_NAME = "smtp.163.com";
// 登陆邮件服务器的用户名、密码、昵称
public static final String USERNAME = "发件人邮箱";
public static final String PASSWORD = "邮箱授权码";
public static final String NICKNAME = "邮箱主题";
/**
* 发送邮件(成功true、失败false)
* @param receiveEmail 收件人邮箱
* @param receiveNick 收件人昵称(随便取)
* @param subject 邮件主题
* @param contents 邮件内容
* @return
*/
public static final boolean sendMail(String receiveEmail,String receiveNick,String subject,String contents){
HtmlEmail email = new HtmlEmail ();
try {
//smtp host
email.setHostName(HOST_NAME);
//登陆邮件服务器的用户名和密码
email.setAuthentication(USERNAME,PASSWORD);
//接收人
email.addTo(receiveEmail, receiveNick);
//发送人
email.setFrom(USERNAME, NICKNAME);
//标题
email.setSubject(subject);
//邮件内容
email.setCharset("utf-8");
email.setHtmlMsg(contents);
//发送
email.send();
return true;
} catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
// MultiPartEmail email = new MultiPartEmail();
// try {
// //smtp host
// email.setHostName(HOST_NAME);
// //登陆邮件服务器的用户名和密码
// email.setAuthentication(USERNAME,PASSWORD);
// //接收人
// email.addTo(receiveEmail, receiveNick);
// //发送人
// email.setFrom(USERNAME, NICKNAME);
// //标题
// email.setSubject(subject);
// //邮件内容
// email.setMsg(contents);
// //发送
// email.send();
// return true;
//
// } catch (EmailException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// return false;
// }
}
}
调用方法如下:
package cn.bestchance;
import java.util.ArrayList;
import cn.bestchance.biz.BookInfoBiz;
import cn.bestchance.biz.BookTypeBiz;
import cn.bestchance.biz.impl.BookInfoBizImpl;
import cn.bestchance.biz.impl.BookTypeBizImpl;
import cn.bestchance.dao.BookInfoDao;
import cn.bestchance.dao.impl.BookInfoDaoImpl;
import cn.bestchance.entity.BookInfo;
import cn.bestchance.entity.BookType;
import cn.bestchance.util.MailUtilByYock;
/**
* 测试类
*
* @author wuchengqian
*
*/
public class Test {
public static void main(String[] args) {
String receiveEmail = "收件人邮箱";
String receiveNick="收件人昵称(可省略)";
String subject="邮箱主题";
String contents="邮箱内容";
MailUtilByChance.sendMail(receiveEmail, receiveNick, subject, contents);
}
}