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

📄 mailutil.java

📁 java servlet著名论坛源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * $Header: /cvsroot/mvnforum/myvietnam/src/net/myvietnam/mvncore/util/MailUtil.java,v 1.26 2004/06/24 12:57:31 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.26 $
 * $Date: 2004/06/24 12:57:31 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2004 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding MyVietnam and MyVietnam CoreLib
 * MUST remain intact in the scripts and source code.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 * @author: Mai  Nguyen  mai.nh@MyVietnam.net
 */
package net.myvietnam.mvncore.util;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;

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

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 "";
        } else {
            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 "";
        } else {
            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.");
        int atIndex = input.indexOf('@');
        int dotIndex = input.lastIndexOf('.');
        if ((atIndex == -1) || (dotIndex == -1) || (atIndex >= dotIndex))
            throw new BadInputException("Error: '" + DisableHtmlTagFilter.filter(input) + "' is not a valid email value. Please try again.");
        // now check for content of the string
        byte[] s = input.getBytes();
        int length = s.length;
        byte b = 0;

        for (int i = 0; i < length; i++) {
            b = s[i];
            if ((b >= 'a') && (b <= 'z')) {
                // lower char
            } else if ((b >= 'A') && (b <= 'Z')) {
                // upper char
            } else if ((b >= '0') && (b <= '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 ( ( (b=='_') || (b=='-') || (b=='.') || (b=='@') ) && (i != 0) ) {
                // _ char
            } else {
                // not good char, throw an BadInputException
                throw new BadInputException(input + " is not a valid email. Reason: character '" + (char)(b) + "' 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);
    }

    /**
     * Old method, to be removed later
     */
    public static void sendMailOld(String from, String to, String cc, String bcc, String subject, String message)
        throws MessagingException, BadInputException, UnsupportedEncodingException {

        if (from == null) from = mailOption.defaultMailFrom;

        // 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)) {
            throw new BadInputException("Cannot send mail since all To, Cc, Bcc addresses are empty.");
        }

        Properties props = new Properties();
        props.put("mail.smtp.host", mailOption.mailServer);
        props.put("mail.smtp.port", String.valueOf(mailOption.port));
        if ( (mailOption.username != null) && (mailOption.username.length() > 0) ) {
            props.put("mail.smtp.auth", "true");
            //props.put("mail.user", mailOption.mailServer);
            //props.put("mail.password", mailOption.mailServer);
        }
        //props.put("mail.debug", "true");

        Transport transport = null;
        try {
            Session session = Session.getDefaultInstance(props, null);
            transport = session.getTransport("smtp");
            if ( (mailOption.username != null) && (mailOption.username.length() > 0) ) {
                transport.connect(mailOption.mailServer, mailOption.username, mailOption.password);
            } else {
                transport.connect();
            }
            // create a message
            Message 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);

            /*
            //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());
        } catch (MessagingException mex) {
            log.error("MessagingException has occured.", mex);
            log.debug("MessagingException has occured. Detail info:");
            log.debug("from = " + from);
            log.debug("to = " + to);

⌨️ 快捷键说明

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