Example usage for javax.mail.internet MimeMessage getSubject

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

Introduction

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

Prototype

@Override
public String getSubject() throws MessagingException 

Source Link

Document

Returns the value of the "Subject" header field.

Usage

From source file:org.nuxeo.ecm.core.convert.plugins.text.extractors.RFC822ToTextConverter.java

protected Blob extractTextFromMessage(Blob blob) {
    if (blob == null) {
        return null;
    }//from ww w  .  j  av  a 2s .com
    File f = null;
    OutputStream fo = null;
    try {
        MimeMessage msg = new MimeMessage((Session) null, blob.getStream());
        f = File.createTempFile("rfc822totext", ".txt");
        fo = new FileOutputStream(f);
        List<Part> parts = getAttachmentParts(msg);
        writeInfo(fo, msg.getSubject());
        writeInfo(fo, msg.getFrom());
        writeInfo(fo, msg.getRecipients(RecipientType.TO));
        writeInfo(fo, msg.getRecipients(RecipientType.CC));
        for (Part part : parts) {
            writeInfo(fo, part.getFileName());
            writeInfo(fo, part.getDescription());
            byte[] extracted = extractTextFromMessagePart(part);
            if (extracted != null) {
                writeInfo(fo, extracted);
            }
        }
        Blob outblob = new FileBlob(new FileInputStream(f));
        outblob.setMimeType(descriptor.getDestinationMimeType());
        return outblob;
    } catch (Exception e) {
        log.error(e);
    } finally {
        if (fo != null) {
            try {
                fo.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
        if (f != null) {
            f.delete();
        }
    }
    return null;
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

@Override
public void sendMessage(MimeMessage msg, MailerResult result) {
    try {/*  w  w w .j  av  a 2 s. c  om*/
        if (Settings.isJUnitTest()) {
            //we want not send really e-mails
        } else if (mailModule.isMailHostEnabled() && result.getReturnCode() == MailerResult.OK) {
            // now send the mail
            if (Settings.isDebuging()) {
                try {
                    logInfo("E-mail send: " + msg.getSubject());
                    logInfo("Content    : " + msg.getContent());
                } catch (IOException e) {
                    logError("", e);
                }
            }
            Transport.send(msg);
        } else if (Settings.isDebuging() && result.getReturnCode() == MailerResult.OK) {
            try {
                logInfo("E-mail send: " + msg.getSubject());
                logInfo("Content    : " + msg.getContent());
            } catch (IOException e) {
                logError("", e);
            }
        } else {
            result.setReturnCode(MailerResult.MAILHOST_UNDEFINED);
        }
    } catch (MessagingException e) {
        result.setReturnCode(MailerResult.SEND_GENERAL_ERROR);
        logWarn("Could not send mail", e);
    }
}

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

/**
 * Process incoming mail./*from  ww w .j av a  2s . com*/
 * 
 * @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  ww  w.  j  a va2 s .c  o  m
 * @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.SmtpMailSendingMassiveTest.java

@Test
public void sendingSeveralMailsSynchronouslyAndAsynchronouslyAndVerifyingSendingPerformedOneByOne(
        GreenMailOperations mail) throws Exception {

    List<Runnable> runnables = new ArrayList<>();
    List<Thread> threads = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        Runnable runnable = new SendOperation("ID_" + StringUtil.leftPad(String.valueOf(i), 3, "0"),
                (i % 4 != 0));//  ww  w  .  j av a  2 s. c o m
        runnables.add(runnable);
        threads.add(new Thread(runnable));
    }

    log("STARTING THREADS...");

    // Starting threads
    for (Thread thread : threads) {
        Thread.sleep(50);
        thread.start();
    }

    log(runnables.size() + " THREADS STARTED");
    log("WAITING ENDING OF THREADS...");

    // Waiting for the end of all threads.
    for (Thread thread : threads) {
        thread.join(60000);
    }

    log(runnables.size() + " THREADS STOPPED");

    // Verifying that mails has been sent
    mail.waitForIncomingEmail(60000, runnables.size());
    Thread.sleep(100);
    assertMailSentOneByOne(runnables);

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

    System.out.println("Received messages:");
    for (MimeMessage message : messages) {
        System.out.println("\t" + message.getSubject());
    }
}

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));//from   w w w .java  2 s  .  c  om

    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));//  w  w  w .j  av a2s.  com

    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.silverpeas.core.mail.TestSmtpMailSendingMassive.java

