Example usage for javax.mail.internet MimeMessage getSentDate

List of usage examples for javax.mail.internet MimeMessage getSentDate

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage getSentDate.

Prototype

@Override
public Date getSentDate() throws MessagingException 

Source Link

Document

Returns the value of the RFC 822 "Date" field.

Usage

From source file:org.sakaiproject.james.SakaiMailet.java

/**
 * Process incoming mail.//w  ww.  j a v  a  2s .c  om
 * 
 * @param mail
 *        ...
 */
public void service(Mail mail) throws MessagingException {
    // get the postmaster user
    User postmaster = null;
    try {
        postmaster = userDirectoryService.getUser(POSTMASTER);
    } catch (UserNotDefinedException e) {
        M_log.warn("service(): no postmaster, incoming mail will not be processed until a postmaster user (id="
                + POSTMASTER + ") exists in this Sakai instance");
        mail.setState(Mail.GHOST);
        return;
    }

    try {
        // set the current user to postmaster
        Session s = sessionManager.getCurrentSession();
        if (s != null) {
            s.setUserId(postmaster.getId());
        } else {
            M_log.warn(
                    "service - no SessionManager.getCurrentSession, cannot set to postmaser user, attempting to use the current user ("
                            + sessionManager.getCurrentSessionUserId() + ") and session ("
                            + sessionManager.getCurrentSession().getId() + ")");
        }

        MimeMessage msg = mail.getMessage();
        String id = msg.getMessageID();

        Address[] fromAddresses = msg.getFrom();
        String from = null;
        String fromAddr = null;
        if ((fromAddresses != null) && (fromAddresses.length == 1)) {
            from = fromAddresses[0].toString();
            if (fromAddresses[0] instanceof InternetAddress) {
                fromAddr = ((InternetAddress) (fromAddresses[0])).getAddress();
            }
        } else {
            from = mail.getSender().toString();
            fromAddr = mail.getSender().toInternetAddress().getAddress();
        }

        Collection<MailAddress> to = mail.getRecipients();

        Date sent = msg.getSentDate();

        String subject = StringUtils.trimToNull(msg.getSubject());

        Enumeration<String> headers = msg.getAllHeaderLines();
        List<String> mailHeaders = new Vector<String>();
        while (headers.hasMoreElements()) {
            String line = (String) headers.nextElement();
            // check if string starts with "Content-Type", ignoring case
            if (line.regionMatches(true, 0, MailArchiveService.HEADER_CONTENT_TYPE, 0,
                    MailArchiveService.HEADER_CONTENT_TYPE.length())) {
                String contentType = line.substring(0, MailArchiveService.HEADER_CONTENT_TYPE.length());
                mailHeaders.add(line.replaceAll(contentType, MailArchiveService.HEADER_OUTER_CONTENT_TYPE));
            }
            // don't copy null subject lines. we'll add a real one below
            if (!(line.regionMatches(true, 0, MailArchiveService.HEADER_SUBJECT, 0,
                    MailArchiveService.HEADER_SUBJECT.length()) && subject == null))
                mailHeaders.add(line);

        }

        //Add headers for a null subject, keep null in DB
        if (subject == null) {
            mailHeaders.add(MailArchiveService.HEADER_SUBJECT + ": <" + rb.getString("err_no_subject") + ">");
        }

        if (M_log.isDebugEnabled()) {
            M_log.debug(id + " : mail: from:" + from + " sent: "
                    + timeService.newTime(sent.getTime()).toStringLocalFull() + " subject: " + subject);
        }

        // process for each recipient
        Iterator<MailAddress> it = to.iterator();
        while (it.hasNext()) {
            String mailId = null;
            try {
                MailAddress recipient = (MailAddress) it.next();
                if (M_log.isDebugEnabled()) {
                    M_log.debug(id + " : checking to: " + recipient);
                }

                // the recipient's mail id
                mailId = recipient.getUser();

                // eat the no-reply
                if ("no-reply".equalsIgnoreCase(mailId)) {
                    mail.setState(Mail.GHOST);
                    if (M_log.isInfoEnabled()) {
                        M_log.info("Incoming message mailId (" + mailId
                                + ") set to no-reply, mail processing cancelled");
                    }
                    /* NOTE: this doesn't make a lot of sense to me, once the mail is ghosted 
                     * then it won't be processed anymore so continuing is kind of a waste of time,
                     * shouldn't this just break instead?
                     */
                    continue;
                }

                // find the channel (mailbox) that this is addressed to
                // for now, check only for it being a site or alias to a site.
                // %%% - add user and other later -ggolden
                MailArchiveChannel channel = null;

                // first, assume the mailId is a site id
                String channelRef = MailArchiveService.channelReference(mailId, SiteService.MAIN_CONTAINER);
                try {
                    channel = MailArchiveService.getMailArchiveChannel(channelRef);
                    if (M_log.isDebugEnabled()) {
                        M_log.debug(
                                "Incoming message mailId (" + mailId + ") IS a valid site channel reference");
                    }
                } catch (IdUnusedException goOn) {
                    // INDICATES the incoming message is NOT for a currently valid site
                    if (M_log.isDebugEnabled()) {
                        M_log.debug("Incoming message mailId (" + mailId
                                + ") is NOT a valid site channel reference, will attempt more matches");
                    }
                } catch (PermissionException e) {
                    // INDICATES the channel is valid but the user has no permission to access it
                    // This generally should not happen because the current user should be the postmaster
                    M_log.warn(
                            "mailarchive failure: message processing cancelled: PermissionException with channelRef ("
                                    + channelRef + ") - user not allowed to get this mail archive channel: (id="
                                    + id + ") (mailId=" + mailId + ") (user="
                                    + sessionManager.getCurrentSessionUserId() + ") (session="
                                    + sessionManager.getCurrentSession().getId() + "): " + e,
                            e);
                    // BOUNCE REPLY - send a message back to the user to let them know their email failed
                    String errMsg = rb.getString("err_not_member") + "\n\n";
                    String mailSupport = StringUtils
                            .trimToNull(serverConfigurationService.getString("mail.support"));
                    if (mailSupport != null) {
                        errMsg += (String) rb.getFormattedMessage("err_questions", new Object[] { mailSupport })
                                + "\n";
                    }
                    mail.setErrorMessage(errMsg);
                    mail.setState(userNotAllowedToPostProcessor);
                    continue;
                }

                // next, if not a site, see if it's an alias to a site or channel
                if (channel == null) {
                    // if not an alias, it will throw the IdUnusedException caught below
                    Reference ref = entityManager.newReference(aliasService.getTarget(mailId));

                    if (ref.getType().equals(SiteService.APPLICATION_ID)) {
                        // ref is a site
                        // now we have a site reference, try for it's channel
                        channelRef = MailArchiveService.channelReference(ref.getId(),
                                SiteService.MAIN_CONTAINER);
                        if (M_log.isDebugEnabled()) {
                            M_log.debug("Incoming message mailId (" + mailId + ") IS a valid site reference ("
                                    + ref.getId() + ")");
                        }
                    } else if (ref.getType().equals(MailArchiveService.APPLICATION_ID)) {
                        // ref is a channel
                        channelRef = ref.getReference();
                        if (M_log.isDebugEnabled()) {
                            M_log.debug("Incoming message mailId (" + mailId
                                    + ") IS a valid channel reference (" + ref.getId() + ")");
                        }
                    } else {
                        // ref cannot be be matched
                        if (M_log.isInfoEnabled()) {
                            M_log.info(id + " : mail rejected: unknown address: " + mailId + " : mailId ("
                                    + mailId + ") does NOT match site, alias, or other current channel");
                        }
                        if (M_log.isDebugEnabled()) {
                            M_log.debug("Incoming message mailId (" + mailId
                                    + ") is NOT a valid does NOT match site, alias, or other current channel reference ("
                                    + ref.getId() + "), message rejected");
                        }
                        throw new IdUnusedException(mailId);
                    }

                    // if there's no channel for this site, it will throw the IdUnusedException caught below
                    try {
                        channel = MailArchiveService.getMailArchiveChannel(channelRef);
                    } catch (PermissionException e) {
                        // INDICATES the channel is valid but the user has no permission to access it
                        // This generally should not happen because the current user should be the postmaster
                        M_log.warn(
                                "mailarchive failure: message processing cancelled: PermissionException with channelRef ("
                                        + channelRef
                                        + ") - user not allowed to get this mail archive channel: (id=" + id
                                        + ") (mailId=" + mailId + ") (user="
                                        + sessionManager.getCurrentSessionUserId() + ") (session="
                                        + sessionManager.getCurrentSession().getId() + "): " + e,
                                e);
                        // BOUNCE REPLY - send a message back to the user to let them know their email failed
                        String errMsg = rb.getString("err_not_member") + "\n\n";
                        String mailSupport = StringUtils
                                .trimToNull(serverConfigurationService.getString("mail.support"));
                        if (mailSupport != null) {
                            errMsg += (String) rb.getFormattedMessage("err_questions",
                                    new Object[] { mailSupport }) + "\n";
                        }
                        mail.setErrorMessage(errMsg);
                        mail.setState(userNotAllowedToPostProcessor);
                        continue;
                    }
                    if (M_log.isDebugEnabled()) {
                        M_log.debug("Incoming message mailId (" + mailId + ") IS a valid channel (" + channelRef
                                + "), found channel: " + channel);
                    }
                }
                if (channel == null) {
                    if (M_log.isDebugEnabled()) {
                        M_log.debug("Incoming message mailId (" + mailId + "), channelRef (" + channelRef
                                + ") could not be resolved and is null: " + channel);
                    }
                    // this should never happen but it is here just in case
                    throw new IdUnusedException(mailId);
                }

                // skip disabled channels
                if (!channel.getEnabled()) {
                    // INDICATES that the channel is NOT currently enabled so no messages can be received
                    if (from.startsWith(POSTMASTER)) {
                        mail.setState(Mail.GHOST);
                    } else {
                        // BOUNCE REPLY - send a message back to the user to let them know their email failed
                        String errMsg = rb.getString("err_email_off") + "\n\n";
                        String mailSupport = StringUtils
                                .trimToNull(serverConfigurationService.getString("mail.support"));
                        if (mailSupport != null) {
                            errMsg += (String) rb.getFormattedMessage("err_questions",
                                    new Object[] { mailSupport }) + "\n";
                        }
                        mail.setErrorMessage(errMsg);
                        mail.setState(courseMailArchiveDisabledProcessor);
                    }

                    if (M_log.isInfoEnabled()) {
                        M_log.info(
                                id + " : mail rejected: channel (" + channelRef + ") not enabled: " + mailId);
                    }
                    continue;
                }

                // for non-open channels, make sure the from is a member
                if (!channel.getOpen()) {
                    // see if our fromAddr is the email address of any of the users who are permitted to add messages to the channel.
                    if (!fromValidUser(fromAddr, channel)) {
                        // INDICATES user is not allowed to send messages to this group
                        if (M_log.isInfoEnabled()) {
                            M_log.info(id + " : mail rejected: from: " + fromAddr + " not authorized for site: "
                                    + mailId + " and channel (" + channelRef + ")");
                        }
                        // BOUNCE REPLY - send a message back to the user to let them know their email failed
                        String errMsg = rb.getString("err_not_member") + "\n\n";
                        String mailSupport = StringUtils
                                .trimToNull(serverConfigurationService.getString("mail.support"));
                        if (mailSupport != null) {
                            errMsg += (String) rb.getFormattedMessage("err_questions",
                                    new Object[] { mailSupport }) + "\n";
                        }
                        mail.setErrorMessage(errMsg);
                        mail.setState(userNotAllowedToPostProcessor);
                        continue;
                    }
                }

                // prepare the message 
                StringBuilder bodyBuf[] = new StringBuilder[2];
                bodyBuf[0] = new StringBuilder();
                bodyBuf[1] = new StringBuilder();
                List<Reference> attachments = entityManager.newReferenceList();
                String siteId = null;
                if (siteService.siteExists(channel.getContext())) {
                    siteId = channel.getContext();
                }

                try {
                    StringBuilder bodyContentType = new StringBuilder();
                    parseParts(siteId, msg, id, bodyBuf, bodyContentType, attachments, Integer.valueOf(-1));

                    if (bodyContentType.length() > 0) {
                        // save the content type of the message body - which may be different from the
                        // overall MIME type of the message (multipart, etc)
                        mailHeaders.add(MailArchiveService.HEADER_INNER_CONTENT_TYPE + ": " + bodyContentType);
                    }
                } catch (MessagingException e) {
                    // NOTE: if this happens it just means we don't get the extra header, not the end of the world
                    //e.printStackTrace();
                    M_log.warn("MessagingException: service(): msg.getContent() threw: " + e, e);
                } catch (IOException e) {
                    // NOTE: if this happens it just means we don't get the extra header, not the end of the world
                    //e.printStackTrace();
                    M_log.warn("IOException: service(): msg.getContent() threw: " + e, e);
                }

                mailHeaders.add("List-Id: <" + channel.getId() + "." + channel.getContext() + "."
                        + serverConfigurationService.getServerName() + ">");

                // post the message to the group's channel
                String body[] = new String[2];
                body[0] = bodyBuf[0].toString(); // plain/text
                body[1] = bodyBuf[1].toString(); // html/text

                try {
                    if (channel.getReplyToList()) {
                        List<String> modifiedHeaders = new Vector<String>();
                        for (String header : (List<String>) mailHeaders) {
                            if (header != null && !header.startsWith("Reply-To:")) {
                                modifiedHeaders.add(header);
                            }
                        }
                        // Note: can't use recipient, since it's host may be configured as mailId@myhost.james
                        String mailHost = serverConfigurationService.getServerName();
                        if (mailHost == null || mailHost.trim().equals(""))
                            mailHost = mail.getRemoteHost();

                        MailAddress replyTo = new MailAddress(mailId, mailHost);
                        if (M_log.isDebugEnabled()) {
                            M_log.debug("Set Reply-To address to " + replyTo.toString());
                        }
                        modifiedHeaders.add("Reply-To: " + replyTo.toString());

                        // post the message to the group's channel
                        channel.addMailArchiveMessage(subject, from.toString(),
                                timeService.newTime(sent.getTime()), modifiedHeaders, attachments, body);
                    } else {
                        // post the message to the group's channel
                        channel.addMailArchiveMessage(subject, from.toString(),
                                timeService.newTime(sent.getTime()), mailHeaders, attachments, body);
                    }
                } catch (PermissionException pe) {
                    // INDICATES that the current user does not have permission to add or get the mail archive message from the current channel
                    // This generally should not happen because the current user should be the postmaster
                    M_log.warn("mailarchive PermissionException message service failure: (id=" + id
                            + ") (mailId=" + mailId + ") : " + pe, pe);
                    mail.setState(Mail.GHOST); // ghost out the message because this should not happen
                }

                if (M_log.isDebugEnabled()) {
                    M_log.debug(id + " : delivered to:" + mailId);
                }

                // all is happy - ghost the message to stop further processing
                mail.setState(Mail.GHOST);
            } catch (IdUnusedException goOn) {
                // INDICATES that the channelReference found above was actually invalid OR that no channel reference could be identified

                // if this is to the postmaster, and there's no site, channel or alias for the postmaster, then quietly eat the message
                if (POSTMASTER.equals(mailId) || from.startsWith(POSTMASTER + "@")) {
                    mail.setState(Mail.GHOST);
                    continue;
                }

                // BOUNCE REPLY - send a message back to the user to let them know their email failed
                if (M_log.isInfoEnabled()) {
                    M_log.info("mailarchive invalid or unusable channel reference (" + mailId + "): " + id
                            + " : mail rejected: " + goOn.toString());
                }
                String errMsg = rb.getString("err_addr_unknown") + "\n\n";
                String mailSupport = StringUtils
                        .trimToNull(serverConfigurationService.getString("mail.support"));
                if (mailSupport != null) {
                    errMsg += (String) rb.getFormattedMessage("err_questions", new Object[] { mailSupport })
                            + "\n";
                }
                mail.setErrorMessage(errMsg);
                mail.setState(courseMailArchiveNotExistsProcessor);
            } catch (Exception ex) {
                // INDICATES that some general exception has occurred which we did not expect
                // This definitely should NOT happen
                M_log.error("mailarchive General message service exception: (id=" + id + ") (mailId=" + mailId
                        + ") : " + ex, ex);
                mail.setState(Mail.GHOST); // ghost the message to stop it from being further processed
            }
        }
    } finally {
        // clear out any current current bindings
        threadLocalManager.clear();
    }
}

