Example usage for javax.mail BodyPart addHeader

List of usage examples for javax.mail BodyPart addHeader

Introduction

In this page you can find the example usage for javax.mail BodyPart addHeader.

Prototype

public void addHeader(String header_name, String header_value) throws MessagingException;

Source Link

Document

Add this value to the existing values for this header_name.

Usage

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Send a calendar message./*from  w  ww .  ja  v a 2 s.c o  m*/
 * @param strRecipientsTo The list of the main recipients email. Every
 *            recipient must be separated by the mail separator defined in
 *            config.properties
 * @param strRecipientsCc The recipients list of the carbon copies .
 * @param strRecipientsBcc The recipients list of the blind carbon copies .
 * @param strSenderName The sender name.
 * @param strSenderEmail The sender email address.
 * @param strSubject The message subject.
 * @param strMessage The HTML message.
 * @param strCalendarMessage The calendar message.
 * @param bCreateEvent True to create the event, false to remove it
 * @param transport the smtp transport object
 * @param session the smtp session object
 * @throws AddressException If invalid address
 * @throws SendFailedException If an error occurred during sending
 * @throws MessagingException If a messaging error occurred
 */
protected static void sendMessageCalendar(String strRecipientsTo, String strRecipientsCc,
        String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject,
        String strMessage, String strCalendarMessage, boolean bCreateEvent, Transport transport,
        Session session) throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);
    msg.setHeader(HEADER_NAME, HEADER_VALUE);

    MimeMultipart multipart = new MimeMultipart();
    BodyPart msgBodyPart = new MimeBodyPart();
    msgBodyPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));

    multipart.addBodyPart(msgBodyPart);

    BodyPart calendarBodyPart = new MimeBodyPart();
    //        calendarBodyPart.addHeader( "Content-Class", "urn:content-classes:calendarmessage" );
    calendarBodyPart.setContent(strCalendarMessage,
            AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_CALENDAR)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET)
                    + AppPropertiesService.getProperty(PROPERTY_CALENDAR_SEPARATOR)
                    + AppPropertiesService.getProperty(
                            bCreateEvent ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL));
    calendarBodyPart.addHeader(HEADER_NAME, CONSTANT_BASE64);
    multipart.addBodyPart(calendarBodyPart);

    msg.setContent(multipart);

    sendMessage(msg, transport);
}

From source file:com.email.SendEmailCalInvite.java

/**
 * Builds the calendar invite for the email
 *
 * @param eml EmailOutInvitesModel//from  w w w  .  j a  v  a  2s  .c o  m
 * @return BodyPart (calendar invite)
 */
private static BodyPart inviteCalObject(EmailOutInvitesModel eml, SystemEmailModel account,
        String emailSubject) {
    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:" + emailSubject.replace("Upcoming", "").trim() + "\n" + "UID:"
                + Calendar.getInstance().get(Calendar.MILLISECOND) + "\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: " + eml.getHearingRoomAbv() + "\n"
                //subject
                + "DESCRIPTION: " + emailSubject + "\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.email.SendEmailCalInvite.java

/**
 * Builds the calendar invite for the email
 *
 * @param eml EmailOutInvitesModel/*from ww w.j  a  v a  2  s.c o  m*/
 * @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:org.apache.axis2.transport.mail.EMailSender.java

private void createMailMimeMessage(final MimeMessage msg, MailToInfo mailToInfo, OMOutputFormat format)
        throws MessagingException {

    // Create the message part
    BodyPart messageBodyPart = new MimeBase64BodyPart();
    messageBodyPart.setText("");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    DataSource source = null;/*www  .  j  a  v a 2s  .  c  o  m*/

    // Part two is attachment
    if (outputStream instanceof ByteArrayOutputStream) {
        source = new ByteArrayDataSource(((ByteArrayOutputStream) outputStream).toByteArray());
    }
    messageBodyPart = new MimeBase64BodyPart();
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setDisposition(Part.ATTACHMENT);

    messageBodyPart.addHeader("Content-Description", "\"" + mailToInfo.getContentDescription() + "\"");

    String contentType = format.getContentType() != null ? format.getContentType()
            : Constants.DEFAULT_CONTENT_TYPE;
    if (contentType.indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) > -1) {
        if (messageContext.getSoapAction() != null) {
            messageBodyPart.setHeader(Constants.HEADER_SOAP_ACTION, messageContext.getSoapAction());
        }
    }

    if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) {
        if (messageContext.getSoapAction() != null) {
            messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding()
                    + " ; action=\"" + messageContext.getSoapAction() + "\"");
        }
    } else {
        messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding());
    }

    multipart.addBodyPart(messageBodyPart);
    msg.setContent(multipart);

}

