⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mailutil.java

📁 解觖java技术中后台无法上传数给的情况
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
                        try {
                            InitialContext ic = new InitialContext();
                            // mailSourceName = "java:comp/env/mail/mailSession";
                            String mailSourceName = MVNCoreConfig.getMailSourceName();
                            log.debug("MailUtil : use mailsource = " + mailSourceName);
                            session = (Session) ic.lookup("java:comp/env/" + mailSourceName);
                            transport = session.getTransport("smtp");
                        } catch (NamingException e) {
                            log.error("Cannot get Mail session", e);
                            throw new MessagingException("Cannot get the mail session from JNDI. Send mail failed.");
                        }
                    } else {// does not use datasourse
                        Properties props = new Properties();

                        server = MVNCoreConfig.getMailServer();
                        port = MVNCoreConfig.getMailServerPort();
                        userName = MVNCoreConfig.getMailUserName();
                        password = MVNCoreConfig.getMailPassword();

                        props.put("mail.smtp.host", server);
                        props.put("mail.smtp.port", String.valueOf(port));
                        if ((userName != null) && (userName.length() > 0)) {
                            props.put("mail.smtp.auth", "true");
                        }
                        //props.put("mail.debug", "true");
                        session = Session.getDefaultInstance(props, null);
                        transport = session.getTransport("smtp");
                    }// end of does not use datasource

                    if ((userName != null) && (userName.length() > 0)) {
                        transport.connect(server, userName, password);
                    } else {
                        transport.connect();
                    }
                }

                MailMessageStruct mailItem = (MailMessageStruct)iter.next();

                String from = mailItem.getFrom();
                String to = mailItem.getTo();
                String cc = mailItem.getCc();
                String bcc = mailItem.getBcc();
                String subject = mailItem.getSubject();
                String message = mailItem.getMessage();

                //if (from == null) from = mailOption.defaultMailFrom;
                if (from == null) from = MVNCoreConfig.getDefaultMailFrom();

                try {
                    // this will also check for email error
                    checkGoodEmail(from);
                    InternetAddress fromAddress = new InternetAddress(from);
                    InternetAddress[] toAddress = getInternetAddressEmails(to);
                    InternetAddress[] ccAddress = getInternetAddressEmails(cc);
                    InternetAddress[] bccAddress = getInternetAddressEmails(bcc);
                    if ((toAddress == null) && (ccAddress == null) && (bccAddress == null)) {
                        //@todo : localize me
                        throw new BadInputException("Cannot send mail since all To, Cc, Bcc addresses are empty.");
                    }

                    // create a message
                    MimeMessage msg = new MimeMessage(session);
                    msg.setSentDate(new Date());
                    msg.setFrom(fromAddress);

                    if (toAddress != null) {
                        msg.setRecipients(Message.RecipientType.TO, toAddress);
                    }
                    if (ccAddress != null) {
                        msg.setRecipients(Message.RecipientType.CC, ccAddress);
                    }
                    if (bccAddress != null) {
                        msg.setRecipients(Message.RecipientType.BCC, bccAddress);
                    }
                    //This code is use to display unicode in Subject
                    //msg.setSubject(MimeUtility.encodeText(subject, "iso-8859-1", "Q"));
                    //msg.setText(message);
                    //String content = new String(message.getBytes(""), "UTF-8");
                    msg.setSubject(subject, "UTF-8");
                    msg.setText(message, "UTF-8");

                    /*
                     //Below code is use for unicode
                     MimeBodyPart messageBodyPart = new MimeBodyPart();
                     messageBodyPart.setText(message);
                     messageBodyPart.setHeader("Content-Type", "text/html;charset=iso-8859-1");
                     messageBodyPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
                     MimeMultipart multipart = new MimeMultipart("alternative");
                     multipart.addBodyPart(messageBodyPart);
                     msg.setContent(multipart);
                     */
                    msg.saveChanges();

                    transport.sendMessage(msg, msg.getAllRecipients());

                    // now check if sent 100 emails, then close connection (transport)
                    if ((count % MAX_MESSAGES_PER_TRANSPORT) == 0) {
                        try {
                            if (transport != null) transport.close();
                        } catch (MessagingException ex) {}
                        transport = null;
                        session = null;
                    }

                } catch (SendFailedException ex) {
                    sendFailedExceptionCount++;
                    log.error("SendFailedException has occured.", ex);
                    log.warn("SendFailedException has occured. Detail info:");
                    log.warn("from = " + from);
                    log.warn("to = " + to);
                    log.warn("cc = " + cc);
                    log.warn("bcc = " + bcc);
                    log.warn("subject = " + subject);
                    log.info("message = " + message);
                    if ((totalEmails != 1) && (sendFailedExceptionCount > 10)) {
                        throw ex;// this may look redundant, but it is not :-)
                    }
                } catch (MessagingException mex) {
                    log.error("MessagingException has occured.", mex);
                    log.warn("MessagingException has occured. Detail info:");
                    log.warn("from = " + from);
                    log.warn("to = " + to);
                    log.warn("cc = " + cc);
                    log.warn("bcc = " + bcc);
                    log.warn("subject = " + subject);
                    log.info("message = " + message);
                    throw mex;// this may look redundant, but it is not :-)
                }
            }//for
        } finally {
            try {
                if (transport != null) transport.close();
            } catch (MessagingException ex) { }
            if (totalEmails != 1) {
                log.info("sendMail: totalEmails = " + totalEmails + " sent count = " + count);
            }
        }
    }

    /**
     * This method trim the email variable, so if it contains only spaces,
     * then it will be empty string, then we have 0 token :-)
     * The returned value is never null
     */
    public static String[] getEmails(String email) throws BadInputException {
        if (email == null) email = "";
        email = email.trim();// very important
        email = email.replace(',', ';');// replace all occurrence of ',' to ';'
        StringTokenizer t = new StringTokenizer(email, ";");
        String[] ret = new String[t.countTokens()];
        int index = 0;
        while(t.hasMoreTokens()) {
            String mail = t.nextToken().trim();
            checkGoodEmail(mail);
            ret[index] = mail;
            //log.debug(ret[index]);
            index++;
        }
        return ret;
    }

    public static String[] getEmails(String to, String cc, String bcc) throws BadInputException {
        String[] toMail = getEmails(to);
        String[] ccMail = getEmails(cc);
        String[] bccMail= getEmails(bcc);
        String[] ret = new String[toMail.length + ccMail.length + bccMail.length];
        int index = 0;
        for (int i = 0; i < toMail.length; i++) {
            ret[index] = toMail[i];
            index++;
        }
        for (int i = 0; i < ccMail.length; i++) {
            ret[index] = ccMail[i];
            index++;
        }
        for (int i = 0; i < bccMail.length; i++) {
            ret[index] = bccMail[i];
            index++;
        }
        return ret;
    }

    /**
     * This method will return null if there is not any email
     *
     * @param email
     * @return
     * @throws BadInputException
     * @throws AddressException
     */
    private static InternetAddress[] getInternetAddressEmails(String email)
        throws BadInputException, AddressException {
        String[] mails = getEmails(email);
        if (mails.length == 0) return null;// must return null, not empty array

        //log.debug("to = " + mails);
        InternetAddress[] address = new InternetAddress[mails.length];
        for (int i = 0; i < mails.length; i++) {
            address[i] = new InternetAddress(mails[i]);
            //log.debug("to each element = " + mails[i]);
        }
        return address;
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -