/**
 * Title:        发送邮件类
 * Company:      泛微软件
 *
 * @author: 刘煜
 * @version: 1.0
 * create date : 2001-10-23
 * modify log:
 * <p>
 * <p>
 * Description:  邮件的发送，采用 SMTP 协议， SMTP 服务器在系统的设置中设置
 * SMTP 服务器在系统的设置中设置：
 * 在ECOLOGY 系统中， 进入系统，选择设置，设置 SMTP 服务器
 */

package weaver.general;

import com.api.email.util.EmailCommonUtils;
import com.engine.email.entity.EmailFlockSendAccountComInfo;

import weaver.conn.RecordSet;
import weaver.email.*;
import weaver.email.externalmail.EmailExternalConstant;
import weaver.email.externalmail.send.EmailSend;
import weaver.email.externalmail.send.entity.EmailSendEntity;
import weaver.email.externalmail.send.entity.EmailSendFileOldEntity;
import weaver.email.externalmail.send.entity.EmailSenderEntity;
import weaver.hrm.User;

import javax.activation.DataHandler;
import javax.activation.FileTypeMap;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.Security;
import java.util.*;

/**
 * 新版已废弃，不建议使用。
 */
@Deprecated
public class SendMail extends MailErrorBean {

    static {
        System.getProperties().setProperty("mail.mime.splitlongparameters", "false"); // linux 会默认为 true，会截断附件名（ava Mail 附件名太长导致接收端附件名解析出错）
        System.setProperty("mail.mime.splitlongparameters", "false"); // linux 会默认为 true，会截断附件名（ava Mail 附件名太长导致接收端附件名解析出错）
    }

    private BaseBean logBean = new BaseBean();

    private boolean isDebug = false;
    private String subcompanyid = "0";

    /**
     *  构造方法
     */
    public SendMail() {
    }

    public SendMail(String subcompanyid) {
        this.subcompanyid = subcompanyid;
    }

    EmailFlockSendAccountComInfo cominfo = new EmailFlockSendAccountComInfo();// 系统设置，默认取群发参数(兼容分权)

    private String username = cominfo.getAccountId(subcompanyid);  // 登录名
    private String password = cominfo.getAccountPassword(subcompanyid);  // 密码
    private String mailserver = cominfo.getSmtpServer(subcompanyid);  // 发件服务器地址
    private boolean needauthsend = "1".equals(cominfo.getNeedCheck(subcompanyid));  // 是否发件认证
    private String needSSL = cominfo.getSendneedSSL(subcompanyid);  // 是否开启SSL模式
    private String smtpServerPort = cominfo.getSmtpServerPort(subcompanyid);  // 发件服务端口
    private String needReceipt = "";  // 是否需要阅读回执
    private String accountName = cominfo.getAccountName(subcompanyid);  // 发件人昵称
    private boolean isStartTls = "1".equals(cominfo.getIsStartTls(subcompanyid));  // 是否启用starttls方式

    private String protocolType = EmailExternalConstant.EMAIL_PROTOCOL_TYPE_SMTP;

    private boolean isSendApart = false; //是否是分别发送
    private int bindMailId = -1; //邮件模块，分别发送，纯文本发送时设置的值。

    public String getSmtpServerPort() {
        return smtpServerPort;
    }

    public void setSmtpServerPort(String smtpServerPort) {
        this.smtpServerPort = smtpServerPort;
    }

    public String getNeedSSL() {
        return needSSL;
    }

    public void setNeedSSL(String needSSL) {
        this.needSSL = needSSL;
    }

