Example usage for javax.mail.internet MimeBodyPart MimeBodyPart

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

Introduction

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

Prototype

public MimeBodyPart() 

Source Link

Document

An empty MimeBodyPart object is created.

Usage

From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java

/**
 * Fill the body of a message already created.
 * The result message depends on the information given.
 *
 * @param message/*from  w  ww .  ja v a  2 s  .  c  om*/
 * @param text
 * @param html
 * @param parts
 * @return The composed message
 * @throws MessagingException
 * @throws IOException
 */
@SuppressWarnings("rawtypes")
public static Message composeMessage(Message message, String text, String html, List parts)
        throws MessagingException, IOException {

    MimeBodyPart txtPart = null;
    MimeBodyPart htmlPart = null;
    MimeMultipart mimeMultipart = null;

    if (text == null && html == null) {
        text = "";
    }
    if (text != null) {
        txtPart = new MimeBodyPart();
        txtPart.setContent(text, "text/plain; charset=UTF-8");
    }
    if (html != null) {
        htmlPart = new MimeBodyPart();
        htmlPart.setContent(html, "text/html; charset=UTF-8");
    }
    if (html != null && text != null) {
        mimeMultipart = new MimeMultipart();
        mimeMultipart.setSubType("alternative");
        mimeMultipart.addBodyPart(txtPart);
        mimeMultipart.addBodyPart(htmlPart);
    }

    if (parts == null || parts.isEmpty()) {
        if (mimeMultipart != null) {
            message.setContent(mimeMultipart);
        } else if (html != null) {
            message.setText(html);
            message.setHeader("Content-type", "text/html");
        } else if (text != null) {
            message.setText(text);
        }
    } else {
        MimeBodyPart bodyPart = new MimeBodyPart();
        if (mimeMultipart != null) {
            bodyPart.setContent(mimeMultipart);
        } else if (html != null) {
            bodyPart.setText(html);
            bodyPart.setHeader("Content-type", "text/html");
        } else if (text != null) {
            bodyPart.setText(text);
        }
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);
        for (Object attachment : parts) {
            if (attachment instanceof FileItem) {
                multipart.addBodyPart(MessageUtils.fileitemToBodypart((FileItem) attachment));
            } else {
                multipart.addBodyPart((BodyPart) attachment);
            }
        }
        message.setContent(multipart);
    }

    message.saveChanges();
    return message;

}

From source file:org.orbeon.oxf.processor.EmailProcessor.java

private void handleBody(PipelineContext pipelineContext, String dataInputSystemId, Part parentPart,
        Element bodyElement) throws Exception {

    // Find out if there are embedded parts
    final Iterator parts = bodyElement.elementIterator("part");
    String multipart;//from  w  w w. j  a  v  a2s  .  com
    if (bodyElement.getName().equals("body")) {
        multipart = bodyElement.attributeValue("mime-multipart");
        if (multipart != null && !parts.hasNext())
            throw new OXFException("mime-multipart attribute on body element requires part children elements");
        // TODO: Check following lines, which were doing nothing!
        //            final String contentTypeFromAttribute = NetUtils.getContentTypeMediaType(bodyElement.attributeValue("content-type"));
        //            if (contentTypeFromAttribute != null && contentTypeFromAttribute.startsWith("multipart/"))
        //                contentTypeFromAttribute.substring("multipart/".length());
        if (parts.hasNext() && multipart == null)
            multipart = DEFAULT_MULTIPART;
    } else {
        final String contentTypeAttribute = NetUtils
                .getContentTypeMediaType(bodyElement.attributeValue("content-type"));
        multipart = (contentTypeAttribute != null && contentTypeAttribute.startsWith("multipart/"))
                ? contentTypeAttribute.substring("multipart/".length())
                : null;
    }

    if (multipart != null) {
        // Multipart content is requested
        final MimeMultipart mimeMultipart = new MimeMultipart(multipart);

        // Iterate through parts
        while (parts.hasNext()) {
            final Element partElement = (Element) parts.next();

            final MimeBodyPart mimeBodyPart = new MimeBodyPart();
            handleBody(pipelineContext, dataInputSystemId, mimeBodyPart, partElement);
            mimeMultipart.addBodyPart(mimeBodyPart);
        }

        // Set content on parent part
        parentPart.setContent(mimeMultipart);
    } else {
        // No multipart, just use the content of the element and add to the current part (which can be the main message)
        handlePart(pipelineContext, dataInputSystemId, parentPart, bodyElement);
    }
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * MimeBodyPart????text/html//from   w w  w . jav  a2s. c o m
 *
 * @return MimeBodyParttext/html?
 * @throws MessagingException
 */
private MimeBodyPart createHtmlPart() throws MessagingException {
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setText(html, charset, "html");
    setHeaderToPart(htmlPart);
    return htmlPart;
}

From source file:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java

private Multipart getMultipartBody(final Session session) throws MessagingException, IOException {

    // if we have a mimeMessage, use it. Otherwise, build one with what we have
    // We can have both a messageHtml and messageText. Build according to it

    MimeMultipart parentMultipart = new MimeMultipart();
    MimeBodyPart htmlBodyPart = null, textBodyPart = null;

    if (getMimeMessage() != null) {

        // Rebuild a MimeMessage and use this one

        final MimeBodyPart original = new MimeBodyPart();
        final MimeMessage originalMimeMessage = new MimeMessage(session, getMimeMessage().getInputStream());
        final MimeMultipart relatedMultipart = (MimeMultipart) originalMimeMessage.getContent();

        parentMultipart = relatedMultipart;

        htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(relatedMultipart);

    }/*from   w w  w.  j  a va  2  s  . c  o  m*/

    // The information we have in the mime-message overrides the getMessageHtml.
    if (getMessageHtml() != null && htmlBodyPart != null) {

        final String content = getInputString(getMessageHtml());

        htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(content, "text/html; charset=" + LocaleHelper.getSystemEncoding());
        final MimeMultipart htmlMultipart = new MimeMultipart();
        htmlMultipart.addBodyPart(htmlBodyPart);

        parentMultipart = htmlMultipart;
    }

    if (getMessagePlain() != null) {

        final String content = getInputString(getMessagePlain());

        textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(content, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
        final MimeMultipart textMultipart = new MimeMultipart();
        textMultipart.addBodyPart(textBodyPart);

        parentMultipart = textMultipart;
    }

    // We have both text and html? Encapsulate it in a multipart/alternative

    if (htmlBodyPart != null && textBodyPart != null) {

        final MimeMultipart alternative = new MimeMultipart("alternative");
        alternative.addBodyPart(textBodyPart);
        alternative.addBodyPart(htmlBodyPart);

        parentMultipart = alternative;

    }

    return parentMultipart;

}

From source file:com.ilopez.jasperemail.JasperEmail.java

public void emailReport(String emailHost, final String emailUser, final String emailPass,
        Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames,
        Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException {

    Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass
            + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport);
    Properties props = new Properties();

    // Setup Email Settings
    props.setProperty("mail.smtp.host", emailHost);
    props.setProperty("mail.smtp.port", smtpport.toString());
    props.setProperty("mail.smtp.auth", smtpauth.toString());

    if (smtpenc == OptionValues.SMTPType.SSL) {
        // SSL settings
        props.put("mail.smtp.socketFactory.port", smtpport.toString());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    } else if (smtpenc == OptionValues.SMTPType.TLS) {
        // TLS Settings
        props.put("mail.smtp.starttls.enable", "true");
    } else {/*from   w w w .ja  v  a  2 s.  c  o  m*/
        // Plain
    }

    // Setup and Apply the Email Authentication

    Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailUser, emailPass);
        }
    });

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");

    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java

private void addAttachment(Multipart multipart, Attachments attachment) throws MessagingException {
    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setFileName(attachment.getName());
    if (StringUtils.isNotBlank(attachment.getDescription())) {
        attachmentPart.setDescription(attachment.getDescription());
    }/*  w w w.j  a  v  a2s  . co m*/
    if (StringUtils.isNotBlank(attachment.getDisposition())) {
        attachmentPart.setDisposition(attachment.getDisposition());
    }
    DataSource source = new ByteArrayDataSource(attachment.getBlob(), attachment.getContentType());
    attachmentPart.setDataHandler(new DataHandler(source));
    multipart.addBodyPart(attachmentPart);
}

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 .jav  a 2s. co 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:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Helper method to create a MimeBodyPart from a binary file.
 *
 * @param pathToFile The complete path to the file - including file name.
 * @param contentType The Mime content type of the file.
 * @param fileName   The name of the file - as it will appear for the mail recipient.
 * @return The resulting MimeBodyPart./*from   w w w  . j a  v  a2s  .  c o  m*/
 * @throws SystemException if the MimeBodyPart can't be created.
 */
public static MimeBodyPart createMimeBodyPartFromBinaryFile(final String pathToFile, final String contentType,
        String fileName) throws SystemException {
    try {
        MimeBodyPart attachmentPart1 = new MimeBodyPart();
        FileDataSource fileDataSource1 = new FileDataSource(pathToFile) {
            @Override
            public String getContentType() {
                return contentType;
            }
        };
        attachmentPart1.setDataHandler(new DataHandler(fileDataSource1));
        attachmentPart1.setFileName(fileName);
        return attachmentPart1;
    } catch (MessagingException e) {
        throw new SystemException("Feil ved generering av MimeBodyPart fra binrfil", e);
    }
}

From source file:com.threewks.thundr.gmail.GmailMailer.java

private MimeMessage createMime(String bodyText, String subject, Map<String, String> to, List<Attachment> pdfs)
        throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage email = new MimeMessage(session);
    Set<InternetAddress> toAddresses = getInternetAddresses(to);

    if (!toAddresses.isEmpty()) {
        email.addRecipients(javax.mail.Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[to.size()]));
    }/*  w w w  .  ja  v  a 2  s  .  c  o m*/

    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/html");
    mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    for (Attachment attachmentPdf : pdfs) {
        MimeBodyPart attachment = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource(attachmentPdf.getData(), "application/pdf");
        attachment.setDataHandler(new DataHandler(source));
        attachment.setFileName(attachmentPdf.getFileName());
        multipart.addBodyPart(mimeBodyPart);
        multipart.addBodyPart(attachment);
    }
    email.setContent(multipart);
    return email;
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Add attachments to a multipart message
 * /*w  w w  .  java2s  .  com*/
 * @param multipart Multipart message
 * @param attachments List of attachments
 */
public MimeBodyPart createAttachmentBodyPart(Attachment attachment, XWikiContext context)
        throws XWikiException, IOException, MessagingException {
    String name = attachment.getFilename();
    byte[] stream = attachment.getContent();
    File temp = File.createTempFile("tmpfile", ".tmp");
    FileOutputStream fos = new FileOutputStream(temp);
    fos.write(stream);
    fos.close();
    DataSource source = new FileDataSource(temp);
    MimeBodyPart part = new MimeBodyPart();
    String mimeType = MimeTypesUtil.getMimeTypeFromFilename(name);

    part.setDataHandler(new DataHandler(source));
    part.setHeader("Content-Type", mimeType);
    part.setFileName(name);
    part.setContentID("<" + name + ">");
    part.setDisposition("inline");

    temp.deleteOnExit();

    return part;
}