Example usage for javax.mail.internet MimePart setHeader

List of usage examples for javax.mail.internet MimePart setHeader

Introduction

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

Prototype

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

Source Link

Document

Set the value for this header_name.

Usage

From source file:com.zimbra.cs.service.FeedManager.java

private static ParsedMessage generateMessage(String title, String content, String ctype, InternetAddress addr,
        Date date, List<Enclosure> attach) throws ServiceException {
    // cull out invalid enclosures
    if (attach != null) {
        for (Iterator<Enclosure> it = attach.iterator(); it.hasNext();) {
            if (it.next().getLocation() == null) {
                it.remove();//  w  w w  .j a  va  2 s . c  o  m
            }
        }
    }
    boolean hasAttachments = attach != null && !attach.isEmpty();

    // clean up whitespace in the title
    if (title != null) {
        title = title.replaceAll("\\s+", " ");
    }

    // create the MIME message and wrap it
    try {
        MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
        MimePart body = hasAttachments ? new ZMimeBodyPart() : (MimePart) mm;
        body.setText(content, "utf-8");
        body.setHeader("Content-Type", ctype);

        if (hasAttachments) {
            // encode each enclosure as an attachment with Content-Location set
            MimeMultipart mmp = new ZMimeMultipart("mixed");
            mmp.addBodyPart((BodyPart) body);
            for (Enclosure enc : attach) {
                MimeBodyPart part = new ZMimeBodyPart();
                part.setText("");
                part.addHeader("Content-Location", enc.getLocation());
                part.addHeader("Content-Type", enc.getContentType());
                if (enc.getDescription() != null) {
                    part.addHeader("Content-Description", enc.getDescription());
                }
                part.addHeader("Content-Disposition", "attachment");
                mmp.addBodyPart(part);
            }
            mm.setContent(mmp);
        }

        mm.setSentDate(date);
        mm.addFrom(new InternetAddress[] { addr });
        mm.setSubject(title, "utf-8");
        // more stuff here!
        mm.saveChanges();
        return new ParsedMessage(mm, date.getTime(), false);
    } catch (MessagingException e) {
        throw ServiceException.PARSE_ERROR("error wrapping feed item in MimeMessage", e);
    }
}

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

/**
 * Converts any 8bit encoded parts to 7bit. Returns true if a part (or all parts) were converted from
 * 8bit to 7bit.//  w w w. java  2 s  . c  o m
 * 
 * @param part
 * @throws MessagingException
 */
public static boolean convertTo7Bit(MimePart part) throws MessagingException, IOException {
    boolean converted = false;

    if (part.isMimeType("multipart/*")) {
        Multipart parts = (Multipart) part.getContent();

        int count = parts.getCount();

        for (int i = 0; i < count; i++) {
            boolean partConverted = convertTo7Bit((MimePart) parts.getBodyPart(i));

            if (partConverted) {
                converted = true;
            }
        }
    } else if ("8bit".equalsIgnoreCase(part.getEncoding())) {
        String encoding = part.isMimeType("text/*") ? "quoted-printable" : "base64";

        /*
         * We need to use a ByteArrayDataSource to make sure it will always be encoded
         */
        part.setDataHandler(
                new DataHandler(new ByteArrayDataSource(part.getInputStream(), part.getContentType())));

        part.setHeader("Content-Transfer-Encoding", encoding);
        part.addHeader("X-MIME-Autoconverted", "from 8bit to " + encoding + " by Djigzo");

        converted = true;
    }

    return converted;
}

From source file:lucee.runtime.net.smtp.SMTPClient.java

private void fillHTMLText(MimePart mp) throws MessagingException {
    mp.setDataHandler(new DataHandler(new StringDataSource(htmlText, TEXT_HTML, htmlTextCharset, 76)));
    //mp.setHeader("Content-Transfer-Encoding", "7bit");
    mp.setHeader("Content-Type", TEXT_HTML + "; charset=" + htmlTextCharset);
}

From source file:lucee.runtime.net.smtp.SMTPClient.java

private void fillPlainText(MimePart mp) throws MessagingException {
    mp.setDataHandler(new DataHandler(new StringDataSource(plainText, TEXT_PLAIN, plainTextCharset, 980)));
    //mp.setHeader("Content-Transfer-Encoding", "7bit");
    mp.setHeader("Content-Type", TEXT_PLAIN + "; charset=" + plainTextCharset);
}