    public void setNeedauthsend(boolean needauthsend) {
        this.needauthsend = needauthsend;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setMailServer(String mailserver) {
        this.mailserver = mailserver;
    }

    public String getNeedReceipt() {
        return needReceipt;
    }

    public void setNeedReceipt(String needReceipt) {
        this.needReceipt = needReceipt;
    }

    public String getAccountName() {
        return accountName;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    public boolean isStartTls() {
        return isStartTls;
    }

    public void setStartTls(boolean isStartTls) {
        this.isStartTls = isStartTls;
    }

    /**
     * 获取isSendApart
     * @return the isSendApart
     */
    public boolean isSendApart() {
        return isSendApart;
    }

    /**
     * 设置isSendApart
     * @param isSendApart the isSendApart to set
     */
    public void setIsSendApart(boolean isSendApart) {
        this.isSendApart = isSendApart;
    }

    /**
     * 设置bindMailId
     * @param bindMailId the bindMailId to set
     */
    public void setBindMailId(int bindMailId) {
        this.bindMailId = bindMailId;
    }

    public String getProtocolType() {
        return protocolType;
    }

    public void setProtocolType(String protocolType) {
        this.protocolType = protocolType;
    }

    /**
     * 发送文本邮件
     *
     * @param from  邮件的发件人参数
     * @param to    邮件的收件人参数，多个收件人之间用逗号隔开
     * @param cc    邮件的抄送人参数，多个抄送人之间用逗号隔开
     * @param bcc   邮件的暗送人参数，多个暗送人之间用逗号隔开
     * @param subject    邮件的主题参数（采用ISO8859编码格式）
     * @param body       邮件的正文参数（采用ISO8859编码格式）
     * @param priority   邮件的重要性参数 3：普通 2：重要 4：紧急
     *
     * @return boolean 邮件发送成功，返回 true，否则，返回false
     */
    public boolean send(String from, String to, String cc, String bcc, String subject, String body, String priority) {
        return this.newSendMailNoEx(from, to, cc, bcc, subject, 3, body, null, null, null, 0, null, isSendApart, priority, needReceipt, true);
    }

    /**
     * 发送HTML邮件，具体到每个email地址的发送
     *
     * @param id
     * @param to
     * @param subject
     * @param body
     * @param sendToId
     * @return
     */
    public boolean sendhtmlProxy(int id, String to, String subject, String body, String sendToId) {
        char flag = Util.getSeparator();
        String para = "";
        para = id + "" + flag + to + flag + subject + flag + body + flag + "0" + flag + sendToId;
        RecordSet rs = new RecordSet();
        rs.executeProc("MailSendRecord_Insert", para);
        return true;
    }

    /**
     * 发送HTML邮件，具体到每批发送的信息，扳回存储到数据库中主表的id，由这个id可以存贮这个批次的明细信息
     * @param from
     * @param cc
     * @param bcc
     * @param char_set
     * @param priority
     * @param user
     * @param sendDate
     * @param sendTime
     * @param sendToType
     * @return
     */
    public int sendhtmlMain(String from, String cc, String bcc, int char_set, String priority, User user, String sendDate, String sendTime, String sendToType) {
        char flag = Util.getSeparator();
        String para = "";
        RecordSet rs = new RecordSet();
        int ret = 0;
        rs.executeProc("SequenceIndex_SMailSendId", "");
        if (rs.next()) {
            ret = rs.getInt(1);
        }
        para = ret + "" + flag + from + flag + cc + flag + bcc + flag + "" + char_set + flag + priority + flag + sendDate + flag + sendTime + flag + "0" + flag + sendToType + flag + "" + user.getUID();
        rs.executeProc("MailSendMain_Insert", para);

        return ret;
    }

    /**
     * 发送HTML邮件
     *
     * @param from  邮件的发件人参数
     * @param to    邮件的收件人参数，多个收件人之间用逗号隔开
     * @param cc    邮件的抄送人参数，多个抄送人之间用逗号隔开
     * @param bcc   邮件的暗送人参数，多个暗送人之间用逗号隔开
     * @param subject    邮件的主题参数（采用ISO8859编码格式）
     * @param body       邮件的正文参数（采用ISO8859编码格式）
     * @param char_set   编码方式 1：iso-8859-1 2：big5 3：GBK
     * @param priority   邮件的重要性参数 3：普通 2：重要 4：紧急
     *
     * @return boolean 邮件发送成功，返回 true，否则，返回false
     */
    public boolean sendhtml(String from, String to, String cc, String bcc, String subject, String body, int char_set, String priority) {
        return this.newSendMailNoEx(from, to, cc, bcc, subject, char_set, body, null, null, null, 0, null, isSendApart, priority, needReceipt, true);
    }

    /**
     * 发送HTML邮件(用于流程、日程、会议提醒等调用，向上抛出异常！！)
     * 此方法内部不处理任何异常，会直接向上抛出！！！
     *
     * @param from  邮件的发件人参数
     * @param to    邮件的收件人参数，多个收件人之间用逗号隔开
     * @param cc    邮件的抄送人参数，多个抄送人之间用逗号隔开
     * @param bcc   邮件的暗送人参数，多个暗送人之间用逗号隔开
     * @param subject    邮件的主题参数（采用ISO8859编码格式）
     * @param body       邮件的正文参数（采用ISO8859编码格式）
     * @param char_set   编码方式 1：iso-8859-1 2：big5 3：GBK
     * @param priority   邮件的重要性参数 3：普通 2：重要 4：紧急
     *
     * @return boolean 邮件发送成功，返回 true，否则，返回false
     */
    public boolean sendhtmlForRemind(String from, String to, String cc, String bcc, String subject, String body, int char_set, String priority) throws Exception {
        EmailSend emailSend = new EmailSend();
        EmailSenderEntity sender = emailSend.initSenderBySendMail(protocolType, from, username, password, mailserver, needauthsend, needSSL, smtpServerPort, accountName, isStartTls);
        EmailSendEntity ese = emailSend.packParameterToEntity(from, to, cc, bcc, subject, char_set, body, null, null, null, 0, null, isSendApart, priority, needReceipt, true);
        emailSend.sendMail(sender, ese);
        return true;
    }

    /**
     * 发送HTML邮件,HTML内容中包含图片。
     *
     * @param from  邮件的发件人参数
     * @param to    邮件的收件人参数，多个收件人之间用逗号隔开
     * @param cc    邮件的抄送人参数，多个抄送人之间用逗号隔开
     * @param bcc   邮件的暗送人参数，多个暗送人之间用逗号隔开
     * @param subject    邮件的主题参数（采用ISO8859编码格式）
     * @param body       邮件的正文参数（采用ISO8859编码格式）
     * @param char_set   编码方式 1：iso-8859-1 2：big5 3：GBK
     * @param priority   邮件的重要性参数 3：普通 2：重要 4：紧急
     * @param imgnames   HTML内容中包含的图片
     *
     * @return boolean 邮件发送成功，返回 true，否则，返回false
     */
    public boolean sendhtml(String from, String to, String cc, String bcc, String subject, String body, int char_set, String priority, Hashtable imgnames, int mailid) {
        return this.newSendMailNoEx(from, to, cc, bcc, subject, char_set, body, imgnames, null, null, mailid, null, isSendApart, priority, needReceipt, true);
    }

    /**
     * Title:设置ssl连接 
     * @param _session
     * @param props
     * @return
     * @return Session
     */
    public Session setSSLConnectMsg(Session _session, Properties props) {
        String userId = logBean.getPropValue("openmailbasebean", "hrm_id");
        String sendmailkey = logBean.getPropValue("openmailbasebean", "sendMail_Debug_switch");
        props.setProperty("mail.smtp.port", smtpServerPort); //设置端口信息 
        props.put("mail.smtp.host", mailserver);
        props.put("mail.transport.protocol", "smtp");

        // 发送邮件建立连接和发送超时设置
        props.setProperty("mail.smtp.connectiontimeout", String.valueOf(1000 * 30));  //ConnectTimeout建立连接超时，10秒
        props.setProperty("mail.smtp.timeout", String.valueOf(1000 * 90));  //ReadTimeout 读取超时30秒

        // Java Mail 附件名太长导致接收端附件名解析出错(出现在javaxmail 1.5.3版本以后)
        System.getProperties().setProperty("mail.mime.splitlongparameters", "false"); // linux 会默认为 true，会截断附件名（ava Mail 附件名太长导致接收端附件名解析出错）
        System.setProperty("mail.mime.splitlongparameters", "false"); // linux 会默认为 true，会截断附件名（ava Mail 附件名太长导致接收端附件名解析出错）

        javax.mail.Authenticator auth = null;

        if (needauthsend) { // 需要发件认证
            props.put("mail.smtp.auth", "true");
            auth = new Email_Autherticator(username, password);
        }

        if ("1".equals(this.needSSL)) {
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.socketFactory.port", smtpServerPort);
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.ssl.enable", "true");

            _session = Session.getInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        } else {
            // 是否启用了starttls方式
            if (this.isStartTls) {
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.ssl.checkserveridentity", "false");
                props.put("mail.smtp.ssl.trust", mailserver);

                props.setProperty("mail.smtp.socketFactory.fallback", "false");
                props.setProperty("mail.smtp.socketFactory.port", String.valueOf(smtpServerPort));

                _session = Session.getInstance(props, new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
            } else {
                _session = Session.getInstance(props, auth);
            }
        }

        //开启调试模式
        if (!"".equals(userId) && "1".equals(sendmailkey)) {
            logBean.writeLog("发送邮件debug日志开启，发件人id为：" + userId);
            _session.setDebug(true);
        }

        return _session;
    }

    /**
     * 发送带附件的邮件
     *
     * @param from  邮件的发件人参数
     * @param to    邮件的收件人参数，多个收件人之间用逗号隔开
     * @param cc    邮件的抄送人参数，多个抄送人之间用逗号隔开
     * @param bcc   邮件的暗送人参数，多个暗送人之间用逗号隔开
     * @param subject    邮件的主题参数（采用ISO8859编码格式）
     * @param body       邮件的正文参数（采用ISO8859编码格式）
     * @param char_set   编码方式 1：iso-8859-1 2：big5 3：GBK
     * @param filenames   所有附件的名称，用ArrayList存放，与内容一一对应
     * @param filecontents   所有附件内容的输入流InputStream ，用ArrayList存放，与名称一一对应
     * @param priority   邮件的重要性参数 3：普通 2：重要 4：紧急
     *
     * @return boolean 邮件发送成功，返回 true，否则，返回false
     */
    public boolean sendMiltipartHtml(String from, String to, String cc, String bcc, String subject, String body, int char_set, ArrayList filenames, ArrayList filecontents, String priority) {
        return this.newSendMailNoEx(from, to, cc, bcc, subject, char_set, body, null, filenames, filecontents, 0, null, isSendApart, priority, needReceipt, true);
    }

    /**
     * 发送带附件的邮件,HTML内容中包含图片
     *
     * @param from  邮件的发件人参数
     * @param to    邮件的收件人参数，多个收件人之间用逗号隔开
     * @param cc    邮件的抄送人参数，多个抄送人之间用逗号隔开
     * @param bcc   邮件的暗送人参数，多个暗送人之间用逗号隔开
     * @param subject    邮件的主题参数（采用ISO8859编码格式）
     * @param body       邮件的正文参数（采用ISO8859编码格式）
     * @param char_set   编码方式 1：iso-8859-1 2：big5 3：GBK
     * @param filenames   所有附件的名称，用ArrayList存放，与内容一一对应
     * @param filecontents   所有附件内容的输入流InputStream ，用ArrayList存放，与名称一一对应
     * @param priority   邮件的重要性参数 3：普通 2：重要 4：紧急
     * @param imgnames   HTML内容中包含的图片
     *
     * @return boolean 邮件发送成功，返回 true，否则，返回false
     */
    public boolean sendMiltipartHtml(String from, String to, String cc, String bcc, String subject, String body, int char_set, ArrayList filenames, ArrayList filecontents, String priority, Hashtable imgnames, int mailid, List<EmailSendFileOldEntity> fileList) {
        return this.newSendMailNoEx(from, to, cc, bcc, subject, char_set, body, imgnames, filenames, filecontents, mailid, fileList, isSendApart, priority, needReceipt, true);
    }
    
    /**
     * 此方法通过map传附件已经无效，请不要使用！！！
     */
    @Deprecated
    public boolean sendMiltipartHtml(String from, String to, String cc, String bcc, String subject, String body, int char_set, ArrayList filenames, ArrayList filecontents, String priority, Hashtable imgnames, int mailid, Map map) {
        return this.newSendMailNoEx(from, to, cc, bcc, subject, char_set, body, imgnames, filenames, filecontents, mailid, null, isSendApart, priority, needReceipt, true);
    }

    /**
     * 发送带附件的邮件
     *
     * @param from  邮件的发件人参数
     * @param to    邮件的收件人参数，多个收件人之间用逗号隔开
     * @param cc    邮件的抄送人参数，多个抄送人之间用逗号隔开
     * @param bcc   邮件的暗送人参数，多个暗送人之间用逗号隔开
     * @param subject    邮件的主题参数（采用ISO8859编码格式）
     * @param body       邮件的正文参数（采用ISO8859编码格式）
     * @param filenames   所有附件的名称，用ArrayList存放，与内容一一对应
     * @param filecontents   所有附件内容的输入流InputStream ，用ArrayList存放，与名称一一对应
     * @param priority   邮件的重要性参数 3：普通 2：重要 4：紧急
     *
     * @return boolean 邮件发送成功，返回 true，否则，返回false
     */
    public boolean sendMiltipartText(String from, String to, String cc, String bcc, String subject, String body, ArrayList filenames, ArrayList filecontents, String priority, List<EmailSendFileOldEntity> fileList) {
        return this.newSendMailNoEx(from, to, cc, bcc, subject, 3, body, null, filenames, filecontents, 0, fileList, isSendApart, priority, needReceipt, false);
    }
    
    /**
     * 此方法通过map传附件已经无效，请不要使用！！！
     */
    @Deprecated
    public boolean sendMiltipartText(String from, String to, String cc, String bcc, String subject, String body, ArrayList filenames, ArrayList filecontents, String priority, Map map) {
        return this.newSendMailNoEx(from, to, cc, bcc, subject, 3, body, null, filenames, filecontents, 0, null, isSendApart, priority, needReceipt, false);
    }


    /**
     * 发送带附件的邮件
     *
     * @param from  邮件的发件人参数
     * @param to    邮件的收件人参数，多个收件人之间用逗号隔开
     * @param subject    邮件的主题参数（采用ISO8859编码格式）
     * @param body       邮件的正文参数（采用ISO8859编码格式）
     * @param filePathList   所有附件路径
     *
     * @return boolean 邮件发送成功，返回 true，否则，返回false
     */
    public boolean sendFileMail(String from, String to, String subject, String body, ArrayList<String> filePathList) {

        Map file = getFileContentByPath(filePathList);
        ArrayList filenames = (ArrayList) file.get("fileNameList");
        Map map = (Map) file.get("fileMap");
        Session _session = null;

        Properties props = new Properties();
        props.put("mail.smtp.from", from);
        props.put("mail.from", from);

        _session = setSSLConnectMsg(_session, props);
        MimeMessage msg = new MimeMessage(_session);
        try {
            msg.setFrom(new InternetAddress(from, this.accountName));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, true));
            int bodyfilesize = filenames.size();
            MimeBodyPart mbp[] = new MimeBodyPart[bodyfilesize + 1];
            for (int i = 0; i < bodyfilesize + 1; i++) {
                mbp[i] = new MimeBodyPart();
            }
            Multipart mp = new MimeMultipart();

            mbp[0].setText(body);
            mp.addBodyPart(mbp[0]);

            Iterator it = map.entrySet().iterator();
            ArrayList dateList1 = new ArrayList();
            ArrayList dateList2 = new ArrayList();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String key = (String) entry.getKey();
                DataHandler value = (DataHandler) entry.getValue();
                dateList1.add(key);
                dateList2.add(value);
            }
            for (int i = 0; i < dateList1.size(); i++) {
                String key = (String) dateList1.get(i);
                DataHandler value = (DataHandler) dateList2.get(i);
                mbp[i + 1].setDataHandler(value);
                mbp[i + 1].setFileName(key);
                mp.addBodyPart(mbp[i + 1]);
            }

            msg.setContent(mp);
            msg.setSubject(subject, "UTF-8");
            msg.setSentDate(new Date());
            msg.setHeader("X-Mailer", "weaver");
            if (null != this.needReceipt && "1".equals(this.needReceipt)) {// 需要回执
                msg.setHeader("Disposition-Notification-To", from); // from为发送者邮件地址
            }
            msg.setHeader("X-Priority", "3");

            Transport.send(msg);

            return true;
        } catch (Exception e) {
            logBean.writeLog("method:sendMiltipartText, from=" + from + ",subject=" + subject + ",to=" + to);
            logBean.writeLog(MailCommonUtils.getStackTrace(e));
            return false;
        }
    }

