Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Multipart mp) throws MessagingException 

Source Link

Document

This method sets the Message's content to a Multipart object.

Usage

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessEmailTextWithAttachment() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);
    MessageListener mockListener2 = mock(MessageListener.class);
    messageChecker.addMessageListener(mockListener1);
    messageChecker.addMessageListener(mockListener2);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Plain text Email test with attachment");
    MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html"));
    attachment.setDisposition(Part.INLINE);
    attachment.setFileName("lemonde.html");
    MimeBodyPart body = new MimeBodyPart();
    body.setText(textEmailContent);//from  w  ww. j  ava 2 s . c  o m
    Multipart multiPart = new MimeMultipart();
    multiPart.addBodyPart(body);
    multiPart.addBodyPart(attachment);
    mail.setContent(multiPart);
    mail.setSentDate(new Date());
    Date sentDate = new Date(mail.getSentDate().getTime());
    Transport.send(mail);
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Plain text Email test with attachment", message.getTitle());
    assertEquals(textEmailContent, message.getBody());
    assertEquals(textEmailContent.substring(0, 200), message.getSummary());
    assertEquals(ATT_SIZE, message.getAttachmentsSize());
    assertEquals(1, message.getAttachments().size());
    String path = MessageFormat.format(attachmentPath,
            messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()));
    Attachment attached = message.getAttachments().iterator().next();
    assertEquals(path, attached.getPath());
    assertEquals("lemonde.html", attached.getFileName());
    assertEquals("componentId", message.getComponentId());
    assertEquals(sentDate.getTime(), message.getSentDate().getTime());
    assertEquals("text/plain", message.getContentType());
    org.jvnet.mock_javamail.Mailbox.clearAll();
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
    verify(mockListener1, times(2)).getComponentId();
}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendFiles(String to, String subject, String text, Collection<File> attachments)
        throws MessagingException {

    MimeMessage message = new MimeMessage(session);
    Transport t = session.getTransport("smtp");

    message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);/*from  w  ww.ja va 2  s  . c  om*/
    message.setSentDate(new Date());
    if (attachments == null || attachments.size() < 1) {
        message.setText(text);
    } else {
        // create the message part 
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(text);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        for (File attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(attachment.getName());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart);
    }

    t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

    t.sendMessage(message, message.getAllRecipients());
    t.close();
}

From source file:org.openmeetings.test.calendar.TestSendIcalMessage.java

private void sendIcalMessage() throws Exception {

    log.debug("sendIcalMessage");

    // Evaluating Configuration Data
    String smtpServer = cfgManagement.getConfKey(3, "smtp_server").getConf_value();
    String smtpPort = cfgManagement.getConfKey(3, "smtp_port").getConf_value();
    // String from = "openmeetings@xmlcrm.org";
    String from = cfgManagement.getConfKey(3, "system_email_addr").getConf_value();

    String emailUsername = cfgManagement.getConfKey(3, "email_username").getConf_value();
    String emailUserpass = cfgManagement.getConfKey(3, "email_userpass").getConf_value();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", smtpServer);
    props.put("mail.smtp.port", smtpPort);

    Configuration conf = cfgManagement.getConfKey(3, "mail.smtp.starttls.enable");
    if (conf != null) {
        if (conf.getConf_value().equals("1")) {
            props.put("mail.smtp.starttls.enable", "true");
        }/*from w w w.  j  a  v  a  2s .c  o m*/
    }

    // Check for Authentification
    Session session = null;
    if (emailUsername != null && emailUsername.length() > 0 && emailUserpass != null
            && emailUserpass.length() > 0) {
        // use SMTP Authentication
        props.put("mail.smtp.auth", "true");
        session = Session.getDefaultInstance(props, new SmtpAuthenticator(emailUsername, emailUserpass));
    } else {
        // not use SMTP Authentication
        session = Session.getDefaultInstance(props, null);
    }

    // Building MimeMessage
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setSubject(subject);
    mimeMessage.setFrom(new InternetAddress(from));
    mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));

    // -- Create a new message --
    BodyPart msg = new MimeBodyPart();
    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody, "text/html; charset=\"utf-8\"")));

    Multipart multipart = new MimeMultipart();

    BodyPart iCalAttachment = new MimeBodyPart();
    iCalAttachment.setDataHandler(new DataHandler(new javax.mail.util.ByteArrayDataSource(
            new ByteArrayInputStream(iCalMimeBody), "text/calendar;method=REQUEST;charset=\"UTF-8\"")));
    iCalAttachment.setFileName("invite.ics");

    multipart.addBodyPart(iCalAttachment);
    multipart.addBodyPart(msg);

    mimeMessage.setSentDate(new Date());
    mimeMessage.setContent(multipart);

    // -- Set some other header information --
    // mimeMessage.setHeader("X-Mailer", "XML-Mail");
    // mimeMessage.setSentDate(new Date());

    // Transport trans = session.getTransport("smtp");
    Transport.send(mimeMessage);

}

From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java

public static void notifyAccountDeleted(TemporaryMailContainer container) {
    try {/*ww w .java2s  . c o m*/
        Publisher publisher = container.getPublisher();
        Publisher deletedBy = container.getDeletedBy();
        String emailaddress = publisher.getEmailAddress();
        if (emailaddress == null || emailaddress.trim().equals(""))
            return;
        Properties properties = new Properties();
        Session session = null;
        String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX,
                Property.DEFAULT_JUDDI_EMAIL_PREFIX);
        if (!mailPrefix.endsWith(".")) {
            mailPrefix = mailPrefix + ".";
        }
        for (String key : mailProps) {
            if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) {
                properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key));
            } else if (System.getProperty(mailPrefix + key) != null) {
                properties.put(key, System.getProperty(mailPrefix + key));
            }
        }

        boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true");
        if (auth) {
            final String username = properties.getProperty("mail.smtp.user");
            String pwd = properties.getProperty("mail.smtp.password");
            //decrypt if possible
            if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false")
                    .equalsIgnoreCase("true")) {
                try {
                    pwd = CryptorFactory.getCryptor().decrypt(pwd);
                } catch (NoSuchPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (NoSuchAlgorithmException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidAlgorithmParameterException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidKeyException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (IllegalBlockSizeException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (BadPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                }
            }
            final String password = pwd;
            log.debug("SMTP username = " + username + " from address = " + emailaddress);
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(properties, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        } else {
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(eMailProperties);
        }

        MimeMessage message = new MimeMessage(session);
        InternetAddress address = new InternetAddress(emailaddress);
        Address[] to = { address };
        message.setRecipients(RecipientType.TO, to);
        message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI")));
        //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s

        Multipart mp = new MimeMultipart();

        MimeBodyPart content = new MimeBodyPart();
        String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ");
        //Hello %s, %s,<br><br>Your account has been deleted by %s, %s at %s. This node is %s.
        msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()),
                StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()),
                StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(sdf.format(new Date())),
                StringEscapeUtils.escapeHtml(
                        AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)"));

        content.setContent(msg_content, "text/html; charset=UTF-8;");
        mp.addBodyPart(content);

        message.setContent(mp);
        message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted.subject"));
        Transport.send(message);

    } catch (Throwable t) {
        log.warn("Error sending email!" + t.getMessage());
        log.debug("Error sending email!" + t.getMessage(), t);
    }
}

From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java

private void sendEmail(boolean test, AmazonSimpleEmailServiceClient emailService, String email,
        List<ApplicationGroup> appGroups) throws IOException, MessagingException {

    StringBuilder body = new StringBuilder();
    body.append(//ww w  .j av  a2 s.c  o m
            "<html><head><style type=\"text/css\">a:link, a:visited{color:#006DBA;}a:link, a:visited, a:hover {\n"
                    + "text-decoration: none;\n" + "}\n" + "body {\n" + "color: #333;\n" + "}"
                    + "</style></head>");
    List<MimeBodyPart> mimeBodyParts = Lists.newArrayList();
    int index = 0;
    String subject = "";
    for (ApplicationGroup appGroup : appGroups) {
        boolean hasData = false;
        for (String prodName : appGroup.data.keySet()) {
            if (config.productService.getProductByName(prodName) == null)
                continue;
            hasData = appGroup.data.get(prodName) != null && appGroup.data.get(prodName).size() > 0;
            if (hasData)
                break;
        }
        if (!hasData)
            continue;

        try {
            MimeBodyPart mimeBodyPart = constructEmail(index, appGroup, body);
            index++;
            if (mimeBodyPart != null) {
                mimeBodyParts.add(mimeBodyPart);
                subject = subject + (subject.length() > 0 ? ", " : "") + appGroup.getDisplayName();
            }
        } catch (Exception e) {
            logger.error("Error contructing email", e);
        }
    }
    body.append("</html>");

    if (mimeBodyParts.size() == 0)
        return;

    DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0);
    subject = String.format("%s Weekly AWS Costs (%s - %s)", subject, formatter.print(end.minusWeeks(1)),
            formatter.print(end));
    String toEmail = test ? testEmail : email;
    Session session = Session.getInstance(new Properties());
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setSubject(subject);
    mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO, toEmail);
    if (!test && !StringUtils.isEmpty(bccEmail)) {
        mimeMessage.addRecipients(Message.RecipientType.BCC, bccEmail);
    }
    MimeMultipart mimeMultipart = new MimeMultipart();
    BodyPart p = new MimeBodyPart();
    p.setContent(body.toString(), "text/html");
    mimeMultipart.addBodyPart(p);

    for (MimeBodyPart mimeBodyPart : mimeBodyParts)
        mimeMultipart.addBodyPart(mimeBodyPart);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    mimeMessage.setContent(mimeMultipart);
    mimeMessage.writeTo(outputStream);
    RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));

    SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
    rawEmailRequest.setDestinations(Lists.<String>newArrayList(toEmail));
    rawEmailRequest.setSource(fromEmail);
    logger.info("sending email to " + toEmail + " " + body.toString());
    emailService.sendRawEmail(rawEmailRequest);
}

From source file:org.codice.alliance.core.email.impl.EmailSenderImpl.java

/** sendEmail method sends email after receiving input parameters */
@Override/*from  w ww  . ja v a  2  s.c o m*/
public void sendEmail(String fromEmail, String toEmail, String subject, String body,
        List<Pair<String, InputStream>> attachments) throws IOException {
    notNull(fromEmail, "fromEmail must be non-null");
    notNull(toEmail, "toEmail must be non-null");
    notNull(subject, "subject must be non-null");
    notNull(body, "body must be non-null");
    notNull(attachments, "attachments must be non-null");

    if (StringUtils.isBlank(mailHost)) {
        throw new IOException("the mail server hostname has not been configured");
    }

    List<File> tempFiles = new LinkedList<>();

    try {
        InternetAddress emailAddr = new InternetAddress(toEmail);
        emailAddr.validate();

        Properties properties = createSessionProperties();

        Session session = Session.getDefaultInstance(properties);

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(fromEmail));
        mimeMessage.addRecipient(Message.RecipientType.TO, emailAddr);
        mimeMessage.setSubject(subject);

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        Holder<Long> bytesWritten = new Holder<>(0L);

        for (Pair<String, InputStream> attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            File file = File.createTempFile("email-sender-", ".dat");
            tempFiles.add(file);

            copyDataToTempFile(file, attachment.getValue(), bytesWritten);
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(file)));
            messageBodyPart.setFileName(attachment.getKey());
            multipart.addBodyPart(messageBodyPart);
        }

        mimeMessage.setContent(multipart);

        send(mimeMessage);

        LOGGER.debug("Email sent to " + toEmail);

    } catch (AddressException e) {
        throw new IOException("invalid email address: email=" + toEmail, e);
    } catch (MessagingException e) {
        throw new IOException("message error occurred on send", e);
    } finally {
        tempFiles.forEach(file -> {
            if (!file.delete()) {
                LOGGER.debug("unable to delete tmp file: path={}", file);
            }
        });
    }
}

From source file:org.apache.james.transport.mailets.StripAttachmentTest.java

@Test
public void testSimpleAttachment2() throws MessagingException, IOException {
    Mailet mailet = new StripAttachment();

    FakeMailetConfig mci = new FakeMailetConfig("Test", FakeMailContext.defaultContext());
    mci.setProperty("directory", "./");
    mci.setProperty("remove", "all");
    mci.setProperty("notpattern", "^(winmail\\.dat$)");
    mailet.init(mci);//from   www. j  av  a 2 s  .  c  om

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMultipart mm = new MimeMultipart();
    MimeBodyPart mp = new MimeBodyPart();
    mp.setText("simple text");
    mm.addBodyPart(mp);
    String body = "\u0023\u00A4\u00E3\u00E0\u00E9";
    MimeBodyPart mp2 = new MimeBodyPart(
            new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body).getBytes("UTF-8")));
    mp2.setDisposition("attachment");
    mp2.setFileName("temp.tmp");
    mm.addBodyPart(mp2);
    String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4";
    MimeBodyPart mp3 = new MimeBodyPart(
            new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body2).getBytes("UTF-8")));
    mp3.setDisposition("attachment");
    mp3.setFileName("winmail.dat");
    mm.addBodyPart(mp3);
    message.setSubject("test");
    message.setContent(mm);
    message.saveChanges();

    Mail mail = FakeMail.builder().mimeMessage(message).build();

    mailet.service(mail);

    ByteArrayOutputStream rawMessage = new ByteArrayOutputStream();
    mail.getMessage().writeTo(rawMessage, new String[] { "Bcc", "Content-Length", "Message-ID" });
    // String res = rawMessage.toString();

    @SuppressWarnings("unchecked")
    Collection<String> c = (Collection<String>) mail
            .getAttribute(StripAttachment.SAVED_ATTACHMENTS_ATTRIBUTE_KEY);
    Assert.assertNotNull(c);

    Assert.assertEquals(1, c.size());

    String name = c.iterator().next();

    File f = new File("./" + name);
    try {
        InputStream is = new FileInputStream(f);
        String savedFile = toString(is);
        is.close();
        Assert.assertEquals(body, savedFile);
    } finally {
        FileUtils.deleteQuietly(f);
    }
}

From source file:pt.ist.fenix.api.SupportFormResource.java

private void sendEmail(String from, String subject, String body, SupportBean bean) {
    Properties props = new Properties();
    props.put("mail.smtp.host", Objects
            .firstNonNull(FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost(), "localhost"));
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    try {/*  ww w .  j  a va2s  . c o m*/
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(CoreConfiguration.getConfiguration().defaultSupportEmailAddress()));
        message.setSubject(subject);
        message.setText(body);

        Multipart multipart = new MimeMultipart();
        {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            multipart.addBodyPart(messageBodyPart);
        }

        if (!Strings.isNullOrEmpty(bean.attachment)) {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(
                    new ByteArrayDataSource(Base64.getDecoder().decode(bean.attachment), bean.mimeType)));
            messageBodyPart.setFileName(bean.fileName);
            multipart.addBodyPart(messageBodyPart);
        }

        message.setContent(multipart);

        Transport.send(message);
    } catch (Exception e) {
        logger.error("Could not send support email! Original message was: " + body, e);
    }
}

From source file:org.grouter.common.mail.MailHandler.java

/**
 * Creates a multipart email with html and plain text email body to fallback to if
 * email client do not handle html base emails.
 *
 * @param mimeMessage/*from   w  w  w  .j  av a2 s  .c  om*/
 * @param dto
 * @throws MessagingException
 */
private void createHtmlAndPlainTextBody(MimeMessage mimeMessage, MailDto dto) throws MessagingException {
    if (StringUtils.isNotEmpty(dto.getHtmlTextBody())) {
        mimeMessage.setContentID(MailDto.CONTENT_TYPE_MULTIPART_ALTERNATIVE);

        // Create your text message part
        BodyPart plainBodyPart = new MimeBodyPart();
        plainBodyPart.setContent(dto.getPlainTextBody(), MailDto.CONTENT_TYPE_TEXT_PLAIN);

        // Create a multi-part to combine the parts
        Multipart multipart = new MimeMultipart("alternative");
        multipart.addBodyPart(plainBodyPart);

        StringBuilder sb = new StringBuilder();
        sb.append(PRE_HTML_HEADER);
        sb.append(dto.getSubject()).append("\n");
        sb.append(POST_HTML_HEADER);
        sb.append(dto.getHtmlTextBody());
        sb.append(END_HTML);

        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(sb.toString(), MailDto.CONTENT_TYPE_TEXT_HTML);

        // Add html part to multi part
        multipart.addBodyPart(htmlBodyPart);
        mimeMessage.setContent(multipart);
    } else {
        mimeMessage.setSubject(dto.getSubject());
        mimeMessage.setText(dto.getPlainTextBody());
        mimeMessage.setContent(dto.getPlainTextBody(), MailDto.CONTENT_TYPE_TEXT_PLAIN);
    }

}

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessEmailHtmlTextWithAttachment() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);
    MessageListener mockListener2 = mock(MessageListener.class);
    messageChecker.addMessageListener(mockListener1);
    messageChecker.addMessageListener(mockListener2);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Html Email test with attachment");
    String html = loadHtml();//from  w w  w  .ja va2  s .  co  m
    MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html"));
    attachment.setDisposition(Part.ATTACHMENT);
    attachment.setFileName("lemonde.html");
    MimeBodyPart body = new MimeBodyPart();
    body.setContent(html, "text/html; charset=\"UTF-8\"");
    Multipart multiPart = new MimeMultipart();
    multiPart.addBodyPart(body);
    multiPart.addBodyPart(attachment);
    mail.setContent(multiPart);
    Transport.send(mail);
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Html Email test with attachment", message.getTitle());
    assertEquals(html, message.getBody());
    assertEquals(htmlEmailSummary, message.getSummary());
    assertEquals(ATT_SIZE, message.getAttachmentsSize());
    assertEquals(1, message.getAttachments().size());
    String path = MessageFormat.format(attachmentPath,
            messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()));
    Attachment attached = message.getAttachments().iterator().next();
    assertEquals(path, attached.getPath());
    assertEquals("lemonde.html", attached.getFileName());
    assertEquals("componentId", message.getComponentId());
    assertEquals("text/html", message.getContentType());
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
}