@Test
public void sendingSeveralMailsSynchronouslyAndAsynchronouslyAndVerifyingSendingPerformedOneByOne()
        throws Exception {

    List<Runnable> runnables = new ArrayList<>();
    List<Thread> threads = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        Runnable runnable = new SendOperation("ID_" + StringUtil.leftPad(String.valueOf(i), 3, "0"),
                (i % 4 != 0));//w w  w .j  a v a2s . co m
        runnables.add(runnable);
        threads.add(new Thread(runnable));
    }

    log("STARTING THREADS...");

    // Starting threads
    for (Thread thread : threads) {
        Thread.sleep(50);
        thread.start();
    }

    log(runnables.size() + " THREADS STARTED");
    log("WAITING ENDING OF THREADS...");

    // Waiting for the end of all threads.
    for (Thread thread : threads) {
        thread.join(60000);
    }

    log(runnables.size() + " THREADS STOPPED");

    // Verifying that mails has been sent
    greenMailRule.waitForIncomingEmail(60000, runnables.size());
    Thread.sleep(100);
    assertMailSentOneByOne(runnables);

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

    System.out.println("Received messages:");
    for (MimeMessage message : messages) {
        System.out.println("\t" + message.getSubject());
    }
}

From source file:org.sonarqube.tests.issue.IssueNotificationsTest.java

@Test
public void notifications_for_personalized_emails() throws Exception {
    String version = RandomStringUtils.randomAlphanumeric(10);
    // 1st analysis without any issue (because no file is analyzed)
    createSampleProject(privateProject ? "private" : "public");
    createUsers();//from   w  w  w . j  a  va  2s.co  m
    tester.settings().setGlobalSettings("sonar.issues.defaultAssigneeLogin", userWithUserRole.getLogin());

    runAnalysis("issue/xoo-with-scm", "sonar.projectVersion", version, "sonar.scm.provider", "xoo",
            "sonar.scm.disabled", "false", "sonar.exclusions", "**/*");

    // No email since all code is ignored
    waitUntilAllNotificationsAreDelivered(1);
    assertThat(smtpServer.getMessages()).isEmpty();

    // run 2nd analysis which will generate issues on the leak period
    runAnalysis("issue/xoo-with-scm", "sonar.projectVersion", version, "sonar.scm.provider", "xoo",
            "sonar.scm.disabled", "false");

    // We expect to receive a notification for each subscriber with UserRole.user
    // And a personalized email for the assignee userWithUserRole
    waitUntilAllNotificationsAreDelivered(privateProject ? 3 : 4);
    assertThat(smtpServer.getMessages()).hasSize(privateProject ? 3 : 4);

    // the last email sent is the personalized one
    MimeMessage message = smtpServer.getMessages().get(privateProject ? 2 : 3).getMimeMessage();

    assertThat(message.getHeader("To", null)).isEqualTo(format("<%s>", userWithUserRole.getEmail()));
    assertThat(message.getSubject()).contains("You have 13 new issues");
    assertThat((String) message.getContent()).contains("Project: Sample").contains("Version: " + version);
}

From source file:org.sonarqube.tests.qualityProfile.BuiltInQualityProfilesNotificationTest.java

private String getSubject(MimeMessage mimeMessage) {
    try {//from   w w w.  ja  v a2  s. co  m
        return mimeMessage.getSubject();
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}