From source file:org.apache.axis2.transport.mail.MailTransportSender.java

/**
 * Populate email with a SOAP formatted message
 * @param outInfo the out transport information holder
 * @param msgContext the message context that holds the message to be written
 * @throws AxisFault on error//w  w w .  j  a v a 2s  .  co m
 * @return id of the send mail message
 */
private String sendMail(MailOutTransportInfo outInfo, MessageContext msgContext)
        throws AxisFault, MessagingException, IOException {

    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    // Make sure that non textual attachements are sent with base64 transfer encoding
    // instead of binary.
    format.setProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS, true);

    MessageFormatter messageFormatter = BaseUtils.getMessageFormatter(msgContext);

    if (log.isDebugEnabled()) {
        log.debug(
                "Creating MIME message using message formatter " + messageFormatter.getClass().getSimpleName());
    }

    WSMimeMessage message = null;
    if (outInfo.getFromAddress() != null) {
        message = new WSMimeMessage(session, outInfo.getFromAddress().getAddress());
    } else {
        message = new WSMimeMessage(session, "");
    }

    Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (log.isDebugEnabled() && trpHeaders != null) {
        log.debug("Using transport headers: " + trpHeaders);
    }

    // set From address - first check if this is a reply, then use from address from the
    // transport out, else if any custom transport headers set on this message, or default
    // to the transport senders default From address        
    if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting From header to " + outInfo.getFromAddress().getAddress()
                    + " from OutTransportInfo");
        }
        message.setFrom(outInfo.getFromAddress());
        message.setReplyTo((new Address[] { outInfo.getFromAddress() }));
    } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) {
        InternetAddress from = new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM));
        if (log.isDebugEnabled()) {
            log.debug("Setting From header to " + from.getAddress() + " from transport headers");
        }
        message.setFrom(from);
        message.setReplyTo(new Address[] { from });
    } else {
        if (smtpFromAddress != null) {
            if (log.isDebugEnabled()) {
                log.debug("Setting From header to " + smtpFromAddress.getAddress()
                        + " from transport configuration");
            }
            message.setFrom(smtpFromAddress);
            message.setReplyTo(new Address[] { smtpFromAddress });
        } else {
            handleException("From address for outgoing message cannot be determined");
        }
    }

    // set To address/es to any custom transport header set on the message, else use the reply
    // address from the out transport information
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) {
        Address[] to = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO));
        if (log.isDebugEnabled()) {
            log.debug("Setting To header to " + InternetAddress.toString(to) + " from transport headers");
        }
        message.setRecipients(Message.RecipientType.TO, to);
    } else if (outInfo.getTargetAddresses() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting To header to " + InternetAddress.toString(outInfo.getTargetAddresses())
                    + " from OutTransportInfo");
        }
        message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses());
    } else {
        handleException("To address for outgoing message cannot be determined");
    }

    // set Cc address/es to any custom transport header set on the message, else use the
    // Cc list from original request message
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) {
        Address[] cc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC));
        if (log.isDebugEnabled()) {
            log.debug("Setting Cc header to " + InternetAddress.toString(cc) + " from transport headers");
        }
        message.setRecipients(Message.RecipientType.CC, cc);
    } else if (outInfo.getCcAddresses() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Cc header to " + InternetAddress.toString(outInfo.getCcAddresses())
                    + " from OutTransportInfo");
        }
        message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses());
    }

    // set Bcc address/es to any custom addresses set at the transport sender level + any
    // custom transport header
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) {
        InternetAddress[] bcc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC));
        if (log.isDebugEnabled()) {
            log.debug("Adding Bcc header values " + InternetAddress.toString(bcc) + " from transport headers");
        }
        message.addRecipients(Message.RecipientType.BCC, bcc);
    }
    if (smtpBccAddresses != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding Bcc header values " + InternetAddress.toString(smtpBccAddresses)
                    + " from transport configuration");
        }
        message.addRecipients(Message.RecipientType.BCC, smtpBccAddresses);
    }

    // set subject
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Subject header to '" + trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)
                    + "' from transport headers");
        }
        message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT));
    } else if (outInfo.getSubject() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Subject header to '" + outInfo.getSubject() + "' from transport headers");
        }
        message.setSubject(outInfo.getSubject());
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Generating default Subject header from SOAP action");
        }
        message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction());
    }

    //TODO: use a combined message id for smtp so that it generates a unique id while
    // being able to support asynchronous communication.
    // if a custom message id is set, use it
    //        if (msgContext.getMessageID() != null) {
    //            message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID());
    //            message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID());
    //        }

    // if this is a reply, set reference to original message
    if (outInfo.getRequestMessageID() != null) {
        message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID());
        message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID());

    } else {
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) {
            message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO));
        }
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) {
            message.setHeader(MailConstants.MAIL_HEADER_REFERENCES,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES));
        }
    }

    // set Date
    message.setSentDate(new Date());

    // set SOAPAction header
    message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());

    // write body
    MessageFormatterEx messageFormatterEx;
    if (messageFormatter instanceof MessageFormatterEx) {
        messageFormatterEx = (MessageFormatterEx) messageFormatter;
    } else {
        messageFormatterEx = new MessageFormatterExAdapter(messageFormatter);
    }

    DataHandler dataHandler = new DataHandler(
            messageFormatterEx.getDataSource(msgContext, format, msgContext.getSoapAction()));

    MimeMultipart mimeMultiPart = null;

    String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT);
    if (mFormat == null) {
        mFormat = defaultMailFormat;
    }

    if (log.isDebugEnabled()) {
        log.debug("Using mail format '" + mFormat + "'");
    }

    MimePart mainPart;
    if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) {
        mimeMultiPart = new MimeMultipart();
        MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
        mimeBodyPart1.setContent("Web Service Message Attached", "text/plain");
        MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
        mimeMultiPart.addBodyPart(mimeBodyPart1);
        mimeMultiPart.addBodyPart(mimeBodyPart2);
        message.setContent(mimeMultiPart);
        mainPart = mimeBodyPart2;
    } else if (MailConstants.TRANSPORT_FORMAT_ATTACHMENT.equals(mFormat)) {
        mimeMultiPart = new MimeMultipart();
        MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
        mimeBodyPart1.setContent("Web Service Message Attached", "text/plain");
        MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
        mimeMultiPart.addBodyPart(mimeBodyPart1);
        mimeMultiPart.addBodyPart(mimeBodyPart2);
        message.setContent(mimeMultiPart);

        String fileName = (String) msgContext.getProperty(MailConstants.TRANSPORT_FORMAT_ATTACHMENT_FILE);
        if (fileName != null) {
            mimeBodyPart2.setFileName(fileName);
        } else {
            mimeBodyPart2.setFileName("attachment");
        }

        mainPart = mimeBodyPart2;
    } else {
        mainPart = message;
    }

    try {
        mainPart.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());
        mainPart.setDataHandler(dataHandler);

        // AXIOM's idea of what is textual also includes application/xml and
        // application/soap+xml (which JavaMail considers as binary). For these content types
        // always use quoted-printable transfer encoding. Note that JavaMail is a bit smarter
        // here because it can choose between 7bit and quoted-printable automatically, but it
        // needs to scan the entire content to determine this.
        if (msgContext.getOptions().getProperty("Content-Transfer-Encoding") != null) {
            mainPart.setHeader("Content-Transfer-Encoding",
                    (String) msgContext.getOptions().getProperty("Content-Transfer-Encoding"));
        } else {
            String contentType = dataHandler.getContentType().toLowerCase();
            if (!contentType.startsWith("multipart/") && CommonUtils.isTextualPart(contentType)) {
                mainPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
            }
        }

        //setting any custom headers defined by the user
        if (msgContext.getOptions().getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS) != null) {
            Map customTransportHeaders = (Map) msgContext.getOptions()
                    .getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS);
            for (Object header : customTransportHeaders.keySet()) {
                mainPart.setHeader((String) header, (String) customTransportHeaders.get(header));
            }
        }

        log.debug("Sending message");
        Transport.send(message);

        // update metrics
        metrics.incrementMessagesSent(msgContext);
        long bytesSent = message.getBytesSent();
        if (bytesSent != -1) {
            metrics.incrementBytesSent(msgContext, bytesSent);
        }

    } catch (MessagingException e) {
        metrics.incrementFaultsSending();
        handleException("Error creating mail message or sending it to the configured server", e);

    }
    return message.getMessageID();
}