From source file:org.apache.camel.component.mail.MailBinding.java

protected void addAttachmentsToMultipart(MimeMultipart multipart, String partDisposition, Exchange exchange)
        throws MessagingException {
    LOG.trace("Adding attachments +++ start +++");
    int i = 0;/*from w  w  w  .ja  va  2  s  . c  o m*/
    for (Map.Entry<String, DataHandler> entry : exchange.getIn().getAttachments().entrySet()) {
        String attachmentFilename = entry.getKey();
        DataHandler handler = entry.getValue();

        if (LOG.isTraceEnabled()) {
            LOG.trace("Attachment #" + i + ": Disposition: " + partDisposition);
            LOG.trace("Attachment #" + i + ": DataHandler: " + handler);
            LOG.trace("Attachment #" + i + ": FileName: " + attachmentFilename);
        }
        if (handler != null) {
            if (shouldAddAttachment(exchange, attachmentFilename, handler)) {
                // Create another body part
                BodyPart messageBodyPart = new MimeBodyPart();
                // Set the data handler to the attachment
                messageBodyPart.setDataHandler(handler);

                if (attachmentFilename.toLowerCase().startsWith("cid:")) {
                    // add a Content-ID header to the attachment
                    // must use angle brackets according to RFC: http://www.ietf.org/rfc/rfc2392.txt
                    messageBodyPart.addHeader("Content-ID", "<" + attachmentFilename.substring(4) + ">");
                    // Set the filename without the cid
                    messageBodyPart.setFileName(attachmentFilename.substring(4));
                } else {
                    // Set the filename
                    messageBodyPart.setFileName(attachmentFilename);
                }

                LOG.trace("Attachment #" + i + ": ContentType: " + messageBodyPart.getContentType());

                if (contentTypeResolver != null) {
                    String contentType = contentTypeResolver.resolveContentType(attachmentFilename);
                    LOG.trace("Attachment #" + i + ": Using content type resolver: " + contentTypeResolver
                            + " resolved content type as: " + contentType);
                    if (contentType != null) {
                        String value = contentType + "; name=" + attachmentFilename;
                        messageBodyPart.setHeader("Content-Type", value);
                        LOG.trace("Attachment #" + i + ": ContentType: " + messageBodyPart.getContentType());
                    }
                }

                // Set Disposition
                messageBodyPart.setDisposition(partDisposition);
                // Add part to multipart
                multipart.addBodyPart(messageBodyPart);
            } else {
                LOG.trace("shouldAddAttachment: false");
            }
        } else {
            LOG.warn("Cannot add attachment: " + attachmentFilename + " as DataHandler is null");
        }
        i++;
    }
    LOG.trace("Adding attachments +++ done +++");
}

From source file:org.apache.hupa.server.utils.TestUtils.java

/**
 * Add a mock attachment to a mime message, you can specify whether the attachment
 * is an in-line image, and the file name
 *
 * @param message//from  w  w w .  j ava 2s .com
 * @param fileName
 * @param isInline
 * @throws IOException
 * @throws MessagingException
 */
public static void addMockAttachment(Message message, String fileName, boolean isInline)
        throws IOException, MessagingException {
    FileItem item = createMockFileItem(fileName, isInline ? "image/mock" : "mock/attachment");

    BodyPart part = MessageUtils.fileitemToBodypart(item);
    if (isInline)
        part.addHeader("Content-ID", "any-id");

    Multipart mpart = (Multipart) message.getContent();
    mpart.addBodyPart(part);
    message.saveChanges();
}

From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java