    /**
     * 获得附件流对象
     * @param filePathList  附件路径
     * @return
     */
    private Map<String, Object> getFileContentByPath(ArrayList<String> filePathList) {

        ArrayList fileContentList = new ArrayList();
        ArrayList fileNameList = new ArrayList();
        Map fileMap = new HashMap();
        Map map = new HashMap();
        String fileName = "";
        String filePath = "";
        // 获取正确的附件留信息
        try {
            for (int i = 0; i < filePathList.size(); i++) {
                InputStream source = null;
                filePath = filePathList.get(i);
                File thefile = new File(filePath);
                source = new BufferedInputStream(new FileInputStream(thefile));
                fileName = thefile.getName();
                fileContentList.add(source);
                fileNameList.add(fileName);
            }
            for (int i = 0, bodyfilesize = fileNameList.size(); i < bodyfilesize; i++) {
                InputStream is = (InputStream) fileContentList.get(i);
                String filename = (String) fileNameList.get(i);
                String ctype = FileTypeMap.getDefaultFileTypeMap().getContentType(filename);
                sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                filename = "=?UTF-8?B?" + enc.encode(filename.getBytes("UTF-8")) + "?=";
                filename = filename.replace("\n", ""); // 当文件名过长时
                StringBuffer sb = new StringBuffer(filename.length()); // 需要
                for (int j = 0; j < filename.length(); j++) { // 过滤换行和无用符号
                    if (filename.getBytes()[j] == 13) {
                        continue;
                    }
                    sb.append(filename.charAt(j));
                }
                DataHandler da = new DataHandler(new weaver.general.ByteArrayDataSource(is, ctype));
                fileMap.put(sb.toString(), da);
            }
            map.put("fileNameList", fileNameList);
            map.put("fileMap", fileMap);
        } catch (Exception e) {
            writeLog("getFileContentByPath 获取附件留信息错误!");
            writeLog(e);
        }
        return map;
    }


    private List processBodyImg(String body) {
        if (this.isDebug) {
//          System.out.println("Body===============================");
//          System.out.println(body);
        }
        return null;
    }


    //####### 支持exchange协议之后，替换老的发送方法为新的形式
    //新的发送方式
    private boolean newSendMailNoEx(String from, String to, String cc, String bcc, String subject,
                                    int char_set, String body, Hashtable imgnames, ArrayList filenames, ArrayList filecontents, int mailid,
                                    List<EmailSendFileOldEntity> fileList, boolean isSendApart, String priority, String needReceipt, boolean isHtmlMode) {
        boolean sendResult = false;
        EmailSend emailSend = new EmailSend();
        try {
            sendResult = this.newSendMail(emailSend, from, to, cc, bcc, subject, char_set, body, imgnames, filenames, filecontents, mailid, fileList, isSendApart, priority, needReceipt, isHtmlMode);
        } catch (Exception e) {
            sendResult = false;

            if (mailid > 0) { //邮件模块发送时，增加异常信息
                MailErrorMessageInfo merinfo = new MailErrorFormat(e).getMailErrorMessageInfo();
                emailSend.setErrorMess(merinfo.toString());

                setErrorMess(merinfo.toString());

                //记录发信错误异常信息
                EmailCommonUtils.recordEmailSendErrorinfo(mailid, merinfo);
            }

            logBean.writeLog("发送异常， from=" + from + ",subject=" + subject + ",mailid=" + mailid + ",isSendApart=" + isSendApart + ",isHtmlMode=" + isHtmlMode);
            logBean.writeLog(e);
        }
        return sendResult;
    }

    //新的发送方式
    private boolean newSendMail(EmailSend emailSend, String from, String to, String cc, String bcc, String subject,
                                int char_set, String body, Hashtable imgnames, ArrayList filenames, ArrayList filecontents, int mailid,
                                List<EmailSendFileOldEntity> fileList, boolean isSendApart, String priority, String needReceipt, boolean isHtmlMode) throws Exception {

        EmailSenderEntity sender = emailSend.initSenderBySendMail(protocolType, from, username, password, mailserver, needauthsend, needSSL, smtpServerPort, accountName, isStartTls);
        EmailSendEntity ese = emailSend.packParameterToEntity(from, to, cc, bcc, subject, char_set, body, imgnames, filenames, filecontents, mailid, fileList, isSendApart, priority, needReceipt, isHtmlMode);
        //兼容新方法的额外设置
        ese.getFrom().setNickname(accountName); //发件人昵称
        emailSend.sendMail(sender, ese);

        return true;
    }

}




