简介
依赖与javax.mail库,需要导入activation-1.1.jar
和mail.jar
,可以直接调用接口来发送邮箱到指定地址,只需要预先配好发邮箱的邮箱信息。
封装SendMail.java
package com.wentao.util;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.log4j.Logger;
public class SendMail {
public static Logger logger = Logger.getLogger(SendMail.class);
String m_strSendTo = "";
String m_strSendFrom = "";
String m_strMailServerHost = "";
String m_strMailSubject = "";
String[] m_vectFiles = { "index.jpg" };
String m_StrMailMsg = "";
private boolean isNeedAuth = false;
private String authUserName = "";
private String authUserPwd = "";
private String m_strDefaultSendFrom = "";
private String contentType = "1";
private Session session;
public SendMail() {
}
public SendMail(String strTo, String strFrom, String smtpServer, String strSubject) {
this.m_strSendTo = strTo;
this.m_strSendFrom = strFrom;
this.m_strMailServerHost = smtpServer;
this.m_strMailSubject = strSubject;
init();
}
public SendMail(String strTo, String strFrom, String smtpServer, String strSubject, boolean isNeedAuth,
String authUserName, String authUserPwd) {
this.m_strSendTo = strTo;
this.m_strSendFrom = strFrom;
this.m_strMailServerHost = smtpServer;
this.m_strMailSubject = strSubject;
this.isNeedAuth = isNeedAuth;
this.authUserName = authUserName;
this.authUserPwd = authUserPwd;
init();
}
public SendMail(String smtpServer, String defSendFrom, boolean isNeedAuth, String authUserName,
String authUserPwd) {
this.m_strMailServerHost = smtpServer;
this.m_strDefaultSendFrom = defSendFrom;
this.isNeedAuth = isNeedAuth;
this.authUserName = authUserName;
this.authUserPwd = authUserPwd;
init();
}
public void setMessage(String msg) {
// m_vectMailMsgs.addElement(msg);
m_StrMailMsg = msg;
}
private void init() {
Properties props = System.getProperties();
props.put("mail.smtp.host", m_strMailServerHost);
if (this.isNeedAuth) {
props.put("mail.smtp.auth", "true");
session = Session.getInstance(props, new MailAuthenticator(authUserName, authUserPwd));
} else
session = Session.getInstance(props, null);
session.setDebug(false);
}
private boolean checkIsValid(String obj) {
boolean res = true;
if ((obj == null) || (obj.length() < 1))
res = false;
return res;
}
public boolean startSend() {
if ((m_strSendFrom == null) || (m_strSendFrom.length() < 1)) {
if ((m_strDefaultSendFrom != null) && (m_strDefaultSendFrom.length() > 1))
m_strSendFrom = m_strDefaultSendFrom;
}
if (!checkIsValid(m_strSendFrom) || !checkIsValid(this.m_strSendTo)
|| !checkIsValid(this.m_strMailServerHost)) {
return false;
}
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(m_strSendFrom));
InternetAddress[] address = { new InternetAddress(m_strSendTo) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(m_strMailSubject);
if (this.m_vectFiles != null && this.m_vectFiles.length > 0) {
Multipart mp = new MimeMultipart();
MimeBodyPart mbp1 = new MimeBodyPart();
if (this.contentType.equals("1")) {
mbp1.setContent(this.m_StrMailMsg, "text/html;charset=utf8");
System.out.println("111111" + this.m_StrMailMsg);
} else
mbp1.setText(this.m_StrMailMsg);
mp.addBodyPart(mbp1);
/*
* BodyPart bodyPart = new MimeBodyPart(); File attach=new
* File("index.jpg"); DataSource dataSource = new
* FileDataSource(attach); bodyPart.setDataHandler(new
* DataHandler(dataSource));
* bodyPart.setFileName(attach.getName());
* bodyPart.setHeader("Content-ID", "");
* mp.addBodyPart(bodyPart);
*/
/*
* BodyPart bodyPart1 = new MimeBodyPart(); bodyPart1.
* setContent(""
* , "text/html;charset=utf8"); mp.addBodyPart(bodyPart1);
*/
/*
* int len = m_vectFiles.length; for (int i = 0; i < len; i++) {
* MimeBodyPart mbp2 = new MimeBodyPart(); String strFileName =
* m_vectFiles[i];
* System.out.println(SendMail.class.getClassLoader().
* getResource(strFileName)); FileDataSource fds = new
* FileDataSource(SendMail.class.getClassLoader().getResource(
* strFileName).toString().substring(6));
* mbp2.setDataHandler(new DataHandler(fds));
* System.out.println(fds.getName());
* mbp2.setFileName(fds.getName()); mbp2.setHeader("Content-ID",
* "");
*
* mp.addBodyPart(mbp2); }
*/
m_vectFiles = null;
msg.setContent(mp);
} else {
if (this.contentType.equals("1"))
msg.setContent(this.m_StrMailMsg, "text/html;charset=gb2312");
else
msg.setText(this.m_StrMailMsg);
}
msg.setSentDate(new Date());
Transport.send(msg);
} catch (Exception excep) {
excep.printStackTrace();
return false;
}
return true;
}
/**
* @param authUserName
* The authUserName to set.
*/
public void setAuthUserName(String authUserName) {
this.authUserName = authUserName;
}
/**
* @param authUserPwd
* The authUserPwd to set.
*/
public void setAuthUserPwd(String authUserPwd) {
this.authUserPwd = authUserPwd;
}
/**
* @param isNeedAuth
* The isNeedAuth to set.
*/
public void setNeedAuth(boolean isNeedAuth) {
this.isNeedAuth = isNeedAuth;
}
/**
* @param mailSubject
* The m_strMailSubject to set.
*/
public void setM_strMailSubject(String mailSubject) {
m_strMailSubject = mailSubject;
}
/**
* @param sendFrom
* The m_strSendFrom to set.
*/
public void setM_strSendFrom(String sendFrom) {
m_strSendFrom = sendFrom;
}
/**
* @param sendTo
* The m_strSendTo to set.
*/
public void setM_strSendTo(String sendTo) {
m_strSendTo = sendTo;
}
public static Map sendMailfunc(String title, String content, String toEmail) {
//以163邮箱为例配好发件邮箱信息
String smtp = "smtp.163.com";
String fromEmail = "[email protected]";
//注意是客户端授权密码而不是邮箱密码
String emailPass = "xxxxxx";
String emailUser = "alarm_xtreme";
String toEmails[] = toEmail.split(",");
Map map = new HashMap();
if (toEmails != null && toEmails.length > 0) {
SendMail sendmail = new SendMail(toEmails[0], fromEmail, smtp, title, true, emailUser, emailPass);
for (int i = 0; i < toEmails.length; i++) {
sendmail.setM_strSendTo(toEmails[i]);
sendmail.setMessage(content);
boolean b = sendmail.startSend();
if (b == true) {
map.put(toEmails[i], "成功");
} else {
map.put(toEmails[i], "失败");
}
logger.info(toEmails[i] + "=====告警邮件发送成功!======" + content);
}
}
return map;
}
public static void main(String[] args) {
// 这里是收到邮件的邮箱地址
SendMail.sendMailfunc("xxx告警", "xxxx计算异常", "[email protected],[email protected]");
}
class MailAuthenticator extends Authenticator {
String mailUserName;
String mailUserPwd;
public MailAuthenticator(String user, String pwd) {
super();
this.mailUserName = user;
this.mailUserPwd = pwd;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailUserName, mailUserPwd);
}
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String[] getM_vectFiles() {
return m_vectFiles;
}
public void setM_vectFiles(String[] files) {
m_vectFiles = files;
}
}
调用
只需按照上面类的main方法一样调用就好了,可以支持发给多个邮箱。