org.apache.commons.mail Commons-Email旨在提供用于发送电子邮件。
下面是一个例子:
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.mail.HtmlEmail;
/**
* 发送电子邮件
*/
public class SendMailUtil {
private static final String from = "";//邮件的地址
private static final String fromName = "测试公司";//邮件的出处
private static final String charSet = "utf-8";//编码方式
private static final String username = "";//使用SMTP协议的用户名
private static final String password = "";//密码
private static Map<String, String> hostMap = new HashMap<String, String>();
static {
// 126
hostMap.put("smtp.126", "smtp.126.com");
// qq
hostMap.put("smtp.qq", "smtp.qq.com");
// 163
hostMap.put("smtp.163", "smtp.163.com");
// sina
hostMap.put("smtp.sina", "smtp.sina.com.cn");
// tom
hostMap.put("smtp.tom", "smtp.tom.com");
// 263
hostMap.put("smtp.263", "smtp.263.net");
// yahoo
hostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");
// hotmail
hostMap.put("smtp.hotmail", "smtp.live.com");
}
/*
* 获取服务器
*/
public static String getHost(String email) throws Exception {
Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
Matcher matcher = pattern.matcher(email);
String key = "unSupportEmail";
if (matcher.find()) {
key = "smtp." + matcher.group(1);
}
if (hostMap.containsKey(key)) {
return hostMap.get(key);
} else {
throw new Exception("unSupportEmail");
}
}
/*
* 获取端口号
*/
public static int getSmtpPort(String email) throws Exception {
//正则
Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
Matcher matcher = pattern.matcher(email);
String key = "unSupportEmail";
if (matcher.find()) {
key = "smtp.port." + matcher.group(1);
}
//map中含有制定key
if (hostMap.containsKey(key)) {
System.out.println(Integer.parseInt(hostMap.get(key)));
return Integer.parseInt(hostMap.get(key));
} else {
return 25;
}
}
/**
* 发送普通邮件
*
* @param toMailAddr
* 收信人地址
* @param subject
* email主题
* @param message
* 发送email信息
*/
public static void sendCommonMail(String toMailAddr, String subject,
String message) {
HtmlEmail hemail = new HtmlEmail();
try {
hemail.setHostName(getHost(from));
hemail.setSmtpPort(getSmtpPort(from));
hemail.setCharset(charSet);
hemail.addTo(toMailAddr);//发送到的邮箱地址
hemail.setFrom(from, fromName);
hemail.setAuthentication(username, password);//验证用户名和密码
hemail.setSubject(subject);//设置标题
hemail.setMsg(message);//设置内容
hemail.send();
System.out.println("email send true!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("email send error!");
}
}
public static void main(String[] args) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("subject", "测试标题");
map.put("content", "测试 内容");
sendCommonMail("", "sendemail test!", "测试一下看看能不能发送邮件");
}
}