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.sakaiproject.kernel.messaging.email.EmailMessageListener.java

public void handleMessage(Message email) throws AddressException, UnsupportedEncodingException,
        SendFailedException, MessagingException, IOException {
    String fromAddress = email.getHeader(Message.Field.FROM);
    if (fromAddress == null) {
        throw new MessagingException("Unable to send without a 'from' address.");
    }/* w w w  .  j  a  v  a  2  s.  c om*/

    // transform to a MimeMessage
    ArrayList<String> invalids = new ArrayList<String>();

    // convert and validate the 'from' address
    InternetAddress from = new InternetAddress(fromAddress, true);

    // convert and validate reply to addresses
    String replyTos = email.getHeader(EmailMessage.Field.REPLY_TO);
    InternetAddress[] replyTo = emails2Internets(replyTos, invalids);

    // convert and validate the 'to' addresses
    String tos = email.getHeader(Message.Field.TO);
    InternetAddress[] to = emails2Internets(tos, invalids);

    // convert and validate 'cc' addresses
    String ccs = email.getHeader(EmailMessage.Field.CC);
    InternetAddress[] cc = emails2Internets(ccs, invalids);

    // convert and validate 'bcc' addresses
    String bccs = email.getHeader(EmailMessage.Field.BCC);
    InternetAddress[] bcc = emails2Internets(bccs, invalids);

    int totalRcpts = to.length + cc.length + bcc.length;
    if (totalRcpts == 0) {
        throw new MessagingException("No recipients to send to.");
    }

    MimeMessage mimeMsg = new MimeMessage(session);
    mimeMsg.setFrom(from);
    mimeMsg.setReplyTo(replyTo);
    mimeMsg.setRecipients(RecipientType.TO, to);
    mimeMsg.setRecipients(RecipientType.CC, cc);
    mimeMsg.setRecipients(RecipientType.BCC, bcc);

    // add in any additional headers
    Map<String, String> headers = email.getHeaders();
    if (headers != null && !headers.isEmpty()) {
        for (Entry<String, String> header : headers.entrySet()) {
            mimeMsg.setHeader(header.getKey(), header.getValue());
        }
    }

    // add the content to the message
    List<Message> parts = email.getParts();
    if (parts == null || parts.size() == 0) {
        setContent(mimeMsg, email);
    } else {
        // create a multipart container
        Multipart multipart = new MimeMultipart();

        // create a body part for the message text
        MimeBodyPart msgBodyPart = new MimeBodyPart();
        setContent(msgBodyPart, email);

        // add the message part to the container
        multipart.addBodyPart(msgBodyPart);

        // add attachments
        for (Message part : parts) {
            addPart(multipart, part);
        }

        // set the multipart container as the content of the message
        mimeMsg.setContent(multipart);
    }

    if (allowTransport) {
        // send
        Transport.send(mimeMsg);
    } else {
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            mimeMsg.writeTo(output);
            String emailString = output.toString();
            LOG.info(emailString);
            observable.notifyObservers(emailString);
        } catch (IOException e) {
            LOG.info("Transport disabled and unable to write message to log: " + e.getMessage(), e);
        }
    }
}

From source file:org.xwiki.mail.internal.factory.html.HTMLMimeBodyPartFactory.java

private MimeBodyPart createHTMLBodyPart(String content, boolean hasAttachments) throws MessagingException {
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(content, TEXT_HTML_CONTENT_TYPE);
    htmlPart.setHeader("Content-Type", TEXT_HTML_CONTENT_TYPE);
    if (hasAttachments) {
        htmlPart.setHeader("Content-Disposition", "inline");
        htmlPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
    }//ww w .ja  va 2 s.  co m
    return htmlPart;
}

From source file:pt.webdetails.cdv.notifications.EmailOutlet.java

private Multipart getMultipartBody(final Session session, final Alert alert)
        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;

    final String content = getMessageBody(alert);

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

    parentMultipart = textMultipart;/*from   w w  w.  ja v  a 2  s  .co  m*/

    // 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:za.co.jumpingbean.alfresco.repo.EmailDocumentsAction.java

public void addAttachments(final Action action, final NodeRef nodeRef, MimeMessage mimeMessage)
        throws MessagingException {
    String text = (String) action.getParameterValue(PARAM_BODY);
    Boolean convertToPDF = (Boolean) action.getParameterValue(PARAM_CONVERT);
    MimeMultipart mail = new MimeMultipart("mixed");
    MimeBodyPart bodyText = new MimeBodyPart();
    bodyText.setText(text);// ww  w  . j a  va2 s  . c om
    mail.addBodyPart(bodyText);

    Queue<NodeRef> que = new LinkedList<>();
    QName type = nodeService.getType(nodeRef);
    if (type.isMatch(ContentModel.TYPE_FOLDER) || type.isMatch(ContentModel.TYPE_CONTAINER)) {
        que.add(nodeRef);
    } else {
        addAttachement(nodeRef, mail, convertToPDF);
    }
    while (!que.isEmpty()) {
        NodeRef tmpNodeRef = que.remove();
        List<ChildAssociationRef> list = nodeService.getChildAssocs(tmpNodeRef);
        for (ChildAssociationRef childRef : list) {
            NodeRef ref = childRef.getChildRef();
            if (nodeService.getType(ref).isMatch(ContentModel.TYPE_CONTENT)) {
                addAttachement(ref, mail, convertToPDF);
            } else {
                que.add(ref);
            }
        }
    }
    mimeMessage.setContent(mail);
}

From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java

private void gereBonLivraisonDansMail(AppockMail appockMail, MimeMessage msg, String contenuFinal)
        throws MessagingException {
    if (appockMail.getBonLivraison() == null) {
        msg.setContent(contenuFinal, "text/html; charset=utf-8");
    } else {/* ww w.jav a  2 s .  com*/
        BonLivraison bonLivraison = appockMail.getBonLivraison();
        Multipart multipart = new MimeMultipart();
        BodyPart attachmentBodyPart = new MimeBodyPart();

        File file = commandeServiceService.getFileBonLivraison(appockMail.getBonLivraison());

        ByteArrayDataSource bds = null;
        try {
            bds = new ByteArrayDataSource(Files.readAllBytes(file.toPath()),
                    bonLivraison.getMimeType().getLibelle());
        } catch (IOException e) {
            e.printStackTrace();
        }

        attachmentBodyPart.setDataHandler(new DataHandler(bds));
        attachmentBodyPart.setFileName(bonLivraison.getNomFichier());
        multipart.addBodyPart(attachmentBodyPart);

        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(contenuFinal, "text/html; charset=utf-8");
        multipart.addBodyPart(htmlBodyPart);
        msg.setContent(multipart);
    }
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Uncompresses message data*/
public byte[] decompressData(AS2MessageInfo info, byte[] data, String contentType) throws Exception {
    MimeBodyPart compressedPart = new MimeBodyPart();
    compressedPart.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    compressedPart.setHeader("content-type", contentType);
    return (this.decompressData(info, new SMIMECompressed(compressedPart), compressedPart.getSize()));
}

From source file:com.email.SendEmailCalInvite.java

/**
 * Builds the calendar invite for the email
 *
 * @param eml EmailOutInvitesModel/*from  w  ww  . j ava  2  s.c  om*/
 * @return BodyPart (calendar invite)
 */
private static BodyPart responseDueCalObject(EmailOutInvitesModel eml, SystemEmailModel account) {
    BodyPart calendarPart = new MimeBodyPart();
    try {
        String calendarContent = "BEGIN:VCALENDAR\n" + "METHOD:REQUEST\n" + "PRODID: BCP - Meeting\n"
                + "VERSION:2.0\n" + "BEGIN:VEVENT\n" + "DTSTAMP:"
                + Global.getiCalendarDateFormat().format(eml.getHearingStartTime()) + "\n" + "DTSTART:"
                + Global.getiCalendarDateFormat().format(eml.getHearingStartTime()) + "\n" + "DTEND:"
                + Global.getiCalendarDateFormat().format(eml.getHearingEndTime()) + "\n"
                //Subject
                + "SUMMARY: " + "ResponseDue" + "\n" + "UID:"
                + Global.getiCalendarDateFormat().format(eml.getHearingStartTime())
                + Global.getiCalendarDateFormat().format(eml.getHearingEndTime()) + "\n"
                //return email
                + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:"
                + new InternetAddress(account.getEmailAddress()).getAddress() + "\n"
                //return email
                + "ORGANIZER:MAILTO:" + new InternetAddress(account.getEmailAddress()).getAddress() + "\n"
                //hearing room
                + "LOCATION: " + "\n"
                //subject
                + "DESCRIPTION: " + "\n" + "SEQUENCE:0\n" + "PRIORITY:5\n" + "CLASS:PUBLIC\n"
                + "STATUS:CONFIRMED\n" + "TRANSP:OPAQUE\n" + "BEGIN:VALARM\n" + "ACTION:DISPLAY\n"
                + "DESCRIPTION:REMINDER\n" + "TRIGGER;RELATED=START:-PT00H15M00S\n" + "END:VALARM\n"
                + "END:VEVENT\n" + "END:VCALENDAR";
        calendarPart.addHeader("Content-Class", "urn:content-classes:calendarmessage");
        calendarPart.setContent(calendarContent, "text/calendar;method=CANCEL");
    } catch (MessagingException ex) {
        ExceptionHandler.Handle(ex);
    }
    return calendarPart;
}

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource imageds, String image, DataSource audiods,
        String audio) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();//from  w w  w .  j a v  a 2  s .  c om
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(imageds));
    messageBodyPart.setFileName(image);
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(audiods));
    messageBodyPart.setFileName(audio);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);

}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testValidateMessageShouldFail() throws Exception {
    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    MimeBodyPart emptyPart = new MimeBodyPart();

    message.setContent(emptyPart, "text/plain");

    message.saveChanges();/*from  w ww  . j  a v  a  2s  . com*/

    try {
        MailUtils.validateMessage(message);

        fail();
    } catch (IOException e) {
        // expected. The message should be corrupt
    }
}

From source file:com.cosmicpush.plugins.smtp.EmailMessage.java

/**
 * @param session the applications current session.
 * @throws EmailMessageException in response to any other type of exception.
 *///from ww  w .j a v  a2s . co  m
@SuppressWarnings({ "ConstantConditions" })
protected void send(Session session) throws EmailMessageException {
    try {

        // create a message
        MimeMessage msg = new MimeMessage(session);

        //set some of the basic attributes.
        msg.setFrom(fromAddress);
        msg.setRecipients(Message.RecipientType.TO, ReflectUtils.toArray(InternetAddress.class, toAddresses));
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        if (replyToAddress.isEmpty() == false) {
            msg.setReplyTo(ReflectUtils.toArray(InternetAddress.class, replyToAddress));
        }

        // create the Multipart and add set it as the content of the message
        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // create and fill the HTML part of the messgae if it exists
        if (html != null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(html, "UTF-8", "html");
            multipart.addBodyPart(bodyPart);
        }

        // create and fill the text part of the messgae if it exists
        if (text != null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(text, "UTF-8", "plain");
            multipart.addBodyPart(bodyPart);
        }

        if (html == null && text == null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText("", "UTF-8", "plain");
            multipart.addBodyPart(bodyPart);
        }

        // remove any nulls from the list of attachments.
        while (attachments.remove(null)) {
            /* keep going */ }

        // Attach any files that we have, making sure that they exist first
        for (File file : attachments) {
            if (file.exists() == false) {
                throw new EmailMessageException("The file \"" + file.getAbsolutePath() + "\" does not exist.");
            } else {
                MimeBodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.attachFile(file);
                multipart.addBodyPart(attachmentPart);
            }
        }

        // send the message
        Transport.send(msg);

    } catch (EmailMessageException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new EmailMessageException("Exception sending email\n" + toString(), ex);
    }
}