public void marshal(ShsMessage shsMessage, OutputStream outputStream) throws IllegalMessageStructureException {
    log.trace("marshal(ShsMessage, OutputStream)");

    MimeMultipart multipart = new MimeMultipart();
    BodyPart bodyPart = new MimeBodyPart();

    try {//from   w ww . j  a v a2  s  .com

        ShsLabel label = shsMessage.getLabel();
        if (label == null) {
            throw new IllegalMessageStructureException("label not found in shs message");
        }

        Content content = label.getContent();
        if (content == null) {
            throw new IllegalMessageStructureException("label/content not found in shs label");
        } else {
            // we will update this according to our data parts below.
            content.getDataOrCompound().clear();

            String contentId = content.getContentId();
            content.setContentId(contentId.substring(0, Math.min(contentId.length(), MAX_LENGTH_CONTENT_ID)));
        }

        List<DataPart> dataParts = shsMessage.getDataParts();

        if (dataParts.isEmpty()) {
            throw new IllegalMessageStructureException("dataparts not found in message");
        }

        for (DataPart dp : dataParts) {
            Data data = new Data();

            data.setDatapartType(dp.getDataPartType());
            data.setFilename(dp.getFileName());
            if (dp.getContentLength() != null && dp.getContentLength() > 0)
                data.setNoOfBytes("" + dp.getContentLength());
            content.getDataOrCompound().add(data);
        }

        bodyPart.setContent(shsLabelMarshaller.marshal(label), "text/xml; charset=ISO-8859-1");
        bodyPart.setHeader("Content-Transfer-Encoding", "binary");

        multipart.addBodyPart(bodyPart);

        for (DataPart dataPart : dataParts) {

            bodyPart = new MimeBodyPart();

            bodyPart.setDisposition(Part.ATTACHMENT);
            if (StringUtils.isNotBlank(dataPart.getFileName())) {
                bodyPart.setFileName(dataPart.getFileName());
            }

            bodyPart.setDataHandler(dataPart.getDataHandler());

            if (dataPart.getTransferEncoding() != null) {
                bodyPart.addHeader("Content-Transfer-Encoding", dataPart.getTransferEncoding().toLowerCase());
            }
            multipart.addBodyPart(bodyPart);
        }

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject("SHS Message");
        mimeMessage.addHeader("Content-Transfer-Encoding", "binary");

        mimeMessage.setContent(multipart);
        mimeMessage.saveChanges();

        String ignoreList[] = { "Message-ID" };

        mimeMessage.writeTo(outputStream, ignoreList);
        outputStream.flush();

    } catch (Exception e) {
        if (e instanceof IllegalMessageStructureException) {
            throw (IllegalMessageStructureException) e;
        }
        throw new IllegalMessageStructureException(e);
    }

}

