需导入包,删除j2ee自带的mail文件
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
* @author nidayu
* @date 2014-12-16
* @Description xxx
* @version V1.0
*/
public class SendEmailUtil {
/**
* xxx
*
* @author nidayu
* @param
* @return
*/
public static void send(String emailName, String emailPwd, String[] to, String smtpHost, String title, String content) {
try {
SmtpAuth sa = new SmtpAuth();
(emailName, emailPwd);
props = new ();
("", "true");
("", smtpHost);
InternetAddress fromAddress = new InternetAddress(emailName);
InternetAddress[] toAddresss = new InternetAddress[];
for (int len = 0; len < ; len++) {
if (to[len] != null && to[len].length() > 1) {
toAddresss[len] = new InternetAddress(to[len]);
}
}
int i = 0;
while (i < ) {
if (toAddresss[i] != null) {
Session mailSession = (props, sa);
MimeMessage testMessage = new MimeMessage(mailSession);
(fromAddress);
(, toAddresss[i]);
(new ());
(title);
(content + "\r\tip:" + getHostIp());
(testMessage);
("A mail have been sent to " + to[i]);
}
i++;
}
} catch (Exception e) {
("邮件发送失败:");
();
}
}
public static String getHostIp() {
String sIP = "";
InetAddress ip = null;
try {
// 如果是Windows操作系统
if (isWindowsOS()) {
ip = ();
}
// 如果是Linux操作系统
else {
boolean bFindIP = false;
Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) ();
while (()) {
if (bFindIP) {
break;
}
NetworkInterface ni = (NetworkInterface) ();
// ----------特定情况,可以考虑用判断
// 遍历所有ip
Enumeration<InetAddress> ips = ();
while (()) {
ip = (InetAddress) ();
if (() && !() // 127.开头的都是lookback地址
&& ().indexOf(":") == -1) {
bFindIP = true;
break;
}
}
}
}
} catch (Exception e) {
}
if (null != ip) {
sIP = ();
}
return sIP;
}
public static boolean isWindowsOS() {
boolean isWindowsOS = false;
String osName = ("");
if (().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}
public static class SmtpAuth extends {
private String user, password;
public void getuserinfo(String getuser, String getpassword) {
user = getuser;
password = getpassword;
}
protected getPasswordAuthentication() {
return new (user, password);
}
}
}
最后测试
public static void main(String[] args) {
("邮箱号@", "邮箱密码", new String[] { "对方邮箱" }, "smtp.", "标题", "文本内容");
}