From source file:org.silverpeas.components.mailinglist.service.job.MailProcessor.java

/**
 * Process an email, extracting attachments and constructing a Message.
 * @param mail the email to be processed.
 * @param mailingList the mailing list it is going to be affected to.
 * @param event the event which will be send at the end of all processing.
 * @throws MessagingException/*from w w w.j  av a  2 s .  c  om*/
 * @throws IOException
 */
public void prepareMessage(MimeMessage mail, MessageListener mailingList, MessageEvent event)
        throws MessagingException, IOException {
    String sender = ((InternetAddress[]) mail.getFrom())[0].getAddress();
    if (!mailingList.checkSender(sender)) {
        return;
    }
    Message message = new Message();
    message.setComponentId(mailingList.getComponentId());
    message.setSender(sender);
    message.setSentDate(mail.getSentDate());
    message.setMessageId(mail.getMessageID());
    String[] referenceId = mail.getHeader(MAIL_HEADER_IN_REPLY_TO);
    if (referenceId == null || referenceId.length == 0) {
        referenceId = mail.getHeader(MAIL_HEADER_REFERENCES);
    }
    if (referenceId == null || referenceId.length == 0) {
        message.setReferenceId(null);
    } else {
        message.setReferenceId(referenceId[0]);
    }
    message.setTitle(mail.getSubject());
    Object content = mail.getContent();
    if (content instanceof Multipart) {
        processMultipart((Multipart) content, message);
    } else if (content instanceof String) {
        processBody((String) content, mail.getContentType(), message);
    }
    event.addMessage(message);
}