From source file:servlets.mailPDF.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//  w  ww .  ja  v  a 2  s.  c  om
        System.out.println("Reached @ mailPDF_Bronze.");

        String pdfBase64 = request.getParameter("pdfBase64");
        String reportdate = request.getParameter("reportdate");
        String emailaddresses = request.getParameter("emailList");
        String emailMessage = request.getParameter("emailMessage");
        String filename = request.getParameter("filename");

        List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*"));

        System.out.println("pdfBase54 is --------------\n" + pdfBase64 + "\n-----------------End");
        System.out.println(reportdate);
        System.out.println(emailaddresses);

        byte[] decodedBytes = decode(pdfBase64.substring(28));
        MultiPartEmail email = new MultiPartEmail();
        email.setSmtpPort(587);
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setAuthentication("reporting@groupnp.com", "D3sign2015");
        email.setTLS(true);

        for (String emailAddress : emailList) {

            email.addTo(emailAddress);
        }
        if (filename.equals("LNIndia Tracker (Gold - Weekly)")) {

            email.setFrom("reporting@groupnp.com");
            email.setSubject(filename + " (" + reportdate + ")");

            MimeMultipart part1 = new MimeMultipart();
            BodyPart messageBodyPart1 = new MimeBodyPart();
            messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
            part1.addBodyPart(messageBodyPart1);
            email.addPart(part1);

            MimeMultipart part2 = new MimeMultipart();
            BodyPart messageBodyPart2 = new MimeBodyPart();
            messageBodyPart2
                    .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
            messageBodyPart2.removeHeader("Content-Transfer-Encoding");
            messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
            messageBodyPart2.setFileName(filename + " " + reportdate + ".pdf");
            part2.addBodyPart(messageBodyPart2);
            email.addPart(part2);

            email.send();

        } else if (filename.equals("LNIndia Tracker (Gold - Monthly)")) {

            email.setFrom("reporting@groupnp.com");
            email.setSubject(filename + " (" + reportdate + ")");

            MimeMultipart part1 = new MimeMultipart();
            BodyPart messageBodyPart1 = new MimeBodyPart();
            messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
            part1.addBodyPart(messageBodyPart1);
            email.addPart(part1);

            MimeMultipart part2 = new MimeMultipart();
            BodyPart messageBodyPart2 = new MimeBodyPart();
            messageBodyPart2
                    .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
            messageBodyPart2.removeHeader("Content-Transfer-Encoding");
            messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
            messageBodyPart2.setFileName(filename + " " + reportdate + ".pdf");
            part2.addBodyPart(messageBodyPart2);
            email.addPart(part2);

            email.send();

        }

    } catch (EmailException | MessagingException ex) {
        Logger.getLogger(mailPDF.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:servlets.mailPDF_Bronze.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from  www  .jav  a2  s  . c  om
        System.out.println("Reached @ mailPDF_Bronze.");

        String pdfBase64 = request.getParameter("pdfBase64");
        String reportdate = request.getParameter("reportdate");
        String emailaddresses = request.getParameter("emailList");
        String emailMessage = request.getParameter("emailMessage");

        List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*"));

        System.out.println("pdfBase54 is --------------\n" + pdfBase64 + "\n-----------------End");
        System.out.println(reportdate);
        System.out.println(emailaddresses);

        byte[] decodedBytes = decode(pdfBase64.substring(28));
        MultiPartEmail email = new MultiPartEmail();
        email.setSmtpPort(587);
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setAuthentication("reporting@groupnp.com", "D3sign2015");
        email.setTLS(true);

        for (String emailAddress : emailList) {

            email.addTo(emailAddress);
        }

        email.setFrom("reporting@groupnp.com");
        email.setSubject("LexisNexis Risk India Tracker (" + reportdate + ")");

        MimeMultipart part1 = new MimeMultipart();
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
        part1.addBodyPart(messageBodyPart1);
        email.addPart(part1);

        MimeMultipart part2 = new MimeMultipart();
        BodyPart messageBodyPart2 = new MimeBodyPart();
        messageBodyPart2
                .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
        messageBodyPart2.removeHeader("Content-Transfer-Encoding");
        messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
        messageBodyPart2.setFileName("LNIndiaTracker_" + reportdate + ".pdf");
        part2.addBodyPart(messageBodyPart2);
        email.addPart(part2);

        email.send();

    } catch (EmailException | MessagingException ex) {
        Logger.getLogger(mailPDF_Bronze.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:servlets.mailPDF_Bronze_ACS.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from  w ww  .  j  a  v  a  2 s  .c o  m*/
        System.out.println("Reached @ mailPDF_Bronze.");

        String pdfBase64 = request.getParameter("pdfBase64");
        String reportdate = request.getParameter("reportdate");
        String emailaddresses = request.getParameter("emailList");
        String emailMessage = request.getParameter("emailMessage");

        List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*"));

        System.out.println("pdfBase54 is --------------\n" + pdfBase64 + "\n-----------------End");
        System.out.println(reportdate);
        System.out.println(emailaddresses);

        byte[] decodedBytes = decode(pdfBase64.substring(28));
        MultiPartEmail email = new MultiPartEmail();
        email.setSmtpPort(587);
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setAuthentication("reporting@groupnp.com", "D3sign2015");
        email.setTLS(true);

        for (String emailAddress : emailList) {

            email.addTo(emailAddress);
        }

        email.setFrom("reporting@groupnp.com");
        email.setSubject("ACS Tracker (" + reportdate + ")");

        MimeMultipart part1 = new MimeMultipart();
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
        part1.addBodyPart(messageBodyPart1);
        email.addPart(part1);

        MimeMultipart part2 = new MimeMultipart();
        BodyPart messageBodyPart2 = new MimeBodyPart();
        messageBodyPart2
                .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
        messageBodyPart2.removeHeader("Content-Transfer-Encoding");
        messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
        messageBodyPart2.setFileName("ACSTracker_" + reportdate + ".pdf");
        part2.addBodyPart(messageBodyPart2);
        email.addPart(part2);

        email.send();

    } catch (EmailException | MessagingException ex) {
        Logger.getLogger(mailPDF_Bronze_ACS.class.getName()).log(Level.SEVERE, null, ex);
    }

}