梦幻之旅

DEBUG - 天道酬勤

   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  671 随笔 :: 6 文章 :: 256 评论 :: 0 Trackbacks
package org.rw.commons.util;

import java.io.File;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
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 javax.mail.internet.MimeUtility;

/**
 * 
 * <p>
 * Title:[Java Mail Tool]
 * </p>
 * <p>
 * Description: [java邮件发送工具类]
 * </p>
 * <p>
 * Copyright 2009 SIYN Co., Ltd.
 * </p>
 * <p>
 * All right reserved.
 * </p>
 * 
 * 
@version 1.0
 * 
 * <p>
 * Created by [SIYN] [Apr 2, 2009]
 * </p>
 * <p>
 * Midified by [Huyvanpull] [Apr 5, 2009]
 * </p>
 * 
 
*/

public class JMailTool
{
    
/** ******************************************************* */
    
/** smtp服务(如:163的SMTP服务是smtp.163.com) */
    
private String smtp = "";
    
    
/** 字符集 */
    
private String charactorSet = "UTF-8";
    
    
/** 内容格式 */
    
private String content_type = "text/html;charset=utf-8";
    
    
/** 发送者 */
    
private String sender = "";
    
    
/** 接收者 */
    
private String[] receivers;
    
    
/** 接收者-抄送 */
    
private String[] CCReceivers;
    
    
/** 接收者-暗送 */
    
private String[] BCCReceivers;
    
    
/** 回复者 */
    
private String[] replys;
    
    
/** 邮件内容 */
    
private String content = "";
    
    
/** 邮件主题 */
    
private String subject = "";
    
    
/** 是否需要权限,有的邮件服务器可以不要权限 */
    
private boolean needAuth = true;
    
    
/** 用户名 */
    
private String username = "";
    
    
/** 密码 */
    
private String password = "";
    
    
/** 是否添加附件 */
    
private boolean isAddFile = false;
    
    
/** 附件全路径 */
    
private String fileNames = "";
    
    
/** ******************************************************* */
    
/** 是否打印信息到控制台 */
    
private boolean isPrintInfoToConsole = true;
    
    
/**
     * 构造方法
     
*/

    
public JMailTool()
    
{}
    
    
/**
     * 
     * <p>
     * Description:[设置SMTP]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param smtp
     * FromAddress的smtp
     
*/

    
public void setSmtp(final String smtp)
    
{
        
this.smtp = smtp;
    }

    
    
/**
     * 
     * <p>
     * Description:[设置字符集]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param charactorSet
     * 字符集
     
*/

    
public void setCharactorSet(final String charactorSet)
    
{
        
this.charactorSet = charactorSet;
    }

    
    
/**
     * 
     * <p>
     * Description:[设置内容格式]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param content_type
     * 内容格式
     
*/

    
public void setContentType(final String content_type)
    
{
        
this.content_type = content_type;
    }

    
    
/**
     * 
     * <p>
     * Description:[设置发送者]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param sender
     * 发送者 格式为: user&lt;user@163.com&gt; or user@163.com
     
*/

    
public void setSender(final String sender)
    
{
        
this.sender = sender;
    }

    
    
/**
     * 
     * <p>
     * Description:[设置邮件主题]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param subject
     * 邮件主题
     
*/

    
public void setSubject(final String subject)
    
{
        
this.subject = subject;
    }

    
    
/**
     * 
     * <p>
     * Description:[设置邮件内容]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param content
     * 邮件内容
     
*/

    
public void setPureContent(final String content)
    
{
        
this.content = content;
    }

    
    
/**
     * 
     * <p>
     * Description:[设置邮件接受者,地址格式为: user&lt;user@163.com&gt; or user@163.com]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param receiver
     * String 多个接收者,用";"或","分隔
     * 
@return
     
*/

    
public boolean setReceivers(final String receiver)
    
{
        
if ((receiver == null|| ("".equals(receiver)))
        
{
            
return false;
        }

        
this.receivers = receiver.split("[;|,]");
        
return this.receivers.length >= 1;
    }

    
    
/**
     * 
     * <p>
     * Description:[设置邮件接受者(抄送) 地址格式为: user&lt;user@163.com&gt; or user@163.com]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param CCReceiver
     * String 多个接收者,用";"或","分隔
     * 
@return
     
*/

    
public boolean setCCReceivers(final String CCReceiver)
    
{
        
if ((CCReceiver == null|| ("".equals(CCReceiver)))
        
{
            
return false;
        }

        
this.CCReceivers = CCReceiver.split("[;|,]");
        
return this.CCReceivers.length >= 1;
    }

    
    
/**
     * 
     * <p>
     * Description:[设置邮件接受者(暗送) 地址格式为: user&lt;user@163.com&gt; or user@163.com]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param BCCReceiver
     * String 多个接收者,用";"或","分隔
     * 
@return
     
*/

    
public boolean setBCCReceiver(final String BCCReceiver)
    
{
        
if ((BCCReceiver == null&& ("".equals(BCCReceiver)))
        
{
            
return false;
        }

        
this.BCCReceivers = BCCReceiver.split("[;|,]");
        
return this.BCCReceivers.length >= 1;
    }

    
    
/**
     * 
     * <p>
     * Description:[设置回复者 地址格式为: user&lt;user@163.com&gt; or user@163.com]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param reply
     * String 多个回复者,用";"或","分隔
     * 
@return
     
*/

    
public boolean setReplys(final String reply)
    
{
        
if ((reply == null|| ("".equals(reply)))
        
{
            
return false;
        }

        
this.replys = reply.split("[;|,]");
        
return this.receivers.length >= 1;
    }

    
    
/**
     * 
     * <p>
     * Description:[设置认证]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param name
     * 用户名
     * 
@param password
     * 密码
     
*/

    
public void setAuth(final String name, final String password)
    
{
        
this.username = name;
        
this.password = password;
    }

    
    
/**
     * 
     * <p>
     * Description:[设置是否添加附件]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param isAddFile
     
*/

    
private void setAddFile(boolean isAddFile)
    
{
        
this.isAddFile = isAddFile;
    }

    
    
/**
     * 
     * <p>
     * Description:[设置邮件的附件,可多个附件]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param fileNames
     * 多个文件名,用";"或","分开
     
*/

    
public void setFileAffixs(final String fileNames)
    
{
        
this.fileNames = fileNames;
        
if (fileNames != null && !"".equals(fileNames))
        
{
            setAddFile(
true);
        }

    }

    
    
/**
     * 
     * <p>
     * Description:[设置是否打印信息到控制台]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param isPrintInfoToConsole
     
*/

    
public void isPrintInfoToConsole(boolean isPrintInfoToConsole)
    
{
        
this.isPrintInfoToConsole = isPrintInfoToConsole;
    }

    
    
/**
     * 
     * <p>
     * Description:[添加邮件的附件,可多个附件]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param multipart
     * MimeMultipart 原来的MimeMultipart
     * 
@param filename
     * String 多个文件名,用";"或","分开
     * 
@return MimeMultipart 最终的MimeMultipart
     
*/

    
private MimeMultipart addFileAffix(MimeMultipart multipart, String fileNames)
    
{
        
/** 如果文件名为NULL名为空字符串 */
        
if (fileNames == null || "".equals(fileNames))
        
{
            
return multipart;
        }

        
        MimeMultipart multipartTemp 
= null;
        multipartTemp 
= multipart;
        
try
        
{
            
final String[] arrFile = fileNames.split("[;|,]");
            
for (int i = 0; i < arrFile.length; i++)
            
{
                
final File delfile = new File(arrFile[i]);
                
if (delfile.exists())
                
{
                    
final MimeBodyPart mbpFile = new MimeBodyPart();
                    
final FileDataSource fileDataSource = new FileDataSource(
                            arrFile[i]);
                    mbpFile.setDataHandler(
new DataHandler(fileDataSource));
                    mbpFile.setFileName(fileDataSource.getName());
                    multipartTemp.addBodyPart(mbpFile);
                }

            }

            
/** 增加邮件附件成功返回修改后的MimeMultipart */
            
return multipartTemp;
        }

        
catch (Exception e)
        
{
            
/** 增加邮件附件失败返回原来的MimeMultipart */
            
return multipart;
        }

    }

    
    
/**
     * 发送邮件
     * 
     * 
@return int 返回结束代码
     
*/

    
public int sendMail()
    
{
        
try
        
{
            
final Properties properties = System.getProperties();
            
/** 设置SMTP开始 ********************************************** */
            
/** 检查是否设置SMTP */
            
if (this.smtp == null || "".equals(this.smtp))
            
{
                
throw new Exception("没有设置SMTP.");
            }

            properties.put(
"mail.smtp.host"this.smtp);
            
/** 处理gmail开始,gmail使用的了ssl加密,需特别处理 ** */
            
if (this.smtp.indexOf("smtp.gmail.com">= 0)
            
{
                properties.setProperty(
"mail.smtp.socketFactory.class",
                        
"javax.net.ssl.SSLSocketFactory");
                properties.setProperty(
"mail.smtp.socketFactory.fallback",
                        
"false");
                properties.setProperty(
"mail.smtp.port""465");
                properties.setProperty(
"mail.smtp.socketFactory.port""465");
            }

            
/** 处理gmail结束,gmail使用的了ssl加密,需特别处理 ** */
            
/** 设置SMTP结束 ********************************************** */
            
            
/** 设置认证开始 *********************************************** */
            
if (this.needAuth)
            
{
                properties.put(
"mail.smtp.auth""true");
            }

            
else
            
{
                properties.put(
"mail.smtp.auth""false");
            }

            
/** 设置认证结束 *********************************************** */
            
final Session session = Session
                    .getDefaultInstance(properties, 
null);
            
            
/** 构造MimeMessage 并设定基本的值 */
            
final MimeMessage mimeMessage = new MimeMessage(session);
            
            
/** 设置发件人开始 ********************************************** */
            
if (this.sender == null || "".equals(this.sender))
            
{
                
throw new Exception("没有设置发件人SENDER.");
            }

            
final InternetAddress from = new InternetAddress(this
                    .encodeAddress(
this.sender));
            mimeMessage.setFrom(from);
            
/** 设置发件人结束 ********************************************** */
            
            
/** 设置收件人开始 ********************************************** */
            
if (this.receivers == null || this.receivers.length <= 0)
            
{
                
throw new Exception("没有设置收件人RECEIVERS.");
            }

            InternetAddress[] arrTo 
= new InternetAddress[this.receivers.length];
            
for (int i = 0; i < this.receivers.length; i++)
            
{
                arrTo[i] 
= new InternetAddress(this
                        .encodeAddress(
this.receivers[i]));
            }

            mimeMessage.setRecipients(Message.RecipientType.TO, arrTo);
            
/** 设置收件人结束 ********************************************** */
            
            
/** 设置抄送人开始 ********************************************** */
            
if (this.CCReceivers != null && this.CCReceivers.length > 0)
            
{
                InternetAddress[] arrCC 
= new InternetAddress[this.CCReceivers.length];
                
for (int i = 0; i < this.CCReceivers.length; i++)
                
{
                    arrCC[i] 
= new InternetAddress(this
                            .encodeAddress(
this.CCReceivers[i]));
                }

                mimeMessage.setRecipients(Message.RecipientType.CC, arrCC);
            }

            
/** 设置抄送人结束 ********************************************** */
            
            
/** 设置暗送人开始 ********************************************** */
            
if (this.BCCReceivers != null && this.BCCReceivers.length > 0)
            
{
                InternetAddress[] arrBCC 
= new InternetAddress[this.BCCReceivers.length];
                
for (int i = 0; i < this.BCCReceivers.length; i++)
                
{
                    arrBCC[i] 
= new InternetAddress(this
                            .encodeAddress(
this.BCCReceivers[i]));
                }

                mimeMessage.setRecipients(Message.RecipientType.BCC, arrBCC);
            }

            
/** 设置暗送人结束 ********************************************** */
            
            
/** 设置回复人开始 ********************************************** */
            
if (this.replys != null && this.replys.length > 0)
            
{
                InternetAddress[] arrReply 
= new InternetAddress[this.replys.length];
                
for (int j = 0; j < this.replys.length; j++)
                
{
                    arrReply[j] 
= new InternetAddress(this
                            .encodeAddress(
this.replys[j]));
                }

                mimeMessage.setReplyTo(arrReply);
            }

            
/** 设置回复人结束 ********************************************** */
            
            
/** 设置邮件主题开始 ******************************************** */
            
if (this.subject == null || "".equals(this.subject))
            
{
                
this.subject = "来自" + this.sender + "的邮件";
            }

            mimeMessage.setSubject(
this.subject, this.charactorSet);
            
/** 设置邮件主题结束 ******************************************** */
            
            MimeMultipart multipart 
= new MimeMultipart();
            
            
/** 设定邮件正文 */
            MimeBodyPart mbpContent 
= new MimeBodyPart();
            mbpContent.setText(
this.content, this.charactorSet);
            mbpContent.setHeader(
"Content-type"this.content_type);
            multipart.addBodyPart(mbpContent);
            
            
/** 设定邮件附件 */
            
if (isAddFile == true)
            
{
                multipart 
= addFileAffix(multipart, this.fileNames);
            }

            
            
/** 设定mimeMessage Header */
            mimeMessage.setHeader(
"Content-type"this.content_type);
            
            
/** 向MimeMessage添加Multipart */
            mimeMessage.setContent(multipart);
            
            
/** 设定时间 */
            mimeMessage.setSentDate(
new Date());
            
            mimeMessage.saveChanges();
            
            
if (this.needAuth)
            
{
                
final Transport transport = session.getTransport("smtp");
                transport.connect((String) properties.get(
"mail.smtp.host"),
                        
this.username, this.password);
                transport.sendMessage(mimeMessage, mimeMessage
                        .getAllRecipients());
            }

            
else
            
{
                Transport.send(mimeMessage);
            }

            
/** 是否打印发送成功与否信息 */
            
if (this.isPrintInfoToConsole)
            
{
                
this.printInfoToConsole(true);
            }

            
return 0;
        }

        
catch (Exception ex)
        
{
            ex.printStackTrace();
            
return -1;
        }

    }

    
    
/**
     * 
     * <p>
     * Description:[地址转码,例如:把user&lt;user@163.com&gt;的地址转码为user@163.com]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param addresses
     * 转码前的地址
     * 
@return 转码后的地址
     
*/

    
private String encodeAddress(String address)
    
{
        
int leftSignPosition = address.indexOf("<");
        
if (leftSignPosition > 1 && address.indexOf(">"> leftSignPosition)
        
{
            String leftPart 
= address.substring(0, leftSignPosition);
            String rightPart 
= address.substring(leftSignPosition, address
                    .length());
            
try
            
{
                leftPart 
= MimeUtility.encodeText(leftPart, this.charactorSet,
                        
"B");
                
return leftPart + rightPart;
            }

            
catch (Exception e)
            
{}
        }

        
return address;
    }

    
    
/**
     * 
     * <p>
     * Description:[在控制台打印发送后的信息]
     * </p>
     * <p>
     * Created by [SIYN] [Apr 2, 2009]
     * </p>
     * <p>
     * Midified by [Huyvanpull] [Apr 5, 2009]
     * </p>
     * 
     * 
@param isSendedSuccess
     * 是否发送成功
     
*/

    
private void printInfoToConsole(boolean isSendedSuccess)
    
{
        
/** 如果不打印控制台信息 */
        
if (!this.isPrintInfoToConsole)
        
{
            
return;
        }

        
/** 组装打印信息开始 **************************************** */
        StringBuffer info 
= new StringBuffer();
        info.append(
"----------------->");
        info.append(isSendedSuccess);
        info.append(
"<-----------------");
        
/** smtp服务器信息 *************** */
        info.append(
"\nSMTP 服务器:");
        info.append(
this.smtp);
        
/** 发送者信息 ******************* */
        info.append(
"\n发送者:     ");
        info.append(sender);
        
/** 接收者信息 ******************* */
        info.append(
"\n接收者:     ");
        
if (this.receivers != null)
        
{
            info.append(
this.receivers[0]);
            
for (int i = 1; i < this.receivers.length; i++)
            
{
                info.append(
"," + this.receivers[i]);
            }

        }

        
/** 抄送者信息 ******************* */
        info.append(
"\n接收者(抄送):");
        
if (this.CCReceivers != null)
        
{
            info.append(
this.CCReceivers[0]);
            
for (int i = 1; i < this.CCReceivers.length; i++)
            
{
                info.append(
"," + this.CCReceivers[i]);
            }

        }

        
else
        
{
            info.append(
"");
        }

        
/** 抄送者信息 ******************** */
        info.append(
"\n接收者(暗送):");
        
if (this.BCCReceivers != null)
        
{
            info.append(
this.BCCReceivers[0]);
            
for (int i = 1; i < this.BCCReceivers.length; i++)
            
{
                info.append(
"," + this.BCCReceivers[i]);
            }

        }

        
else
        
{
            info.append(
"");
        }

        
/** 组装打印信息结束 **************************************** */
        System.out.println(info.toString());
    }

    
}

posted on 2009-04-02 18:24 HUIKK 阅读(307) 评论(0)  编辑  收藏 所属分类: TOOL

只有注册用户登录后才能发表评论。


网站导航: