Example usage for javax.mail.internet MimeBodyPart setContent

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

Introduction

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

Prototype

@Override
public void setContent(Object o, String type) throws MessagingException 

Source Link

Document

A convenience method for setting this body part's content.

Usage

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  ww  . ja  v  a2 s  . c o 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");
}

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

@Test
public void sendingMailSynchronouslyValidMailWithReplyTo() throws Exception {
    MailAddress senderEmail = MailAddress.eMail(COMMON_FROM).withName("From Personal Name");
    MailAddress receiverEmail = MailAddress.eMail(COMMON_TO).withName("To Personal Name");
    String subject = "A subject";
    Multipart content = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent("A content", MimeTypes.HTML_MIME_TYPE);
    content.addBodyPart(mimeBodyPart);/*from   www .j  a  va  2  s . c om*/
    MailSending mailSending = MailSending.from(senderEmail).to(receiverEmail).withSubject(subject)
            .withContent(content).setReplyToRequired();

    // Sending mail
    mailSending.sendSynchronously();

    // Verifying sent data
    MailToSend mailToSend = getStubbedSmtpMailSender().currentMailToSend;
    assertThat(mailToSend.getFrom(), is(senderEmail));
    assertThat(mailToSend.getTo(), hasItem(receiverEmail));
    assertThat(mailToSend.getSubject(), is(subject));
    assertThat(mailToSend.getContent().isHtml(), is(true));
    assertThat(mailToSend.getContent().toString(), is(content.toString()));
    assertThat(mailToSend.isReplyToRequired(), is(true));
    assertThat(mailToSend.isAsynchronous(), is(false));
    assertMailSent(mailToSend);
}

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

@Test
public void sendingMailSynchronouslyWithFromWithToPersonalWithSubjectWithMultipartContentAndDefaultValues()
        throws Exception {
    MailAddress senderEmail = MailAddress.eMail(COMMON_FROM);
    MailAddress receiverEmail = MailAddress.eMail(COMMON_TO).withName("To Personal Name");
    String subject = "A subject";
    Multipart content = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent("A content", MimeTypes.HTML_MIME_TYPE);
    content.addBodyPart(mimeBodyPart);// www .j  a  va  2 s. c  om
    MailSending mailSending = MailSending.from(senderEmail).to(receiverEmail).withSubject(subject)
            .withContent(content);

    // Sending mail
    mailSending.sendSynchronously();

    // Verifying sent data
    MailToSend mailToSend = getStubbedSmtpMailSender().currentMailToSend;
    assertThat(mailToSend.getFrom(), is(senderEmail));
    assertThat(mailToSend.getTo(), hasItem(receiverEmail));
    assertThat(mailToSend.getSubject(), is(subject));
    assertThat(mailToSend.getContent().isHtml(), is(true));
    assertThat(mailToSend.getContent().toString(), is(content.toString()));
    assertThat(mailToSend.isReplyToRequired(), is(false));
    assertThat(mailToSend.isAsynchronous(), is(false));
    assertMailSent(mailToSend);
}

From source file:com.assetmanager.service.mail.MailService.java

/**
 * Sends the activation e-mail to the given user.
 *
 * @param user the user//from   w w  w. jav a2 s .co m
 * @param locale the locale
 * @throws MessagingException messaging exception
 */
public final void sendActivationEmail(final UserAccount user, final String locale) throws MessagingException {
    final Properties props = new Properties();
    final Session session = Session.getDefaultInstance(props, null);
    final Message message = new MimeMessage(session);
    final Multipart multipart = new MimeMultipart();
    final MimeBodyPart htmlPart = new MimeBodyPart();
    final MimeBodyPart textPart = new MimeBodyPart();

    message.setFrom(new InternetAddress(getFromAddress()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));

    message.setSubject(messageSource.getMessage("mail.subject", null, new Locale(locale)));

    textPart.setContent(messageSource.getMessage("mail.body.txt",
            new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/plain");

    htmlPart.setContent(messageSource.getMessage("mail.body.html",
            new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/html");

    multipart.addBodyPart(textPart);
    multipart.addBodyPart(htmlPart);
    message.setContent(multipart);

    Transport.send(message);
}

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

@Test
public void sendingMailSynchronouslyValidMailWithReplyTo(GreenMailOperations mail) throws Exception {
    MailAddress senderEmail = MailAddress.eMail(COMMON_FROM).withName("From Personal Name");
    MailAddress receiverEmail = MailAddress.eMail(COMMON_TO).withName("To Personal Name");
    String subject = "A subject";
    Multipart content = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent("A content", MimeTypes.HTML_MIME_TYPE);
    content.addBodyPart(mimeBodyPart);/*from w w  w .  j  a v  a  2s  . co  m*/
    MailSending mailSending = MailSending.from(senderEmail).to(receiverEmail).withSubject(subject)
            .withContent(content).setReplyToRequired();

    // Sending mail
    mailSending.sendSynchronously();

    // Verifying sent data
    MailToSend mailToSend = getStubbedSmtpMailSender().currentMailToSend;
    assertThat(mailToSend.getFrom(), is(senderEmail));
    assertThat(mailToSend.getTo(), hasItem(receiverEmail));
    assertThat(mailToSend.getSubject(), is(subject));
    assertThat(mailToSend.getContent().isHtml(), is(true));
    assertThat(mailToSend.getContent().toString(), is(content.toString()));
    assertThat(mailToSend.isReplyToRequired(), is(true));
    assertThat(mailToSend.isAsynchronous(), is(false));
    assertMailSent(mailToSend, mail);
}

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

@Test
public void sendingMailSynchronouslyWithFromWithToPersonalWithSubjectWithMultipartContentAndDefaultValues(
        GreenMailOperations mail) throws Exception {
    MailAddress senderEmail = MailAddress.eMail(COMMON_FROM);
    MailAddress receiverEmail = MailAddress.eMail(COMMON_TO).withName("To Personal Name");
    String subject = "A subject";
    Multipart content = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent("A content", MimeTypes.HTML_MIME_TYPE);
    content.addBodyPart(mimeBodyPart);/* w w  w .  j  a va2  s . c  o m*/
    MailSending mailSending = MailSending.from(senderEmail).to(receiverEmail).withSubject(subject)
            .withContent(content);

    // Sending mail
    mailSending.sendSynchronously();

    // Verifying sent data
    MailToSend mailToSend = getStubbedSmtpMailSender().currentMailToSend;
    assertThat(mailToSend.getFrom(), is(senderEmail));
    assertThat(mailToSend.getTo(), hasItem(receiverEmail));
    assertThat(mailToSend.getSubject(), is(subject));
    assertThat(mailToSend.getContent().isHtml(), is(true));
    assertThat(mailToSend.getContent().toString(), is(content.toString()));
    assertThat(mailToSend.isReplyToRequired(), is(false));
    assertThat(mailToSend.isAsynchronous(), is(false));
    assertMailSent(mailToSend, mail);
}

From source file:com.waveerp.sendMail.java

public String sendMsgWithAttach(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc, String strPath) throws Exception {

    String strResult = "OK";

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.port", strPort);
    props.put("mail.user", strUser);
    props.put("mail.password", strPass01);

    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }//from   w  ww .j  a  va 2  s . c o  m
    };
    Session session = Session.getInstance(props, auth);

    // creates a new e-mail message
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(strSource));
    //InternetAddress[] toAddresses = { new InternetAddress(strDestination) };
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(strDestination));
    msg.setSubject(strSubject);
    msg.setSentDate(new Date());

    // creates message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(strMsg, "text/html");

    // creates multi-part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // adds attachments
    //if (attachFiles != null && attachFiles.length > 0) {
    //    for (String filePath : attachFiles) {
    //        MimeBodyPart attachPart = new MimeBodyPart();
    //
    //        try {
    //            attachPart.attachFile(filePath);
    //        } catch (IOException ex) {
    //            ex.printStackTrace();
    //        }
    //
    //        multipart.addBodyPart(attachPart);
    //    }
    //}

    String fna;
    String fnb;
    URL fileUrl;

    fileUrl = null;
    fileUrl = this.getClass().getResource("sendMail.class");
    fna = fileUrl.getPath();
    fna = fna.substring(0, fna.indexOf("WEB-INF"));
    //fnb = URLDecoder.decode( fna + TEMP_DIR + strPath );
    fnb = URLDecoder.decode(fna + strPath);

    MimeBodyPart attachPart = new MimeBodyPart();
    try {

        attachPart.attachFile(fnb);

    } catch (IOException ex) {

        //ex.printStackTrace();
        strResult = ex.getMessage();

    }
    multipart.addBodyPart(attachPart);

    // sets the multi-part as e-mail's content
    msg.setContent(multipart);

    // sends the e-mail
    Transport.send(msg);

    return strResult;

}

From source file:org.openiam.idm.srvc.msg.service.MailSenderClient.java

public void send(Message msg) {
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.transport.protocol", "smtp");

    if (username != null && !username.isEmpty()) {
        properties.setProperty("mail.user", username);
        properties.setProperty("mail.password", password);
    }//from   ww  w  .  j  a va 2  s .c o m

    if (port != null && !port.isEmpty()) {
        properties.setProperty("mail.smtp.port", port);
    }

    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(msg.getFrom());
        if (msg.getTo().size() > 1) {
            List<InternetAddress> addresses = msg.getTo();
            message.addRecipients(TO, addresses.toArray(new Address[addresses.size()]));
        } else {
            message.addRecipient(TO, msg.getTo().get(0));
        }
        if (msg.getBcc() != null && msg.getBcc().size() != 0) {
            if (msg.getTo().size() > 1) {
                List<InternetAddress> addresses = msg.getBcc();
                message.addRecipients(BCC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(TO, msg.getBcc().get(0));
            }
        }
        if (msg.getCc() != null && msg.getCc().size() > 0) {
            if (msg.getCc().size() > 1) {
                List<InternetAddress> addresses = msg.getCc();
                message.addRecipients(CC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(CC, msg.getCc().get(0));
            }
        }
        message.setSubject(msg.getSubject(), "UTF-8");
        MimeBodyPart mbp1 = new MimeBodyPart();
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();

        if (msg.getBodyType() == Message.BodyType.HTML_TEXT) {
            mbp1.setContent(msg.getBody(), "text/html");
        } else {
            mbp1.setText(msg.getBody(), "UTF-8");
        }
        if (port != null && !port.isEmpty()) {
            properties.setProperty("mail.smtp.port", port);
        }
        mp.addBodyPart(mbp1);
        if (msg.getAttachments().size() > 0) {
            for (String fileName : msg.getAttachments()) {
                // create the second message part
                MimeBodyPart mbpFile = new MimeBodyPart();
                // attach the file to the message
                FileDataSource fds = new FileDataSource(fileName);
                mbpFile.setDataHandler(new DataHandler(fds));
                mbpFile.setFileName(fds.getName());

                mp.addBodyPart(mbpFile);
            }
        }
        // add the Multipart to the message
        message.setContent(mp);

        if (username != null && !username.isEmpty()) {
            properties.setProperty("mail.user", username);
            properties.setProperty("mail.password", password);
            properties.put("mail.smtp.auth", auth);
            properties.put("mail.smtp.starttls.enable", starttls);
            Transport mailTransport = session.getTransport();
            mailTransport.connect(host, username, password);
            mailTransport.sendMessage(message, message.getAllRecipients());

        } else {
            Transport.send(message);
            log.debug("Message successfully sent.");
        }
    } catch (Throwable e) {
        log.error("Exception while sending mail", e);
    }
}

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

private MimeBodyPart createDSN(Mail originalMail) throws MessagingException {
    StringBuffer buffer = new StringBuffer();

    appendReportingMTA(buffer);//from  ww w. j a va  2 s.co m
    buffer.append("Received-From-MTA: dns; " + originalMail.getRemoteHost()).append(LINE_BREAK);

    for (MailAddress rec : originalMail.getRecipients()) {
        appendRecipient(buffer, rec, getDeliveryError(originalMail), originalMail.getLastUpdated());
    }

    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setContent(buffer.toString(), "text/plain");
    bodyPart.setHeader("Content-Type", "message/delivery-status");
    bodyPart.setDescription("Delivery Status Notification");
    bodyPart.setFileName("status.dat");
    return bodyPart;
}

From source file:org.viafirma.util.SendMailUtil.java

public MultiPartEmail buildMessage(String subject, String mailTo, String texto, String htmlTexto, String alias,
        String password) throws ExcepcionErrorInterno, ExcepcionCertificadoNoEncontrado {

    try {//from  w  w w  . j a va  2 s .  com
        // 1.- Preparamos el certificado
        // Recuperamos la clave privada asociada al alias
        PrivateKey privateKey = KeyStoreLoader.getPrivateKey(alias, password);
        if (privateKey == null) {
            throw new ExcepcionCertificadoNoEncontrado(
                    "No existe una clave privada para el alias  '" + alias + "'");
        }
        if (log.isDebugEnabled())
            log.info("Firmando el documento con el certificado " + alias);

        // Recuperamos el camino de confianza asociado al certificado
        List<Certificate> chain = KeyStoreLoader.getCertificateChain(alias);

        // Obtenemos los datos del certificado utilizado.
        X509Certificate certificadoX509 = (X509Certificate) chain.get(0);
        CertificadoGenerico datosCertificado = CertificadoGenericoFactory.getInstance()
                .generar(certificadoX509);
        String emailFrom = datosCertificado.getEmail();
        String emailFromDesc = datosCertificado.getCn();
        if (StringUtils.isEmpty(emailFrom)) {
            log.warn("El certificado indicado no tiene un email asociado, No es vlido para firmar emails"
                    + datosCertificado);
            throw new ExcepcionCertificadoNoEncontrado(
                    "El certificado indicado no tiene un email asociado, No es vlido para firmar emails.");
        }

        CertStore certificadosYcrls = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(chain), BouncyCastleProvider.PROVIDER_NAME);

        // 2.- Preparamos el mail
        MimeBodyPart bodyPart = new MimeBodyPart();
        MimeMultipart dataMultiPart = new MimeMultipart();

        MimeBodyPart msgHtml = new MimeBodyPart();
        if (StringUtils.isNotEmpty(htmlTexto)) {
            msgHtml.setContent(htmlTexto, Email.TEXT_HTML + "; charset=UTF-8");
        } else {
            msgHtml.setContent("<p>" + htmlTexto + "</p>", Email.TEXT_PLAIN + "; charset=UTF-8");
        }

        // create the message we want signed
        MimeBodyPart mensajeTexto = new MimeBodyPart();
        if (StringUtils.isNotEmpty(texto)) {
            mensajeTexto.setText(texto, "UTF-8");
        } else if (StringUtils.isEmpty(texto)) {
            mensajeTexto.setText(CadenaUtilities.cleanHtml(htmlTexto), "UTF-8");
        }
        dataMultiPart.addBodyPart(mensajeTexto);
        dataMultiPart.addBodyPart(msgHtml);

        bodyPart.setContent(dataMultiPart);

        // Crea el nuevo mensaje firmado
        MimeMultipart multiPart = createMultipartWithSignature(privateKey, certificadoX509, certificadosYcrls,
                bodyPart);

        // Creamos el mensaje que finalmente sera enviadio.
        MultiPartEmail mail = createMultiPartEmail(subject, mailTo, emailFrom, emailFromDesc, multiPart,
                multiPart.getContentType());

        return mail;
    } catch (InvalidAlgorithmParameterException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (NoSuchAlgorithmException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (NoSuchProviderException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (MessagingException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (CertificateParsingException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (CertStoreException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (SMIMEException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (EmailException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    }

}