From source file:org.silverpeas.core.mail.SmtpMailSendingTest.java

private void assertMailSent(MailToSend verifiedMailToSend, GreenMailOperations mail) throws Exception {
    assertThat("assertMailSent is compatible with one receiver only...", verifiedMailToSend.getTo(),
            hasSize(1));//www .  j  av a2  s . co m

    assertThat(verifiedMailToSend.getTo().getRecipientType().getTechnicalType(), is(Message.RecipientType.TO));

    MimeMessage[] messages = mail.getReceivedMessages();
    assertThat(messages, arrayWithSize(1));

    MimeMessage sentMessage = messages[0];
    MailAddress originalReceiverMailAddress = verifiedMailToSend.getTo().iterator().next();

    assertThat(sentMessage.getFrom().length, is(1));
    assertThat(sentMessage.getFrom()[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressFrom = (InternetAddress) sentMessage.getFrom()[0];
    assertThat(internetAddressFrom.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
    assertThat(internetAddressFrom.getPersonal(),
            is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));

    assertThat(sentMessage.getRecipients(Message.RecipientType.TO).length, is(1));
    assertThat(sentMessage.getRecipients(Message.RecipientType.CC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.BCC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.TO)[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressTo = (InternetAddress) sentMessage
            .getRecipients(Message.RecipientType.TO)[0];
    assertThat(internetAddressTo.getAddress(), is(originalReceiverMailAddress.getEmail()));
    assertThat(internetAddressTo.getPersonal(), nullValue());

    assertThat(sentMessage.getSubject(), is(verifiedMailToSend.getSubject()));
    if (verifiedMailToSend.getContent().getValue() instanceof Multipart) {
        assertThat(sentMessage.getContent(), instanceOf(verifiedMailToSend.getContent().getValue().getClass()));
    } else {
        assertThat(sentMessage.getContent().toString().replaceAll("[\n\r]*$", ""),
                is(verifiedMailToSend.getContent().getValue()));
    }

    assertThat(DateUtils.addSeconds(sentMessage.getSentDate(), 10), greaterThanOrEqualTo(new Date()));

    assertThat(sentMessage.getReplyTo().length, is(1));
    if (verifiedMailToSend.isReplyToRequired()) {
        assertThat(sentMessage.getHeader("Reply-To"), notNullValue());
        assertThat(sentMessage.getReplyTo()[0], instanceOf(InternetAddress.class));
        InternetAddress internetAddressReplyTo = (InternetAddress) sentMessage.getReplyTo()[0];
        assertThat(internetAddressReplyTo.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
        assertThat(internetAddressReplyTo.getPersonal(),
                is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));
    } else {
        assertThat(sentMessage.getHeader("Reply-To"), nullValue());
        assertThat(sentMessage.getReplyTo()[0].toString(), is(internetAddressFrom.toString()));
    }
}

From source file:org.silverpeas.core.mail.TestSmtpMailSending.java

private void assertMailSent(MailToSend verifiedMailToSend) throws Exception {
    assertThat("assertMailSent is compatible with one receiver only...", verifiedMailToSend.getTo(),
            hasSize(1));/*from   w w  w.j av  a  2 s  . c  o m*/

    assertThat(verifiedMailToSend.getTo().getRecipientType().getTechnicalType(), is(Message.RecipientType.TO));

    MimeMessage[] messages = greenMailRule.getReceivedMessages();
    assertThat(messages, arrayWithSize(1));

    MimeMessage sentMessage = messages[0];
    MailAddress originalReceiverMailAddress = verifiedMailToSend.getTo().iterator().next();

    assertThat(sentMessage.getFrom().length, is(1));
    assertThat(sentMessage.getFrom()[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressFrom = (InternetAddress) sentMessage.getFrom()[0];
    assertThat(internetAddressFrom.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
    assertThat(internetAddressFrom.getPersonal(),
            is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));

    assertThat(sentMessage.getRecipients(Message.RecipientType.TO).length, is(1));
    assertThat(sentMessage.getRecipients(Message.RecipientType.CC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.BCC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.TO)[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressTo = (InternetAddress) sentMessage
            .getRecipients(Message.RecipientType.TO)[0];
    assertThat(internetAddressTo.getAddress(), is(originalReceiverMailAddress.getEmail()));
    assertThat(internetAddressTo.getPersonal(), nullValue());

    assertThat(sentMessage.getSubject(), is(verifiedMailToSend.getSubject()));
    if (verifiedMailToSend.getContent().getValue() instanceof Multipart) {
        assertThat(sentMessage.getContent(), instanceOf(verifiedMailToSend.getContent().getValue().getClass()));
    } else {
        assertThat(sentMessage.getContent().toString().replaceAll("[\n\r]*$", ""),
                is(verifiedMailToSend.getContent().getValue()));
    }

    assertThat(DateUtils.addSeconds(sentMessage.getSentDate(), 10), greaterThanOrEqualTo(new Date()));

    assertThat(sentMessage.getReplyTo().length, is(1));
    if (verifiedMailToSend.isReplyToRequired()) {
        assertThat(sentMessage.getHeader("Reply-To"), notNullValue());
        assertThat(sentMessage.getReplyTo()[0], instanceOf(InternetAddress.class));
        InternetAddress internetAddressReplyTo = (InternetAddress) sentMessage.getReplyTo()[0];
        assertThat(internetAddressReplyTo.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
        assertThat(internetAddressReplyTo.getPersonal(),
                is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));
    } else {
        assertThat(sentMessage.getHeader("Reply-To"), nullValue());
        assertThat(sentMessage.getReplyTo()[0].toString(), is(internetAddressFrom.toString()));
    }
}

From source file:org.springframework.mail.javamail.JavaMailSenderImpl.java

/**
 * Actually send the given array of MimeMessages via JavaMail.
 * @param mimeMessages MimeMessage objects to send
 * @param originalMessages corresponding original message objects
 * that the MimeMessages have been created from (with same array
 * length and indices as the "mimeMessages" array), if any
 * @throws org.springframework.mail.MailAuthenticationException
 * in case of authentication failure//from  ww w . j a  v a2 s  .  c o m
 * @throws org.springframework.mail.MailSendException
 * in case of failure when sending a message
 */
protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException {
    Map failedMessages = new HashMap();
    try {
        Transport transport = getTransport(getSession());
        transport.connect(getHost(), getPort(), getUsername(), getPassword());
        try {
            for (int i = 0; i < mimeMessages.length; i++) {
                MimeMessage mimeMessage = mimeMessages[i];
                try {
                    if (mimeMessage.getSentDate() == null) {
                        mimeMessage.setSentDate(new Date());
                    }
                    mimeMessage.saveChanges();
                    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
                } catch (MessagingException ex) {
                    Object original = (originalMessages != null ? originalMessages[i] : mimeMessage);
                    failedMessages.put(original, ex);
                }
            }
        } finally {
            transport.close();
        }
    } catch (AuthenticationFailedException ex) {
        throw new MailAuthenticationException(ex);
    } catch (MessagingException ex) {
        throw new MailSendException("Mail server connection failed", ex);
    }
    if (!failedMessages.isEmpty()) {
        throw new MailSendException(failedMessages);
    }
}

From source file:won.preprocessing.MailProcessing.java

/**
 * Read mail files from the input folder, extract several fields (e.g. subject, content, from,
 * to) and save this data back into a text file of the output folder.
 *
 * @param inputFolder  input folder with the mails
 * @param outputFolder output folder with extracted content files
 * @throws IOException/*from   w w  w.j av  a 2 s  .c  om*/
 */
private static void preprocessMails(String inputFolder, String outputFolder) throws IOException {

    File inFolder = new File(inputFolder);
    File outFolder = new File(outputFolder);
    outFolder.mkdirs();

    if (!inFolder.isDirectory()) {
        throw new IOException("Input folder not a directory: " + inputFolder);
    }
    if (!outFolder.isDirectory()) {
        throw new IOException("Output folder not a directory: " + outputFolder);
    }

    logger.info("preprocessing mail files: ");
    logger.info("- input folder {}", inputFolder);
    logger.info("- output folder {}", outputFolder);

    for (File file : inFolder.listFiles()) {
        if (file.isDirectory()) {
            continue;
        }

        logger.debug("processing mail file: {} ", file);
        FileInputStream fis = null;
        Writer fw = null;

        try {
            fis = new FileInputStream(file);
            MimeMessage emailMessage = new MimeMessage(null, fis);
            MimeMessageParser parser = new MimeMessageParser(emailMessage);
            parser.parse();
            String content = null;
            if (parser.hasPlainContent()) {
                content = parser.getPlainContent();
                int endIndex = content.indexOf("-------------");
                if (endIndex != -1) {
                    content = content.substring(0, endIndex);
                }
            } else {
                logger.warn("no plain content in file: {}, use HTML content", file);
                content = parser.getHtmlContent();
            }

            File outfile = new File(outputFolder + "/" + file.getName());
            logger.debug("writing output file: {}", outfile.getAbsolutePath());
            logger.debug("- mail subject: {}", parser.getSubject());
            FileOutputStream outputStream = new FileOutputStream(outfile);

            // Enforce UTF-8 when writing files. Non UTF-8 files will be reported.
            fw = new OutputStreamWriter(outputStream, Charset.forName("UTF-8"));

            fw.append(FROM_PREFIX + parser.getFrom() + "\n");
            fw.append(TO_PREFIX + parser.getTo() + "\n");
            fw.append(DATE_PREFIX + emailMessage.getSentDate() + "\n");
            fw.append(SUBJECT_PREFIX + parser.getSubject() + "\n");
            fw.append(CONTENT_PREFIX + /*parser.getPlainContent()*/content + "\n");

        } catch (MessagingException me) {
            logger.error("Error opening mail file: " + file.getAbsolutePath(), me);
        } catch (IOException ioe) {
            logger.error("Error writing file: " + file.getAbsolutePath(), ioe);
            System.err.println("Error writing file: " + file.getAbsolutePath());
        } catch (Exception e) {
            logger.error("Error parsing mail file: " + file.getAbsolutePath(), e);
        } finally {
            if (fis != null)
                fis.close();
            if (fw != null)
                fw.close();
        }
    }
}