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

📄 mailutil.java

📁 解觖java技术中后台无法上传数给的情况
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * $Header: /cvsroot/mvnforum/myvietnam/src/net/myvietnam/mvncore/util/MailUtil.java,v 1.38 2006/04/15 02:59:20 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.38 $
 * $Date: 2006/04/15 02:59:20 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2006 by MyVietnam.net
 *
 * All copyright notices regarding MyVietnam and MyVietnam CoreLib
 * MUST remain intact in the scripts and source code.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Correspondence and Marketing Questions can be sent to:
 * info at MyVietnam net
 *
 * @author: Minh Nguyen  
 * @author: Mai  Nguyen  
 */
package net.myvietnam.mvncore.util;

import java.io.UnsupportedEncodingException;
import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import net.myvietnam.mvncore.MVNCoreConfig;
import net.myvietnam.mvncore.exception.BadInputException;
import net.myvietnam.mvncore.filter.DisableHtmlTagFilter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class MailUtil {

    public static final int MAX_MESSAGES_PER_TRANSPORT = 100;

    private static Log log = LogFactory.getLog(MailUtil.class);

    private MailUtil() {// prevent instantiation
    }

    //private static MailOptions mailOption = new MailOptions();

    /**
     * Get the user name part of an email. Ex: input: test@yahoo.com => output: test
     * @param email String the email
     * @return String the user name part of an email
     */
    public static String getEmailUsername(String email) {
        if (email == null) return "";
        int atIndex = email.indexOf('@');
        if (atIndex == -1) {
            return "";
        }
        return email.substring(0, atIndex);
    }

    /**
     * Get the domain part of an email. Ex: input: test@yahoo.com => output: yahoo.com
     * @param email String the email
     * @return String the user name part of an email
     */
    public static String getEmailDomain(String email) {
        if (email == null) return "";
        int atIndex = email.indexOf('@');
        if (atIndex == -1) {
            return "";
        }
        return email.substring(atIndex + 1);
    }

    /**
     * Check if an email is good and safe or not.
     * This method should be use for all email input from user
     * @param input String
     * @throws BadInputException if email is not good
     */
    public static void checkGoodEmail(String input) throws BadInputException {
        if (input == null) throw new BadInputException("Sorry, null string is not a good email.");//@todo : localize me
        int atIndex = input.indexOf('@');
        int dotIndex = input.lastIndexOf('.');
        if ((atIndex == -1) || (dotIndex == -1) || (atIndex >= dotIndex)) {
            //@todo : localize me
            throw new BadInputException("Error: '" + DisableHtmlTagFilter.filter(input) + "' is not a valid email value. Please try again.");
        }

        // now check for content of the string
        int length = input.length();
        char c = 0;

        for (int i = 0; i < length; i++) {
            c = input.charAt(i);
            if ((c >= 'a') && (c <= 'z')) {
                // lower char
            } else if ((c >= 'A') && (c <= 'Z')) {
                // upper char
            } else if ((c >= '0') && (c <= '9')/* && (i != 0)*/) {
                // as of 31 Jan 2004, i relax the email checking
                // so that the email can start with an numeric char
                // hopefully it does not introduce a security bug
                // because this value will be inserted into sql script

                // numeric char
            } else if ( ( (c=='_') || (c=='-') || (c=='.') || (c=='@') ) && (i != 0) ) {
                // _ char
            } else {
                // not good char, throw an BadInputException
                //@todo : localize me
                throw new BadInputException(input + " is not a valid email. Reason: character '" + c + "' is not accepted in an email.");
            }
        }// for

        // last check
        try {
            new javax.mail.internet.InternetAddress(input);
        } catch (Exception ex) {
            log.error("Error when running checkGoodEmail", ex);
            throw new BadInputException("Assertion: dont want to occur in Util.checkGoodEmail");
        }
    }

    /**
     * NOTE: param to, cc, bcc cannot be all empty. At least one must have a valid value
     * @param from : must be a valid email. However, if this param is null,
     *              then the default mail in config file will be use
     * @param to : can be null
     * @param cc : can be null
     * @param bcc: can be null
     * @param subject
     * @param message
     * @throws MessagingException
     * @throws BadInputException
     */
    public static void sendMail(String from, String to, String cc, String bcc, String subject, String message)
        throws MessagingException, BadInputException, UnsupportedEncodingException {

        MailMessageStruct mailItem = new MailMessageStruct();
        mailItem.setFrom(from);
        mailItem.setTo(to);
        mailItem.setCc(cc);
        mailItem.setBcc(bcc);
        mailItem.setSubject(subject);
        mailItem.setMessage(message);

        sendMail(mailItem);
    }

    public static void sendMail(MailMessageStruct mailItem)
        throws MessagingException, BadInputException, UnsupportedEncodingException {

        ArrayList mailList = new ArrayList(1);
        mailList.add(mailItem);
        try {
            sendMail(mailList);
        } catch (MessagingException mex) {
            log.error("MessagingException has occured.", mex);
            log.debug("MessagingException has occured. Detail info:");
            log.debug("from = " + mailItem.getFrom());
            log.debug("to = " + mailItem.getTo());
            log.debug("cc = " + mailItem.getCc());
            log.debug("bcc = " + mailItem.getBcc());
            log.debug("subject = " + mailItem.getSubject());
            log.debug("message = " + mailItem.getMessage());
            throw mex;// this may look redundant, but it is not :-)
        }
    }

    public static void sendMail(Collection mailStructCollection)
        throws MessagingException, BadInputException, UnsupportedEncodingException {

        Session session = null;
        Transport transport = null;
        int totalEmails = mailStructCollection.size();
        int count = 0;
        int sendFailedExceptionCount = 0;

        String server = "";
        String userName = "";
        String password = "";
        int port = 25;

        boolean useMailsource = MVNCoreConfig.isUseMailSource();

        try {
            for (Iterator iter = mailStructCollection.iterator(); iter.hasNext(); ) {
                count++;

                if ((transport == null) || (session == null)) {
                    if (useMailsource) {

⌨️ 快捷键说明

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