1、sendMailUtil.java工具类:
package com.company.ssh2.utils;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Date;
import java.util.ResourceBundle;
import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.*;
/**
* This class performs mail transmission.
*/
public class SendMailUtil{
private String to_; // 送达人
private String cc_; // copy to email-addres
private String bcc_;// bcc email-address
private String[] toList_;// 送达人 list
private String[] ccList_; // copy to email-address list
private String[] bccList_;// bcc email-address list
protected String sub_; // 标题
protected String msg_; // 正文
protected String personalPhrase_;
protected String from_; // 发件人
protected boolean set_on_; //标志,以确定所需的信息是否设置发送邮件
private Properties props;
private Session session;
private MimeMessage msg;
private String senderAddr_;
private String strSMTPuser;
private String strSMTPusername;
public String getStrSMTPusername() {
return strSMTPusername;
}
public void setStrSMTPusername(String strSMTPusername) {
this.strSMTPusername = strSMTPusername;
}
private String strSMTPpwd;
private int type_;
private String typeName_;
public String getTypeName_() {
return typeName_;
}
public void setTypeName_(String typeName) {
typeName_ = typeName;
}
public int getType_() {
return type_;
}
public void setType_(int type) {
type_ = type;
}
public String getStrSMTPuser() {
return strSMTPuser;
}
public void setStrSMTPuser(String strSMTPuser) {
this.strSMTPuser = strSMTPuser;
}
public String getStrSMTPpwd() {
return strSMTPpwd;
}
public void setStrSMTPpwd(String strSMTPpwd) {
this.strSMTPpwd = strSMTPpwd;
}
private void init(String smtpHost){
sub_ = null;
msg_ = null;
personalPhrase_ = null;
from_ = null;
set_on_ = false;
}
private void init(){
to_ = null;
toList_ = null;
sub_ = null;
msg_ = null;
personalPhrase_ = null;
from_ = null;
set_on_ = false;
}
/**
* 构造函数
*/
public SendMailUtil(){
init();
}
/**
* 设置值的方法
*
* @param to
* @param sub
* @param msg
* @param from
* @param smtphost SMTP
*/
public void setMailInfo(String to,
String subject,
String message,
String from){
setTo(to);
setSubject(subject);
setMessage(message);
setFromAddress(from);
}
public void setMailInfo(String to,
String subject,
String message,
String from,
String Cc){
setTo(to);
setSubject(subject);
setMessage(message);
setFromAddress(from);
setCc(Cc);
}
public void setMailInfo(String[] toList,
int type,
String typeName,
String from){
setToList(toList);
setType_(type);
setTypeName_(typeName);
setFromAddress(from);
}
public void setConnectInfo(String smtpUser,
String smtpUserName,
String smtpPwd){
setStrSMTPuser(smtpUser);
setStrSMTPusername(smtpUserName);
setStrSMTPpwd(smtpPwd);
}
/**
* Construct the class object with a smtpServer String.
*
* @param smtpHost a smtp Server,such as 192.168.99.2
*/
public SendMailUtil(String smtpHost){ // mod by liuhai 2004-05-21
init(smtpHost);
}
public boolean send(){ //mod by liuhai 2004-05-21 //Modify by CaiJianHui 2004-9-15
try {
doSendMulti();
}catch (Exception e) {
return false;
}
return true; //modify by chenhongzhu SMTP for camel4 05-9-19
}
private boolean sendOut() {//Added by chenhongzhu SMTP for camel4 05-9-19
checkValidate();
if (!set_on_) {
System.err.println("Necessary parameter was not passed.");
Thread.dumpStack();
return false;
}
try {
if (personalPhrase_ != null) {
msg.setFrom(new InternetAddress(from_, personalPhrase_,
"UTF-8"));
} else {
msg.setFrom(new InternetAddress(from_));
}
String message = msg_;
msg.setSubject(MimeUtility.encodeWord(sub_, "UTF-8", "B"));
msg.setSentDate(new Date());
msg.setContent(message, "text/plain; charset=" + "UTF-8" + "");
msg.setHeader("Content-Transfer-Encoding", "7bit");
msg.saveChanges() ;//implicit with send();
Transport transport = session.getTransport("smtp");
transport.connect() ;
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Send mail to one receiver and return a flag.
*
* @param to receiver's mail address
* @return return true if the mail transmit successfully ,otherwise returns false.
* @throws AddressException if the address is invalid address.
* @throws MessagingException if the message is invalid message.
*/
public boolean send(String to) throws AddressException, MessagingException{
setTo(to);
return send();
}
/**
* Send mail to receivers and return a flag.
*
* @param toList receivers' mail address
* @return return true if the mail transmit successfully ,otherwise returns false.
* @throws AddressException if the address is invalid address.
* @throws MessagingException if the message is invalid message.
*/
public boolean sendToMultipleRecipients(String[] toList) throws AddressException, MessagingException{
setToList(toList);
return send();
}
/**
* Sets the sender's mail address.
*
* @param from sender's mail address.
**/
public void setFromAddress(String from){
from_ = from;
}
/**
* Sets the mail subject.
*
* @param subject mail subject.
**/
public void setSubject(String subject){
sub_ = subject;
}
/**
* Sets the mail content.
*
* @param msg mail content.
*/
public void setMessage(String msg){
msg_ = msg;
}
/**
* Sets the sender name .
*
* @param name sender name.
*/
public void setFromName(String name){
personalPhrase_ = name;
}
/**
* @param toList
*
* @param ccList
* @param bccList
* @param sub
*
* @param msg
*
* @param from
*
* @param personalName
*/
public void set(String[] toList, String[] ccList, String[] bccList,
String sub, String msg, String from, String personalName) {
setToList(toList);
setCcList(ccList);
setBccList(bccList);
setSubject(sub);
setMessage(msg);
setFromName(personalName);
setFromAddress(from);
}
/**
* @param to
*
* @param cc
* @param bcc
* @param sub
*
* @param msg
*
* @param from
*
* @param personalName
*/
public void set(String to, String cc, String bcc, String sub,
String content, String from, String personalName) {
setTo(to);
setCc(cc);
setBcc(bcc);
setFromAddress(from);
setSubject(sub);
setMessage(content);
setFromName(personalName);
}
/**
* check if Necessary parameter passed
*
*/
private void checkValidate() {
if ((to_ != null || cc_ != null || bcc_ != null
|| toList_ != null || ccList_ != null || bccList_ != null)
&& (sub_ != null) && (msg_ != null) && (from_ != null)
&& (!from_.equals("")))
set_on_ = true;
}
/**
* send mail
*
* @throws AddressException
* @throws MessagingException
*/
public void doSendMulti() throws AddressException, MessagingException {
props = new Properties();
// UPD 2010-06-22 LINAN
// 将常量的读取改为从 properties 文件读取
/**Locale myLocale = Locale.getDefault();
ResourceBundle bundle = ResourceBundle.getBundle("messageResource", myLocale);
String strSmtpPort = bundle.getString("DefaultSmtpPort");
String strSmtpHost = bundle.getString("DefaultSmtpHost");
*/
//props.put("mail.smtp.host", Constants.DEFAULT_SMTP_HOST);
props.put("mail.smtp.host", Constants.DEFAULT_SMTP_HOST); // SMTP 主机地址
if (Constants.DEFAULT_SMTP_HOST != null) {
props.put("mail.smtp.port", Constants.DEFAULT_SMTP_PORT); // SMTP 端口地址
}
/*
if(Constants.DEFAULT_SMTP_PORT != null){
props.put("mail.smtp.port", Constants.DEFAULT_SMTP_PORT);
}*/
// END UPD
authenticat();
msg = new MimeMessage(session);
if (to_ != null)
setRecipient(to_,Message.RecipientType.TO);
if (cc_ != null)
setRecipient(cc_,Message.RecipientType.CC);
if (bcc_ != null)
setRecipient(bcc_,Message.RecipientType.BCC);
if (ccList_ != null)
setMultipleRecipients(ccList_,Message.RecipientType.CC);
if (bccList_ != null)
setMultipleRecipients(bccList_,Message.RecipientType.BCC);
if (toList_ != null)
setMultipleRecipients(toList_,Message.RecipientType.TO);
sendMulti();
}
/**
* @param list
* @param recipientType
* @throws MessagingException
*/
private void setMultipleRecipients(String[] list,RecipientType recipientType)
throws MessagingException{
if(list != null){
Address[] ccAddress = new Address[list.length];
for(int i = 0; i < list.length; ++i){
ccAddress[i] = (Address) new InternetAddress(list[i]);
}
msg.addRecipients(recipientType, ccAddress);
}
}
/**
* @param recipient
* @param pecipientType
* @throws MessagingException
*/
private void setRecipient(String recipient,RecipientType recipientType)
throws MessagingException {
msg.addRecipients(recipientType, InternetAddress.parse(recipient, false));
}
/**
* inside sendmail
*
* @throws SendFailedException
*/
private void sendMulti() {
sendOut();
}
/**
* read information from database and prepare session for mail
*
*/
private void authenticat() {
sessionInstance(strSMTPuser, strSMTPpwd);
}
/**
* get session Instance,if useSMTP==false,do not do SMTP auth
*
* @param strSMTPuser
* @param strSMTPpwd
* @param strUseSMTP
*/
private void sessionInstance(String strSMTPuser, String strSMTPpwd) {
session = Session.getInstance(props, null);
}
public void setBcc(String bcc) {
this.bcc_ = bcc;
}
public void setBccList(String[] bccList) {
this.bccList_ = bccList;
}
public void setCc(String cc) {
this.cc_ = cc;
}
public void setCcList(String[] ccList) {
this.ccList_ = ccList;
}
public void setTo(String to) {
this.to_ = to;
}
public void setToList(String[] toList) {
this.toList_ = toList;
}
public void setSenderAddr(String addr){
this.setSenderAddr_(addr);
}
public Map<String, Object> doSendMulti(boolean smtpAuthUse,
boolean sslUse,
String smtpUser,
String smtpPass)
throws AddressException, MessagingException, Exception {
props = new Properties();
props.put("mail.smtp.host", Constants.DEFAULT_SMTP_HOST);
props.put("mail.smtp.port", Constants.DEFAULT_SMTP_PORT);
authenticate(smtpAuthUse, smtpUser, smtpPass);
if (sslUse) {
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
msg = new MimeMessage(session);
if (to_ != null)
setRecipient(to_,Message.RecipientType.TO);
if (cc_ != null)
setRecipient(cc_,Message.RecipientType.CC);
if (bcc_ != null)
setRecipient(bcc_,Message.RecipientType.BCC);
if (ccList_ != null)
setMultipleRecipients(ccList_,Message.RecipientType.CC);
if (bccList_ != null)
setMultipleRecipients(bccList_,Message.RecipientType.BCC);
if (toList_ != null)
setMultipleRecipients(toList_,Message.RecipientType.TO);
Map<String,Object> map = new HashMap<String, Object>();
try {
if(sendOutForPsMailDlvAll()) {
map.put("msg", msg);
}
} catch (Exception e) {
map.put("msg", msg);
map.put("exception", e.getMessage());
}
return map;
}
private void authenticate(boolean smtpAuthUse,
String smtpUser,
String smtpPass) {
sessionInstance(smtpUser, smtpPass);
}
private boolean sendOutForPsMailDlvAll() throws Exception {
checkValidate();
if (!set_on_) {
System.err.println("Necessary parameter was not passed.");
Thread.dumpStack();
return false;
}
try {
if (personalPhrase_ != null) {
msg.setFrom(new InternetAddress(from_, personalPhrase_,
"UTF-8"));
} else {
msg.setFrom(new InternetAddress(from_));
}
String message = msg_;
msg.setSubject(MimeUtility.encodeWord(sub_, "UTF-8", "B"));
msg.setSentDate(new Date());
msg.setContent(message, "text/plain; charset=" + "UTF-8" + "");
msg.setHeader("Content-Transfer-Encoding", "7bit");
msg.saveChanges() ;
Transport transport = session.getTransport("smtp");
transport.connect() ;
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return true;
}
public void setSenderAddr_(String senderAddr_) {
this.senderAddr_ = senderAddr_;
}
public String getSenderAddr_() {
return senderAddr_;
}
}
2、在Action中的调用方法:
package com.company.ssh2.email.action;
import com.company.ssh2.common.action.BaseAction;
import com.company.ssh2.common.exception.Ssh2Exception;
import com.company.ssh2.utils.Constants;
import com.company.ssh2.utils.SendMailUtil;
public class EmailAction extends BaseAction{
private static final long serialVersionUID = 1L;
private String to;
private String cc;
private String subject;
private String message;
private String flag;
public String init() throws Ssh2Exception{
try{
return SUCCESS;
}catch (Exception e){
throw new Ssh2Exception(e.getMessage(),e.getCause());
}
}
public String emailSend() throws Ssh2Exception{
flag = "fail";
try{
SendMailUtil sendMail = new SendMailUtil();
sendMail.setMailInfo(to, subject, message, Constants.DefaultMail,cc);
sendMail.setConnectInfo("管理系统", Constants.DefaultMail, Constants.DefaultMailPassWord);
sendMail.send();
flag = "success";
return SUCCESS;
}catch (Exception e){
throw new Ssh2Exception(e.getMessage(),e.getCause());
}
}
public String init2() throws Ssh2Exception{
try{
return SUCCESS;
}catch (Exception e){
throw new Ssh2Exception(e.getMessage(),e.getCause());
}
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getCc() {
return cc;
}
public void setCc(String cc) {
this.cc = cc;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}