Example usage for javax.mail MessagingException getMessage

List of usage examples for javax.mail MessagingException getMessage

Introduction

In this page you can find the example usage for javax.mail MessagingException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Writes a passed payload part to the passed message object. 
 *//*from  ww  w  .j  a  va2 s . co m*/
public void writePayloadsToMessage(Part payloadPart, AS2Message message, Properties header) throws Exception {
    List<Part> attachmentList = new ArrayList<Part>();
    AS2Info info = message.getAS2Info();
    if (!info.isMDN()) {
        AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
        if (payloadPart.isMimeType("multipart/*")) {
            //check if it is a CEM
            if (payloadPart.getContentType().toLowerCase().contains("application/ediint-cert-exchange+xml")) {
                messageInfo.setMessageType(AS2Message.MESSAGETYPE_CEM);
                if (this.logger != null) {
                    this.logger.log(Level.FINE, this.rb.getResourceString("found.cem",
                            new Object[] { messageInfo.getMessageId(), message }), info);
                }
            }
            ByteArrayOutputStream mem = new ByteArrayOutputStream();
            payloadPart.writeTo(mem);
            mem.flush();
            mem.close();
            MimeMultipart multipart = new MimeMultipart(
                    new ByteArrayDataSource(mem.toByteArray(), payloadPart.getContentType()));
            //add all attachments to the message
            for (int i = 0; i < multipart.getCount(); i++) {
                //its possible that one of the bodyparts is the signature (for compressed/signed messages), skip the signature
                if (!multipart.getBodyPart(i).getContentType().toLowerCase().contains("pkcs7-signature")) {
                    attachmentList.add(multipart.getBodyPart(i));
                }
            }
        } else {
            attachmentList.add(payloadPart);
        }
    } else {
        //its a MDN, write whole part
        attachmentList.add(payloadPart);
    }
    //write the parts
    for (Part attachmentPart : attachmentList) {
        ByteArrayOutputStream payloadOut = new ByteArrayOutputStream();
        InputStream payloadIn = attachmentPart.getInputStream();
        this.copyStreams(payloadIn, payloadOut);
        payloadOut.flush();
        payloadOut.close();
        byte[] data = payloadOut.toByteArray();
        AS2Payload as2Payload = new AS2Payload();
        as2Payload.setData(data);
        String[] contentIdHeader = attachmentPart.getHeader("content-id");
        if (contentIdHeader != null && contentIdHeader.length > 0) {
            as2Payload.setContentId(contentIdHeader[0]);
        }
        String[] contentTypeHeader = attachmentPart.getHeader("content-type");
        if (contentTypeHeader != null && contentTypeHeader.length > 0) {
            as2Payload.setContentType(contentTypeHeader[0]);
        }
        try {
            as2Payload.setOriginalFilename(payloadPart.getFileName());
        } catch (MessagingException e) {
            if (this.logger != null) {
                this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                        new Object[] { info.getMessageId(), e.getMessage(), }), info);
            }
        }
        if (as2Payload.getOriginalFilename() == null) {
            String filenameheader = header.getProperty("content-disposition");
            if (filenameheader != null) {
                //test part for convinience: extract file name
                MimeBodyPart filenamePart = new MimeBodyPart();
                filenamePart.setHeader("content-disposition", filenameheader);
                try {
                    as2Payload.setOriginalFilename(filenamePart.getFileName());
                } catch (MessagingException e) {
                    if (this.logger != null) {
                        this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                                new Object[] { info.getMessageId(), e.getMessage(), }), info);
                    }
                }
            }
        }
        message.addPayload(as2Payload);
    }
}

From source file:org.exist.xquery.modules.mail.SendEmailFunction.java

public Sequence sendEmail(Sequence[] args, Sequence contextSequence) throws XPathException {
    // was a session handle specified?
    if (args[0].isEmpty()) {
        throw (new XPathException(this, "Session handle not specified"));
    }//from   www .ja v  a 2s .  c o m

    // get the Session
    long sessionHandle = ((IntegerValue) args[0].itemAt(0)).getLong();
    Session session = MailModule.retrieveSession(context, sessionHandle);
    if (session == null) {
        throw (new XPathException(this, "Invalid Session handle specified"));
    }

    try {
        List<Message> messages = parseInputEmails(session, args[1]);
        String proto = session.getProperty("mail.transport.protocol");
        if (proto == null)
            proto = "smtp";
        Transport t = session.getTransport(proto);
        try {
            if (session.getProperty("mail." + proto + ".auth") != null)
                t.connect(session.getProperty("mail." + proto + ".user"),
                        session.getProperty("mail." + proto + ".password"));
            for (Message msg : messages) {
                t.sendMessage(msg, msg.getAllRecipients());
            }
        } finally {
            t.close();
        }

        return (Sequence.EMPTY_SEQUENCE);
    } catch (TransformerException te) {
        throw new XPathException(this, "Could not Transform XHTML Message Body: " + te.getMessage(), te);
    } catch (MessagingException smtpe) {
        throw new XPathException(this, "Could not send message(s): " + smtpe.getMessage(), smtpe);
    } catch (IOException ioe) {
        throw new XPathException(this, "Attachment in some message could not be prepared: " + ioe.getMessage(),
                ioe);
    } catch (Throwable t) {
        throw new XPathException(this,
                "Unexpected error from JavaMail layer (Is your message well structured?): " + t.getMessage(),
                t);
    }
}

From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java

/**
 * The main method of this job. Called by confluence every time the mail2news trigger
 * fires./*from w w  w.j  av  a  2s  .  co m*/
 *
 * @see com.atlassian.quartz.jobs.AbstractJob#doExecute(org.quartz.JobExecutionContext)
 */
public void doExecute(JobExecutionContext arg0) throws JobExecutionException {

    /* The mailstore object used to connect to the server */
    Store store = null;

    try {

        this.log.info("Executing mail2news plugin.");

        /* check if we have all necessary components */
        if (pageManager == null) {
            throw new Exception("Null PageManager instance.");
        }
        if (spaceManager == null) {
            throw new Exception("Null SpaceManager instance.");
        }
        if (configurationManager == null) {
            throw new Exception("Null ConfigurationManager instance.");
        }

        /* get the mail configuration from the manager */
        MailConfiguration config = configurationManager.getMailConfiguration();
        if (config == null) {
            throw new Exception("Null MailConfiguration instance.");
        }

        /* create the properties for the session */
        Properties prop = new Properties();

        /* get the protocol to use */
        if (config.getProtocol() == null) {
            throw new Exception("Cannot get protocol.");
        }
        String protocol = config.getProtocol().toLowerCase().concat(config.getSecure() ? "s" : "");
        /* assemble the property prefix for this protocol */
        String propertyPrefix = "mail.";
        propertyPrefix = propertyPrefix.concat(protocol).concat(".");

        /* get the server port from the configuration and add it to the properties,
         * but only if it is actually set. If port = 0 this means we use the standard
         * port for the chosen protocol */
        int port = config.getPort();
        if (port != 0) {
            prop.setProperty(propertyPrefix.concat("port"), "" + port);
        }

        /* set connection timeout (10 seconds) */
        prop.setProperty(propertyPrefix.concat("connectiontimeout"), "10000");

        /* get the session for connecting to the mail server */
        Session session = Session.getInstance(prop, null);

        /* get the mail store, using the desired protocol */
        if (config.getSecure()) {
            store = session.getStore(protocol);
        } else {
            store = session.getStore(protocol);
        }

        /* get the host and credentials for the mail server from the configuration */
        String host = config.getServer();
        String username = config.getUsername();
        String password = config.getPassword();

        /* sanity check */
        if (host == null || username == null || password == null) {
            throw new Exception("Incomplete mail configuration settings (at least one setting is null).");
        }

        /* connect to the mailstore */
        try {
            store.connect(host, username, password);
        } catch (AuthenticationFailedException afe) {
            throw new Exception("Authentication for mail store failed: " + afe.getMessage(), afe);
        } catch (MessagingException me) {
            throw new Exception("Connecting to mail store failed: " + me.getMessage(), me);
        } catch (IllegalStateException ise) {
            throw new Exception("Connecting to mail store failed, already connected: " + ise.getMessage(), ise);
        } catch (Exception e) {
            throw new Exception("Connecting to mail store failed, general exception: " + e.getMessage(), e);
        }

        /***
         * Open the INBOX
         ***/

        /* get the INBOX folder */
        Folder folderInbox = store.getFolder("INBOX");
        /* we need to open it READ_WRITE, because we want to move messages we already handled */
        try {
            folderInbox.open(Folder.READ_WRITE);
        } catch (FolderNotFoundException fnfe) {
            throw new Exception("Could not find INBOX folder: " + fnfe.getMessage(), fnfe);
        } catch (Exception e) {
            throw new Exception("Could not open INBOX folder: " + e.getMessage(), e);
        }

        /* here we have to split, because IMAP will be handled differently from POP3 */
        if (config.getProtocol().toLowerCase().equals("imap")) {
            /***
             * Open the default folder, under which will be the processed
             * and the invalid folder.
             ***/

            Folder folderDefault = null;
            try {
                folderDefault = store.getDefaultFolder();
            } catch (MessagingException me) {
                throw new Exception("Could not get default folder: " + me.getMessage(), me);
            }
            /* sanity check */
            try {
                if (!folderDefault.exists()) {
                    throw new Exception(
                            "Default folder does not exist. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author.");
                }
            } catch (MessagingException me) {
                throw new Exception("Could not test existence of the default folder: " + me.getMessage(), me);
            }

            /**
             * This is kind of a fallback mechanism. For some reasons it can happen that
             * the default folder has an empty name and exists() returns true, but when
             * trying to create a subfolder it generates an error message.
             * So what we do here is if the name of the default folder is empty, we
             * look for the "INBOX" folder, which has to exist and then create the
             * subfolders under this folder.
             */
            if (folderDefault.getName().equals("")) {
                this.log.warn("Default folder has empty name. Looking for 'INBOX' folder as root folder.");
                folderDefault = store.getFolder("INBOX");
                if (!folderDefault.exists()) {
                    throw new Exception(
                            "Could not find default folder and could not find 'INBOX' folder. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author.");
                }
            }

            /***
             * Open the folder for processed messages
             ***/

            /* get the folder where we store processed messages */
            Folder folderProcessed = folderDefault.getFolder("Processed");
            /* check if it exists */
            if (!folderProcessed.exists()) {
                /* does not exist, create it */
                try {
                    if (!folderProcessed.create(Folder.HOLDS_MESSAGES)) {
                        throw new Exception("Creating 'processed' folder failed.");
                    }
                } catch (MessagingException me) {
                    throw new Exception("Could not create 'processed' folder: " + me.getMessage(), me);
                }
            }
            /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */
            try {
                folderProcessed.open(Folder.READ_WRITE);
            } catch (FolderNotFoundException fnfe) {
                throw new Exception("Could not find 'processed' folder: " + fnfe.getMessage(), fnfe);
            } catch (Exception e) {
                throw new Exception("Could not open 'processed' folder: " + e.getMessage(), e);
            }

            /***
             * Open the folder for invalid messages
             ***/

            /* get the folder where we store invalid messages */
            Folder folderInvalid = folderDefault.getFolder("Invalid");
            /* check if it exists */
            if (!folderInvalid.exists()) {
                /* does not exist, create it */
                try {
                    if (!folderInvalid.create(Folder.HOLDS_MESSAGES)) {
                        throw new Exception("Creating 'invalid' folder failed.");
                    }
                } catch (MessagingException me) {
                    throw new Exception("Could not create 'invalid' folder: " + me.getMessage(), me);
                }
            }
            /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */
            try {
                folderInvalid.open(Folder.READ_WRITE);
            } catch (FolderNotFoundException fnfe) {
                throw new Exception("Could not find 'invalid' folder: " + fnfe.getMessage(), fnfe);
            } catch (Exception e) {
                throw new Exception("Could not open 'invalid' folder: " + e.getMessage(), e);
            }

            /***
             * Get all new messages
             ***/

            /* get all messages in the INBOX */
            Message message[] = folderInbox.getMessages();

            /* go through all messages and get the unseen ones (all should be unseen,
             * as the seen ones get moved to a different folder
             */
            for (int i = 0; i < message.length; i++) {

                if (message[i].isSet(Flags.Flag.SEEN)) {
                    /* this message has been seen, should not happen */
                    /* send email to the sender */
                    sendErrorMessage(message[i],
                            "This message has already been flagged as seen before being handled and was thus ignored.");
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                Space space = null;
                try {
                    space = getSpaceFromAddress(message[i]);
                } catch (Exception e) {
                    this.log.error("Could not get space from message: " + e.getMessage());
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage());
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                /* initialise content and attachments */
                blogEntryContent = null;
                attachments = new LinkedList();
                attachmentsInputStreams = new LinkedList();

                containsImage = false;

                /* get the content of this message */
                try {
                    Object content = message[i].getContent();
                    if (content instanceof Multipart) {
                        handleMultipart((Multipart) content);
                    } else {
                        handlePart(message[i]);
                    }
                } catch (Exception e) {
                    this.log.error("Error while getting content of message: " + e.getMessage(), e);
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage());
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                try {
                    createBlogPost(space, message[i]);
                } catch (MessagingException me) {
                    this.log.error("Error while creating blog post: " + me.getMessage(), me);
                    /* send email to sender */
                    sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage());
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                /* move the message to the processed folder */
                moveMessage(message[i], folderInbox, folderProcessed);

            }

            /* close the folders, expunging deleted messages in the process */
            folderInbox.close(true);
            folderProcessed.close(true);
            folderInvalid.close(true);
            /* close the store */
            store.close();

        } else if (config.getProtocol().toLowerCase().equals("pop3")) {
            /* get all messages in this POP3 account */
            Message message[] = folderInbox.getMessages();

            /* go through all messages */
            for (int i = 0; i < message.length; i++) {

                Space space = null;
                try {
                    space = getSpaceFromAddress(message[i]);
                } catch (Exception e) {
                    this.log.error("Could not get space from message: " + e.getMessage());
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage());
                    /* delete this message */
                    message[i].setFlag(Flags.Flag.DELETED, true);
                    /* get the next message, this message will be deleted when
                     * closing the folder */
                    continue;
                }

                /* initialise content and attachments */
                blogEntryContent = null;
                attachments = new LinkedList();
                attachmentsInputStreams = new LinkedList();

                containsImage = false;

                /* get the content of this message */
                try {
                    Object content = message[i].getContent();
                    if (content instanceof Multipart) {
                        handleMultipart((Multipart) content);
                    } else {
                        handlePart(message[i]);
                    }
                } catch (Exception e) {
                    this.log.error("Error while getting content of message: " + e.getMessage(), e);
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage());
                    /* delete this message */
                    message[i].setFlag(Flags.Flag.DELETED, true);
                    /* get the next message, this message will be deleted when
                     * closing the folder */
                    continue;
                }

                try {
                    createBlogPost(space, message[i]);
                } catch (MessagingException me) {
                    this.log.error("Error while creating blog post: " + me.getMessage(), me);
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage());
                    /* delete this message */
                    message[i].setFlag(Flags.Flag.DELETED, true);
                    /* get the next message, this message will be deleted when
                     * closing the folder */
                    continue;
                }

                /* finished processing this message, delete it */
                message[i].setFlag(Flags.Flag.DELETED, true);
                /* get the next message, this message will be deleted when
                 * closing the folder */

            }

            /* close the pop3 folder, deleting all messages flagged as DELETED */
            folderInbox.close(true);
            /* close the mail store */
            store.close();

        } else {
            throw new Exception("Unknown protocol: " + config.getProtocol());
        }

    } catch (Exception e) {
        /* catch any exception which was not handled so far */
        this.log.error("Error while executing mail2news job: " + e.getMessage(), e);
        JobExecutionException jee = new JobExecutionException(
                "Error while executing mail2news job: " + e.getMessage(), e, false);
        throw jee;
    } finally {
        /* try to do some cleanup */
        try {
            store.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.dspace.workflowbasic.BasicWorkflowServiceImpl.java

protected void notifyGroupOfTask(Context c, BasicWorkflowItem wi, Group mygroup, List<EPerson> epa)
        throws SQLException, IOException {
    // check to see if notification is turned off
    // and only do it once - delete key after notification has
    // been suppressed for the first time
    UUID myID = wi.getItem().getID();

    if (noEMail.containsKey(myID)) {
        // suppress email, and delete key
        noEMail.remove(myID);//from ww  w.  j  a  va2s  .c o m
    } else {
        try {
            // Get the item title
            String title = getItemTitle(wi);

            // Get the submitter's name
            String submitter = getSubmitterName(wi);

            // Get the collection
            Collection coll = wi.getCollection();

            String message = "";

            for (EPerson anEpa : epa) {
                Locale supportedLocale = I18nUtil.getEPersonLocale(anEpa);
                Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_task"));
                email.addArgument(title);
                email.addArgument(coll.getName());
                email.addArgument(submitter);

                ResourceBundle messages = ResourceBundle.getBundle("Messages", supportedLocale);
                switch (wi.getState()) {
                case WFSTATE_STEP1POOL:
                    message = messages.getString("org.dspace.workflow.WorkflowManager.step1");

                    break;

                case WFSTATE_STEP2POOL:
                    message = messages.getString("org.dspace.workflow.WorkflowManager.step2");

                    break;

                case WFSTATE_STEP3POOL:
                    message = messages.getString("org.dspace.workflow.WorkflowManager.step3");

                    break;
                }
                email.addArgument(message);
                email.addArgument(getMyDSpaceLink());
                email.addRecipient(anEpa.getEmail());
                email.send();
            }
        } catch (MessagingException e) {
            String gid = (mygroup != null) ? String.valueOf(mygroup.getID()) : "none";
            log.warn(LogManager.getHeader(c, "notifyGroupofTask", "cannot email user group_id=" + gid
                    + " workflow_item_id=" + wi.getID() + ":  " + e.getMessage()));
        }
    }
}

From source file:smilehouse.opensyncro.pipes.Pipe.java

private void addLogEntry(LogEntry logEntry, int statusCode) {
    if (this.log == null)
        this.log = new HashSet();

    logEntry.setStatusCode(statusCode);//from  ww w .  j ava2 s  . c o  m
    logEntry.setTime(new Date());

    // The LogEntry is not explicitly added to the Pipe's log Set, since it causes
    // Hibernate to query all LogEntries from the database and thus consume
    // ever-increasing amount of server resources.

    //this.log.add(logEntry);
    String status = getStatusString(statusCode);

    Persister persister = new Persister(database);

    try {
        persister.update(logEntry);

        List messages;

        boolean mailAddressNotSet = ((getMailHost() == null || getRecipientAddress() == null)
                || (getMailHost().length() == 0 || getRecipientAddress().length() == 0));

        // Notification via email only if host and email address are present
        if (!mailAddressNotSet && !(getTransferLogNotificationLevel() == MessageLogger.MAIL_NONE)) {

            String date = dateFormat.format(new Date());
            String subject = this.getName() + " " + status + " " + date + " (" + database + ")";
            String message = "";

            // Get number of log messages at or below transferLogNotificationLevel.  

            int entries = persister.getLogMessageEntries(logEntry.getId(), getTransferLogNotificationLevel())
                    .size();

            //Generate mail message
            if (entries > 0) {

                messages = persister.getLogMessageEntries(logEntry.getId(), getLoggingVerbosityLevel());
                for (Iterator m = messages.iterator(); m.hasNext();) {
                    LogMessageEntry messageEntry = (LogMessageEntry) m.next();
                    message += (messageEntry.getMessage()) + "\n";
                }
            } else {
                message += MAIL_MESSAGE_NO_ENTRIES;
            }

            // Send notification email except when the message is
            // MAIL_MESSAGE_NO_ENTRIES or the pipe has aborted and 
            // isAbortMailEnabled()==true 
            if (!message.equals(MAIL_MESSAGE_NO_ENTRIES)
                    || (statusCode == LogEntry.STATUS_ABORTED && isAbortMailEnabled())) {
                try {

                    Properties props = new Properties();
                    props.put("mail.host", getMailHost());

                    Session mailConnection = Session.getInstance(props, null);
                    Message msg = new MimeMessage(mailConnection);
                    Address sender = new InternetAddress(MAIL_SENDER + "@" + getMailHost(), MAIL_SENDER);
                    Address[] receivers = receiverAddresses(getRecipientAddress());

                    // Set mail content and subject
                    msg.setContent(message, "text/plain");
                    msg.setFrom(sender);
                    msg.setRecipients(Message.RecipientType.TO, receivers);
                    msg.setSubject(subject);

                    // Send the mail
                    Transport.send(msg);

                } catch (MessagingException e) {
                    String error = "An error occurred when sending mail report from " + MAIL_SENDER + "@"
                            + getMailHost() + " to " + getRecipientAddress() + ":\n" + e.getMessage();
                    Environment.getInstance().log(error);
                    logEntry.logMessage(error, this, MessageLogger.ERROR);
                    persister.update(logEntry);
                } catch (RuntimeException ex) {
                    Environment.getInstance().log("A RuntimeException has occurred: " + ex.getMessage()
                            + ex.getStackTrace().toString());
                }
            }
        }
        // Remove unnecessary (debug level) messages from the LogEntry if Transfer log
        // verbosity level is set to DYNAMIC and the current LogEntry's status is either
        // OK or ABORTED
        if (getLoggingVerbosityLevel() == MessageLogger.LOG_DYNAMIC
                && (statusCode == LogEntry.STATUS_OK || statusCode == LogEntry.STATUS_ABORTED)) {
            messages = persister.getLogMessageEntries(logEntry.getId(), MessageLogger.DEBUG);
            if (messages.size() > 0) {
                for (Iterator m = messages.iterator(); m.hasNext();) {
                    LogMessageEntry messageEntry = (LogMessageEntry) m.next();
                    if (messageEntry.getMessageType() == MessageLogger.DEBUG) {
                        persister.delete(messageEntry);

                    }
                }
            }
        }
    } catch (Exception e) {
        Environment.getInstance().log(e.getMessage());
    } finally {
        persister.close();
    }
}

From source file:org.apache.james.smtpserver.DataLineJamesMessageHookHandler.java

public Response onLine(SMTPSession session, ByteBuffer lineByteBuffer, LineHandler<SMTPSession> next) {

    byte[] line = new byte[lineByteBuffer.remaining()];
    lineByteBuffer.get(line, 0, line.length);

    MimeMessageInputStreamSource mmiss = (MimeMessageInputStreamSource) session
            .getAttachment(SMTPConstants.DATA_MIMEMESSAGE_STREAMSOURCE, State.Transaction);

    try {//from  ww w  .j av  a 2s  . c om
        OutputStream out = mmiss.getWritableOutputStream();

        // 46 is "."
        // Stream terminated
        if (line.length == 3 && line[0] == 46) {
            out.flush();
            out.close();

            @SuppressWarnings("unchecked")
            List<MailAddress> recipientCollection = (List<MailAddress>) session
                    .getAttachment(SMTPSession.RCPT_LIST, State.Transaction);
            MailAddress mailAddress = (MailAddress) session.getAttachment(SMTPSession.SENDER,
                    State.Transaction);

            List<org.apache.mailet.MailAddress> rcpts = new ArrayList<org.apache.mailet.MailAddress>();
            for (MailAddress address : recipientCollection) {
                rcpts.add(new MailetMailAddressAdapter(address));
            }

            MailetMailAddressAdapter mailetMailAddressAdapter = null;
            if (mailAddress != MailAddress.nullSender()) {
                mailetMailAddressAdapter = new MailetMailAddressAdapter(mailAddress);
            }

            MailImpl mail = new MailImpl(MailImpl.getId(), mailetMailAddressAdapter, rcpts);

            // store mail in the session so we can be sure it get disposed later
            session.setAttachment(SMTPConstants.MAIL, mail, State.Transaction);

            MimeMessageCopyOnWriteProxy mimeMessageCopyOnWriteProxy = null;
            try {
                mimeMessageCopyOnWriteProxy = new MimeMessageCopyOnWriteProxy(mmiss);
                mail.setMessage(mimeMessageCopyOnWriteProxy);

                Response response = processExtensions(session, mail);

                session.popLineHandler();
                return response;

            } catch (MessagingException e) {
                // TODO probably return a temporary problem
                session.getLogger().info("Unexpected error handling DATA stream", e);
                return new SMTPResponse(SMTPRetCode.LOCAL_ERROR, "Unexpected error handling DATA stream.");
            } finally {
                LifecycleUtil.dispose(mimeMessageCopyOnWriteProxy);
                LifecycleUtil.dispose(mmiss);
                LifecycleUtil.dispose(mail);
            }

            // DotStuffing.
        } else if (line[0] == 46 && line[1] == 46) {
            out.write(line, 1, line.length - 1);
            // Standard write
        } else {
            // TODO: maybe we should handle the Header/Body recognition here
            // and if needed let a filter to cache the headers to apply some
            // transformation before writing them to output.
            out.write(line);
        }
    } catch (IOException e) {
        LifecycleUtil.dispose(mmiss);
        SMTPResponse response = new SMTPResponse(SMTPRetCode.LOCAL_ERROR,
                DSNStatus.getStatus(DSNStatus.TRANSIENT, DSNStatus.UNDEFINED_STATUS)
                        + " Error processing message: " + e.getMessage());
        session.getLogger().error("Unknown error occurred while processing DATA.", e);
        return response;
    } catch (AddressException e) {
        LifecycleUtil.dispose(mmiss);
        SMTPResponse response = new SMTPResponse(SMTPRetCode.LOCAL_ERROR,
                DSNStatus.getStatus(DSNStatus.TRANSIENT, DSNStatus.UNDEFINED_STATUS)
                        + " Error processing message: " + e.getMessage());
        session.getLogger().error("Invalid email address while processing DATA.", e);
        return response;
    }
    return null;
}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

/**
 * {@inheritDoc}//from  w w  w .  j  a v a2 s  . co  m
 * 
 * @see org.sakaiproject.email.api.EmailService#send(EmailMessage)
 * For temporary backward compatibility
 */
public List<EmailAddress> send(EmailMessage msg) throws AddressValidationException, NoRecipientsException {
    List<EmailAddress> addresses = new ArrayList<EmailAddress>();
    try {
        addresses = send(msg, true);
    } catch (MessagingException e) {
        M_log.error("Email.sendMail: exception: " + e.getMessage(), e);
    }
    return addresses;
}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

/**
 * {@inheritDoc}//w w  w. j a  va 2  s  . com
 */
public void sendMail(InternetAddress from, InternetAddress[] to, String subject, String content,
        Map<RecipientType, InternetAddress[]> headerTo, InternetAddress[] replyTo,
        List<String> additionalHeaders, List<Attachment> attachments) {
    try {
        sendMailMessagingException(from, to, subject, content, headerTo, replyTo, additionalHeaders,
                attachments);
    } catch (MessagingException e) {
        M_log.error("Email.sendMail: exception: " + e.getMessage(), e);
    }
}

From source file:de.xirp.ui.widgets.dialogs.ComposeMailDialog.java

/**
 * Opens the given mail to be edited or created. If the given mail
 * was <code>null</code> the dialog is used to create a new
 * mail.//from ww w  .j a  v a2  s  . co  m
 * 
 * @param mail
 *            The mail.
 * @see de.xirp.mail.Mail
 */
public void open(Mail mail) {
    this.mail = mail;
    if (mail != null) {
        forward = true;
    }

    dialogShell = new XShell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);

    dialogShell.addShellListener(new ShellAdapter() {

        @Override
        public void shellClosed(ShellEvent e) {
            SWTUtil.secureDispose(dialogShell);
        }
    });
    dialogShell.setSize(WIDTH, HEIGHT);
    if (forward) {
        dialogShell.setTextForLocaleKey("ComposeMailDialog.gui.title.forwardMessage"); //$NON-NLS-1$
    } else {
        dialogShell.setTextForLocaleKey("ComposeMailDialog.gui.title.composeMessage"); //$NON-NLS-1$
    }
    dialogShell.setImage(ImageManager.getSystemImage(SystemImage.SEND_MAIL));
    SWTUtil.setGridLayout(dialogShell, 3, false);

    toolBar = new XToolBar(dialogShell, SWT.FLAT);

    XToolItem send = new XToolItem(toolBar, SWT.PUSH);
    if (mail == null) {
        send.setToolTipTextForLocaleKey("ComposeMailDialog.tool.item.tooltip.send"); //$NON-NLS-1$
        send.setImage(ImageManager.getSystemImage(SystemImage.SEND_MAIL));
    } else {
        send.setToolTipTextForLocaleKey("ComposeMailDialog.tool.item.tooltip.forward"); //$NON-NLS-1$
        send.setImage(ImageManager.getSystemImage(SystemImage.FORWARD_MAIL));
    }
    send.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {

            Runnable runnable = new Runnable() {

                public void run() {
                    try {
                        if (forward) {
                            getMail().setSubject(I18n.getString("ComposeMailDialog.internal.mail.subject", //$NON-NLS-1$
                                    getMail().getSubject()));
                        } else {
                            buildMail();
                        }
                        MailManager.sendMail(getMail());
                        dialogShell.close();
                    } catch (MessagingException ex) {
                        XMessageBox box = new XMessageBox(dialogShell, HMessageBoxType.INFO, XButtonType.OK);
                        box.setTextForLocaleKey("ComposeMailDialog.messagebox.title.errorSendingMail"); //$NON-NLS-1$
                        box.setMessageForLocaleKey("ComposeMailDialog.mesagebox.message.errorSendingMail", //$NON-NLS-1$
                                Constants.LINE_SEPARATOR, ex.getMessage());
                        box.open();
                    } catch (EmailException ex) {
                        XMessageBox box = new XMessageBox(dialogShell, HMessageBoxType.ERROR, XButtonType.OK);
                        box.setTextForLocaleKey("ComposeMailDialog.messagebox.title.errorSendingMail"); //$NON-NLS-1$
                        box.setMessageForLocaleKey("ComposeMailDialog.mesagebox.message.errorSendingMail", //$NON-NLS-1$
                                Constants.LINE_SEPARATOR, ex.getMessage());
                        box.open();
                        dialogShell.close();
                    }
                }
            };
            SWTUtil.showBusyWhile(parent, runnable);
        }
    });

    if (!forward) {

        new ToolItem(toolBar, SWT.SEPARATOR);

        menu = new Menu(dialogShell, SWT.POP_UP);
        XMenuItem filesystem = new XMenuItem(menu, SWT.PUSH);
        filesystem.setTextForLocaleKey("ComposeMailDialog.menu.item.fromFileSystem"); //$NON-NLS-1$
        filesystem.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                FileDialog dialog = new FileDialog(dialogShell, SWT.OPEN);
                dialog.setFilterPath(Constants.USER_DIR);
                String names[] = Attachment.FileType.extensionsNames();
                dialog.setFilterNames(names);
                String xts[] = Attachment.FileType.extensions();
                dialog.setFilterExtensions(xts);
                String path = dialog.open();

                if (!Util.isEmpty(path)) {
                    try {
                        Attachment a = new Attachment(new File(path));
                        attachmentList.add(a);
                        list.add(a.getFileName());
                    } catch (IOException ex) {
                        logClass.error("Error: " + ex.getMessage() //$NON-NLS-1$
                                + Constants.LINE_SEPARATOR, ex);
                    }
                }
            }
        });

        XMenuItem log = new XMenuItem(menu, SWT.PUSH);
        log.setTextForLocaleKey("ComposeMailDialog.menu.item.logFromDatabase"); //$NON-NLS-1$
        log.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                RecordLookupDialog dialog = new RecordLookupDialog(dialogShell);
                Record record = dialog.openSingle();
                if (record != null) {
                    try {
                        List<Observed> obs = ChartDatabaseUtil.getObservedListForRecord(record);

                        File file = new File(Constants.TMP_DIR, record.getName() + "_" //$NON-NLS-1$
                                + record.getRobotName() + "_" + record.getId() + ".csv"); //$NON-NLS-1$ //$NON-NLS-2$
                        ChartUtil.exportCSV(obs, file);
                        Attachment a = new Attachment(file);
                        attachmentList.add(a);
                        list.add(a.getFileName());
                        DeleteManager.deleteOnShutdown(file);
                    } catch (IOException ex) {
                        logClass.error("Error: " + ex.getMessage() + Constants.LINE_SEPARATOR, ex); //$NON-NLS-1$
                    }
                }
            }
        });

        XMenuItem report = new XMenuItem(menu, SWT.PUSH);
        report.setTextForLocaleKey("ComposeMailDialog.menu.item.reportFromDatabase"); //$NON-NLS-1$
        report.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                ReportSearchDialog dialog = new ReportSearchDialog(dialogShell);
                ReportDescriptor rd = dialog.open();
                if (rd != null) {
                    try {
                        File file = new File(Constants.TMP_DIR, rd.getFileName());
                        FileUtils.writeByteArrayToFile(file, rd.getPdfData());
                        Attachment a = new Attachment(file);
                        attachmentList.add(a);
                        list.add(a.getFileName());
                    } catch (IOException ex) {
                        logClass.error("Error: " + ex.getMessage() + Constants.LINE_SEPARATOR, ex); //$NON-NLS-1$
                    }
                }
            }

        });

        XMenuItem charts = new XMenuItem(menu, SWT.PUSH);
        charts.setTextForLocaleKey("ComposeMailDialog.menu.item.chartFromDatabase"); //$NON-NLS-1$
        charts.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                FileDialog dialog = new FileDialog(dialogShell, SWT.OPEN);
                String names[] = Attachment.FileType.extensionsNames();
                dialog.setFilterNames(names);
                String xts[] = Attachment.FileType.extensions();
                dialog.setFilterExtensions(xts);
                dialog.setFilterPath(Constants.CHART_DIR);
                String path = dialog.open();

                if (!Util.isEmpty(path)) {
                    try {
                        Attachment a = new Attachment(new File(path));
                        attachmentList.add(a);
                        list.add(a.getFileName());
                    } catch (IOException ex) {
                        logClass.error("Error: " + ex.getMessage() //$NON-NLS-1$
                                + Constants.LINE_SEPARATOR, ex);
                    }
                }
            }

        });

        attachment = new XToolItem(toolBar, SWT.DROP_DOWN);
        attachment.setToolTipTextForLocaleKey("ComposeMailDialog.tool.item.tooltip.attachFile"); //$NON-NLS-1$
        attachment.setImage(ImageManager.getSystemImage(SystemImage.ATTACHMENT));
        attachment.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                Runnable runnable = new Runnable() {

                    public void run() {
                        Rectangle rect = attachment.getBounds();
                        Point pt = new Point(rect.x, rect.y + rect.height);
                        pt = toolBar.toDisplay(pt);
                        menu.setLocation(pt.x, pt.y);
                        menu.setVisible(true);
                    }
                };
                SWTUtil.showBusyWhile(parent, runnable);
            }
        });

    }

    new XToolItem(toolBar, SWT.SEPARATOR);

    delete = new XToolItem(toolBar, SWT.PUSH);
    delete.setToolTipTextForLocaleKey("ComposeMailDialog.tool.item.tooltip.deleteSelection"); //$NON-NLS-1$
    delete.setEnabled(false);
    delete.setImage(ImageManager.getSystemImage(SystemImage.DELETE));
    delete.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            Runnable runnable = new Runnable() {

                public void run() {
                    deleteSelections();
                }
            };
            SWTUtil.showBusyWhile(parent, runnable);
        }
    });

    new XToolItem(toolBar, SWT.SEPARATOR);

    manageContacts = new XToolItem(toolBar, SWT.PUSH);
    manageContacts.setToolTipTextForLocaleKey("ComposeMailDialog.tool.item.tooltip.manageContacts"); //$NON-NLS-1$
    manageContacts.setEnabled(true);
    manageContacts.setImage(ImageManager.getSystemImage(SystemImage.CONTACTS));
    manageContacts.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            Runnable runnable = new Runnable() {

                public void run() {
                    ContactDialog dialog = new ContactDialog(dialogShell);
                    dialog.open();
                }
            };
            SWTUtil.showBusyWhile(parent, runnable);
        }
    });

    addContact = new XToolItem(toolBar, SWT.PUSH);
    addContact.setToolTipTextForLocaleKey("ComposeMailDialog.tool.item.tooltip.newContact"); //$NON-NLS-1$
    addContact.setEnabled(true);
    addContact.setImage(ImageManager.getSystemImage(SystemImage.ADD_CONTACT));
    addContact.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            Runnable runnable = new Runnable() {

                public void run() {
                    try {
                        Contact aux = new Contact();
                        Contact clone = ObjectSerializer.<Contact>deepCopy(aux);

                        EditContactDialog dialog = new EditContactDialog(dialogShell);
                        if (!clone.equals(dialog.open(aux))) {
                            MailManager.addContact(aux);
                        }
                    } catch (IOException ex) {
                        logClass.error("Error: " + ex.getMessage() + Constants.LINE_SEPARATOR, ex); //$NON-NLS-1$
                    }
                }
            };
            SWTUtil.showBusyWhile(parent, runnable);
        }
    });

    SWTUtil.setGridData(toolBar, true, false, SWT.FILL, SWT.BEGINNING, 3, 1);

    XButton to = new XButton(dialogShell);
    to.setTextForLocaleKey("ComposeMailDialog.button.to"); //$NON-NLS-1$
    to.addSelectionListener(new SelectionAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            ContactLookupDialog dialog = new ContactLookupDialog(dialogShell);
            for (Contact c : dialog.open()) {
                addToContact(c);
            }
        }

    });

    SWTUtil.setGridData(to, false, false, SWT.LEFT, SWT.BEGINNING, 1, 1);

    tos = new XList(dialogShell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
    SWTUtil.setGridData(tos, true, false, SWT.FILL, SWT.FILL, 1, 1);
    tos.addSelectionListener(new SelectionAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            setDeleteStatus();
        }

    });
    tos.addKeyListener(new KeyAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.KeyAdapter#keyReleased(org.eclipse.swt.events.KeyEvent)
         */
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.keyCode == SWT.DEL) {
                int idx = tos.getSelectionIndex();
                tos.remove(idx);
                toContactList.remove(idx);
            }
        }
    });

    list = new XList(dialogShell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI);
    SWTUtil.setGridData(list, true, false, SWT.FILL, SWT.FILL, 1, 3);
    list.addSelectionListener(new SelectionAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            setDeleteStatus();
        }

    });
    list.addKeyListener(new KeyAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.KeyAdapter#keyReleased(org.eclipse.swt.events.KeyEvent)
         */
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.keyCode == SWT.DEL) {
                int idx = list.getSelectionIndex();
                list.remove(idx);
                attachmentList.remove(idx);
            }
        }
    });

    XButton cc = new XButton(dialogShell);
    cc.setTextForLocaleKey("ComposeMailDialog.button.cc"); //$NON-NLS-1$
    cc.addSelectionListener(new SelectionAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            ContactLookupDialog dialog = new ContactLookupDialog(dialogShell);
            for (Contact c : dialog.open()) {
                addCcContact(c);
            }
        }

    });
    SWTUtil.setGridData(cc, false, false, SWT.LEFT, SWT.BEGINNING, 1, 1);

    ccs = new XList(dialogShell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
    SWTUtil.setGridData(ccs, true, false, SWT.FILL, SWT.FILL, 1, 1);
    ccs.addSelectionListener(new SelectionAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            setDeleteStatus();
        }

    });
    ccs.addKeyListener(new KeyAdapter() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.swt.events.KeyAdapter#keyReleased(org.eclipse.swt.events.KeyEvent)
         */
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.keyCode == SWT.DEL) {
                int idx = ccs.getSelectionIndex();
                ccs.remove(idx);
                ccContactList.remove(idx);
            }
        }
    });

    XLabel l = new XLabel(dialogShell, SWT.CENTER);
    l.setTextForLocaleKey("ComposeMailDialog.label.subject"); //$NON-NLS-1$
    SWTUtil.setGridData(l, false, false, SWT.CENTER, SWT.CENTER, 1, 1);

    subject = new XTextField(dialogShell, SWT.NONE);
    SWTUtil.setGridData(subject, true, false, SWT.FILL, SWT.BEGINNING, 1, 1);

    text = new XText(dialogShell, SWT.MULTI | SWT.BORDER, true);
    SWTUtil.setGridData(text, true, true, SWT.FILL, SWT.FILL, 3, 1);

    if (forward) {
        setMailContent();
    } else {
        this.mail = new Mail();
        toContactList = new ArrayList<Contact>();
        ccContactList = new ArrayList<Contact>();
        attachmentList = new ArrayList<Attachment>();
    }

    dialogShell.layout();
    SWTUtil.centerDialog(dialogShell);
    dialogShell.open();

    SWTUtil.blockDialogFromReturning(dialogShell);

    return;
}

From source file:org.sakaiproject.component.app.messageforums.ui.PrivateMessageManagerImpl.java

/**
 * @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#sendPrivateMessage(org.sakaiproject.api.app.messageforums.PrivateMessage, java.util.Set, boolean)
 *///  ww w  .j a  v  a2 s .c  o  m
public void sendPrivateMessage(PrivateMessage message, Map<User, Boolean> recipients, boolean asEmail) {

    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("sendPrivateMessage(message: " + message + ", recipients: " + recipients + ")");
        }

        if (message == null || recipients == null) {
            throw new IllegalArgumentException("Null Argument");
        }

        if (recipients.size() == 0 && !message.getDraft().booleanValue()) {
            /** for no just return out
              throw new IllegalArgumentException("Empty recipient list");
            **/
            return;
        }

        String currentUserAsString = getCurrentUser();
        User currentUser = UserDirectoryService.getCurrentUser();
        List recipientList = new UniqueArrayList();

        /** test for draft message */
        if (message.getDraft().booleanValue()) {
            PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(currentUserAsString,
                    typeManager.getDraftPrivateMessageType(), getContextId(), Boolean.TRUE, false);

            recipientList.add(receiver);
            message.setRecipients(recipientList);
            savePrivateMessage(message, false);
            return;
        }

        //build the message body
        List additionalHeaders = new ArrayList(1);
        additionalHeaders.add("Content-Type: text/html; charset=utf-8");

        /** determines if default in sakai.properties is set, if not will make a reasonable default */
        String defaultEmail = ServerConfigurationService.getString("setup.request",
                "postmaster@" + ServerConfigurationService.getServerName());
        String systemEmail = ServerConfigurationService.getString("msgcntr.notification.from.address",
                defaultEmail);

        if (!ServerConfigurationService.getBoolean("msgcntr.notification.user.real.from", false)) {
            systemEmail = ServerConfigurationService.getString("msgcntr.notification.from.address",
                    defaultEmail);
        } else {
            if (currentUser.getEmail() != null)
                systemEmail = currentUser.getEmail();
            else
                systemEmail = ServerConfigurationService.getString("msgcntr.notification.from.address",
                        defaultEmail);
        }

        String bodyString = buildMessageBody(message);

        Area currentArea = null;
        List<PrivateForum> privateForums = null;
        Map<String, PrivateForum> pfMap = null;

        currentArea = getAreaByContextIdAndTypeId(typeManager.getPrivateMessageAreaType());

        // make sure the site-wide email copy preference is respected in case an invalid
        // value slipped in
        if (currentArea.getSendToEmail() == Area.EMAIL_COPY_ALWAYS) {
            asEmail = true;
        } else if (currentArea.getSendToEmail() == Area.EMAIL_COPY_NEVER) {
            asEmail = false;
        }

        //this is fairly inneficient and should realy be a convenience method to lookup
        // the users who want to forward their messages
        privateForums = currentArea.getPrivateForums();

        //create a map for efficient lookup for large sites
        pfMap = new HashMap<String, PrivateForum>();
        for (int i = 0; i < privateForums.size(); i++) {
            PrivateForum pf1 = (PrivateForum) privateForums.get(i);
            pfMap.put(pf1.getOwner(), pf1);
        }

        boolean forwardingEnabled = false;
        List<InternetAddress> fAddresses = new ArrayList<InternetAddress>();
        //this only needs to be done if the message is not being sent
        for (Iterator<Entry<User, Boolean>> i = recipients.entrySet().iterator(); i.hasNext();) {
            Entry<User, Boolean> entrySet = (Entry<User, Boolean>) i.next();
            User u = (User) entrySet.getKey();
            Boolean bcc = (Boolean) entrySet.getValue();
            String userId = u.getId();

            //boolean forwardingEnabled = false;
            //String forwardAddress = null;

            PrivateForum pf = null;
            if (pfMap.containsKey(userId))
                pf = pfMap.get(userId);

            if (pf != null && pf.getAutoForward().booleanValue() && pf.getAutoForwardEmail() != null) {
                forwardingEnabled = true;
                fAddresses.add(new InternetAddress(pf.getAutoForwardEmail()));
                //forwardAddress = pf.getAutoForwardEmail();
            }
            if (pf == null) {
                //only check for default settings if the pf is null
                PrivateForum oldPf = forumManager.getPrivateForumByOwnerAreaNull(userId);
                if (oldPf != null && oldPf.getAutoForward().booleanValue()
                        && oldPf.getAutoForwardEmail() != null) {
                    //forwardAddress = oldPf.getAutoForwardEmail();
                    forwardingEnabled = true;
                    fAddresses.add(new InternetAddress(oldPf.getAutoForwardEmail()));
                }
            }

            /** determine if current user is equal to recipient */
            Boolean isRecipientCurrentUser = (currentUserAsString.equals(userId) ? Boolean.TRUE
                    : Boolean.FALSE);

            PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(userId,
                    typeManager.getReceivedPrivateMessageType(), getContextId(), isRecipientCurrentUser, bcc);
            recipientList.add(receiver);
        }

        if (asEmail) {
            //send as 1 action to all recipients
            //we need to add som headers
            additionalHeaders.add("From: " + systemEmail);
            additionalHeaders.add("Subject: " + message.getTitle());
            emailService.sendToUsers(recipients.keySet(), additionalHeaders, bodyString);
        }

        if (!isEmailForwardDisabled() && forwardingEnabled) {
            InternetAddress fAddressesArr[] = new InternetAddress[fAddresses.size()];
            fAddressesArr = fAddresses.toArray(fAddressesArr);
            emailService.sendMail(new InternetAddress(systemEmail), fAddressesArr, message.getTitle(),
                    bodyString, null, null, additionalHeaders);
        }

        /** add sender as a saved recipient */
        PrivateMessageRecipientImpl sender = new PrivateMessageRecipientImpl(currentUserAsString,
                typeManager.getSentPrivateMessageType(), getContextId(), Boolean.TRUE, false);

        recipientList.add(sender);

        message.setRecipients(recipientList);

        savePrivateMessage(message, false);
    } catch (MessagingException e) {
        LOG.warn("PrivateMessageManagerImpl.sendPrivateMessage: exception: " + e.getMessage(), e);
    }
}