email.java

来自「jetspeed源代码」· Java 代码 · 共 1,221 行 · 第 1/3 页

JAVA
1,221
字号
/*
 * Copyright 2000-2001,2004 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.jetspeed.modules.actions.portlets.email;

//JavaMail

import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Folder;
import javax.mail.AuthenticationFailedException;
import javax.mail.NoSuchProviderException;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.Address;
import javax.mail.Multipart;
import javax.mail.Flags;
import javax.mail.Part;
import javax.mail.Header;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.DataHandler;

import com.sun.mail.imap.IMAPFolder;

import org.apache.turbine.util.upload.FileItem;
import org.apache.turbine.services.servlet.TurbineServlet;

import java.io.File;

//util
import java.util.List;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import java.util.Hashtable;

//tdk2.2 version
import org.apache.torque.util.Criteria;

import org.apache.jetspeed.om.apps.email.EmailInboxPeer;
import org.apache.jetspeed.om.apps.email.EmailInbox;

//for logging
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Email
{

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

    private Properties props;

    private Session session;

    private Store store;

    private Folder folder;

    private Hashtable parameters;

    /**
     * Email Action
     * 
     * @author <a href="mailto:jlim@gluecode.com">Jonas Lim </a>
     * @version $Id: Email.java,v 1.2 2004/03/22 22:26:58 taylor Exp $
     */
    public Email(String user, String pass, Hashtable param)
            throws AuthenticationFailedException, NoSuchProviderException,
            Exception
    {

        parameters = param;
        String host = (String) parameters.get("hostname");
        String protocol = (String) parameters.get("protocol");
        String smtpUser = (String) parameters.get("smtp_user");
        String smtpPort = (String) parameters.get("smtp_port");
        String smtpFrom = (String) parameters.get("smtp_from");
        String smtpConnTimeout = (String) parameters.get("smtp_conn_timeout");
        String smptTimeout = (String) parameters.get("smtp_timeout");
        String smtpLocalhost = (String) parameters.get("smtp_localhost");
        String smtpEhlo = (String) parameters.get("smtp_ehlo");
        String smtpAuth = (String) parameters.get("smtp_auth");
        String smtpDSNNotify = (String) parameters.get("smtp_dsn_notify");
        String smtpDSNRet = (String) parameters.get("smtp_dsn_ret");
        String smtpallow8bitmime = (String) parameters
                .get("smtp_allow8bitmime");
        String smtpsendPartial = (String) parameters.get("smtp_send_partial");
        String smtpSaslrealm = (String) parameters.get("smtp_sasl_realm");
        String smtpquitWait = (String) parameters.get("smtp_quit_wait");
        String imapPort = null;
        String imapPartialfetch = null;
        String imapFetchsize = null;
        String imapTimeout = null;
        String imapHost = null;

        if (protocol.equals("imap"))
        {
            imapPort = (String) parameters.get("imap_port");
            imapPartialfetch = (String) parameters.get("imap_partial_fetch");
            imapFetchsize = (String) parameters.get("imap_fetch_size");
            imapTimeout = (String) parameters.get("imap_timeout");
            imapHost = (String) parameters.get("imap_host");
        }

        props = new Properties();
        props.put("mail.smtp.host", host);
        if (!smtpUser.equals(""))
        {
            props.put("mail.smtp.user", smtpUser);
        }
        if (!smtpPort.equals(""))
        {
            props.put("mail.smtp.port", smtpPort);
        }
        if (!smtpFrom.equals(""))
        {
            props.put("mail.smtp.from", smtpFrom);
        }
        if (!smtpConnTimeout.equals(""))
        {
            props.put("mail.smtp.connectiontimeout", smtpConnTimeout);
        }
        if (!smptTimeout.equals(""))
        {
            props.put("mail.smtp.timeout", smptTimeout);
        }
        if (!smtpLocalhost.equals(""))
        {
            props.put("mail.smtp.localhost", smtpLocalhost);
        }
        if (!smtpEhlo.equals(""))
        {
            props.put("mail.smtp.ehlo", smtpEhlo);
        }
        if (!smtpAuth.equals(""))
        {
            props.put("mail.smtp.auth", smtpAuth);
        }
        if (!smtpDSNNotify.equals(""))
        {
            props.put("mail.smtp.dsn.notify", smtpDSNNotify);
        }
        if (!smtpDSNRet.equals(""))
        {
            props.put("mail.smtp.dsn.ret", smtpDSNRet);
        }
        if (!smtpallow8bitmime.equals(""))
        {
            props.put("mail.smtp.allow8bitmime", smtpallow8bitmime);
        }
        if (!smtpsendPartial.equals(""))
        {
            props.put("mail.smtp.sendpartial", smtpsendPartial);
        }
        if (!smtpSaslrealm.equals(""))
        {
            props.put("mail.smtp.saslrealm", smtpSaslrealm);
        }
        if (!smtpquitWait.equals(""))
        {
            props.put("mail.smtp.quitwait", smtpquitWait);
        }

        if (protocol.equals("imap"))
        {
            if ((imapPort != null) && (!imapPort.equals("")))
            {
                props.put("mail.imap.port", imapPort);
            }
            if ((imapPartialfetch != null) && (!imapPartialfetch.equals("")))
            {
                props.put("mail.imap.partialfetch", imapPartialfetch);
            }
            if ((imapFetchsize != null) && (!imapFetchsize.equals("")))
            {
                props.put("mail.imap.fetchsize", imapFetchsize);
            }
            if ((imapTimeout != null) && (!imapTimeout.equals("")))
            {
                props.put("mail.imap.timeout", imapTimeout);
            }
            if ((imapHost != null) && (!imapHost.equals("")))
            {
                props.put("mail.imap.host", imapHost);
            }
        }
        // Get session
        session = Session.getDefaultInstance(props, null);
        // Get the store
        //store = session.getStore("imap");
        store = session.getStore(protocol);
        

        store.connect(host, user, pass);
       //  boolean b = store.isConnected();
        folder = store.getFolder("INBOX");

    }

    public void authenticateUser(String user, String pass)
            throws AuthenticationFailedException, NoSuchProviderException,
            Exception
    {
        String protocol = (String) parameters.get("protocol");
        String host = (String) parameters.get("hostname");
        // Create empty properties
        Properties props = new Properties();
        props.put("mail.smtp.host", host);

        // Get session
        Session session = Session.getDefaultInstance(props, null);
        // Get the store
        //Stofalsere store = session.getStore("imap");
        Store store = session.getStore(protocol);
        store.connect(host, user, pass);

       
    }

    public void doSendEmail(String addressTo, String addressFrom,
            String subject, String msg, FileItem file) throws Exception
    {

        Session session = Session.getDefaultInstance(props, null);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(addressFrom));

        checkRecipients(addressTo, message);

        // if no subject, default as none
        if (subject.equals(""))
        {
            subject = "none";
        }

        message.setSubject(subject);

        // Part two is attachment
        // check if there's an attachment to be sent
        if (file != null && !file.equals(""))
        {
            sendAttachment(message, file, msg);
        } else
        {
            log.info("file null or space " + file);
            message.setText(msg);
        }

        Transport.send(message);

        if (file != null)
        { // delete the file after being uploaded
            //deleteUploadedfile(file);
        }
    }

    public void uploadAttachment(FileItem fileItem) throws Exception
    {

        log.info("upload attachment");
        //String contentType = fileItem.getContentType();
        java.io.File file1 = new java.io.File(fileItem.getFileName());

        String filePath = file1.getAbsolutePath();
        int d = filePath.lastIndexOf(File.separator);
        String b = filePath.substring(d + 1);
        String filename = b;

        fileItem.write(getAttachmentsFolder() + File.separator + filename);

    }

    public void deleteUploadedfile(FileItem file) throws Exception
    {
        {
            log.info("delete uploaded file");
            java.io.File fn = new java.io.File(file.getFileName());
            String filename = fn.getName();
            String realPath = getAttachmentsFolder();

            File fDelete = new File(realPath + File.separator + filename);
            System.out.println("deleted file : " + fDelete);
            fDelete.delete();
        }

    }

    //check if it's a single/multiple recipients
    public void checkRecipients(String addressTo, Message message)
            throws Exception
    {
        String recipient = null;
        int startIndex = 0;
        int semicolonIndex = 0;
        int lastsemicolonIndex = 0;

        try
        {
            if (addressTo.indexOf(";", 0) == -1)
            {
                log.info("addr" + addressTo.indexOf(";", 0));
                message.setRecipients(Message.RecipientType.TO, InternetAddress
                        .parse(addressTo, false));
            } else
            {
                while ((semicolonIndex = addressTo.indexOf(";", startIndex)) != -1)
                {
                    recipient = addressTo.substring(startIndex, semicolonIndex);
                    startIndex = semicolonIndex + 1;
                    lastsemicolonIndex = semicolonIndex;
                    message.addRecipient(Message.RecipientType.TO,
                            new InternetAddress(recipient));

                }
                recipient = addressTo.substring(lastsemicolonIndex + 1);
                message.addRecipient(Message.RecipientType.TO,
                        new InternetAddress(recipient));
                log.info("recipient" + recipient);
            }
            Address a[] = message.getAllRecipients();
            for (int j = 0; j < a.length; j++)
            {
                log.info("address" + a[j]);
            }

        } catch (Exception e)
        {
            log.error("Error in checkRecepients()",e);
        }
    }

    public void sendAttachment(Message message, FileItem file, String msg)
            throws Exception
    {

        log.info("file not null or space " + file);

        uploadAttachment(file);

        java.io.File fn = new java.io.File(file.getFileName());
        String filename = fn.getName();

        //set the message
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        //messageBodyPart.setText(msg);
        messageBodyPart.setContent(msg, "text/html");

        MimeBodyPart messageBodyPart2 = new MimeBodyPart();

        DataSource source = new FileDataSource(getAttachmentsFolder()
                + File.separator + filename);

        // Set the data handler to the attachment
        messageBodyPart2.setDataHandler(new DataHandler(source));

        // Set the filename
        messageBodyPart2.setFileName(filename.toString());

        // Add the message part and attachment
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        multipart.addBodyPart(messageBodyPart2);

        // Put parts in message
        message.setContent(multipart);

    }

    public void reply(String from, String addressTo, String msgecontent,
            String subject, FileItem file, Message msge) throws Exception
    {

        //since the folder in getMessage method (getting the exact message) is
        // opened,re-opening the folder may cause an error
        //folder.open(Folder.READ_ONLY);

        //Message cmessage[] = folder.getMessages();
        //MimeMessage message = (MimeMessage)msge[current_index].reply(false);

        MimeMessage message = (MimeMessage) msge.reply(false);

        message.setFrom(new InternetAddress(from));

        checkRecipients(addressTo, message);

        message.setSubject(subject);

⌨️ 快捷键说明

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