List of usage examples for javax.mail.internet MimeBodyPart setHeader
@Override public void setHeader(String name, String value) throws MessagingException
From source file:no.kantega.publishing.modules.mailsender.MailSender.java
/** * Helper method to create a MimeBodyPart from a string. * * @param content The string to insert into the MimeBodyPart. * @return The resulting MimeBodyPart.//w w w. j ava 2s.c om * @throws SystemException if the MimeBodyPart can't be created. */ public static MimeBodyPart createMimeBodyPartFromStringMessage(String content) throws SystemException { try { MimeBodyPart bp = new MimeBodyPart(); if (content.toLowerCase().contains("<html>")) { log.debug("Set content as text/html"); bp.setContent(content, "text/html; charset=iso-8859-1"); } else { log.debug("Set content as text/plain"); bp.setText(content, "ISO-8859-1"); bp.setHeader("Content-Transfer-Encoding", "quoted-printable"); } return bp; } catch (MessagingException e) { throw new SystemException("Feil ved generering av MimeBodyPart fra string", e); } }
From source file:org.apache.axis.attachments.MimeUtils.java
/** * This routine will create a multipart object from the parts and the SOAP content. * @param env should be the text for the main root part. * @param parts contain a collection of the message parts. * * @return a new MimeMultipart object//from w w w . j ava2 s . c o m * * @throws org.apache.axis.AxisFault */ public static javax.mail.internet.MimeMultipart createMP(String env, java.util.Collection parts, int sendType) throws org.apache.axis.AxisFault { javax.mail.internet.MimeMultipart multipart = null; try { String rootCID = SessionUtils.generateSessionId(); if (sendType == Attachments.SEND_TYPE_MTOM) { multipart = new javax.mail.internet.MimeMultipart("related;type=\"application/xop+xml\"; start=\"<" + rootCID + ">\"; start-info=\"text/xml; charset=utf-8\""); } else { multipart = new javax.mail.internet.MimeMultipart( "related; type=\"text/xml\"; start=\"<" + rootCID + ">\""); } javax.mail.internet.MimeBodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart(); messageBodyPart.setText(env, "UTF-8"); if (sendType == Attachments.SEND_TYPE_MTOM) { messageBodyPart.setHeader("Content-Type", "application/xop+xml; charset=utf-8; type=\"text/xml; charset=utf-8\""); } else { messageBodyPart.setHeader("Content-Type", "text/xml; charset=UTF-8"); } messageBodyPart.setHeader("Content-Id", "<" + rootCID + ">"); messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, "binary"); multipart.addBodyPart(messageBodyPart); for (java.util.Iterator it = parts.iterator(); it.hasNext();) { org.apache.axis.Part part = (org.apache.axis.Part) it.next(); javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils .getActivationDataHandler(part); String contentID = part.getContentId(); messageBodyPart = new javax.mail.internet.MimeBodyPart(); messageBodyPart.setDataHandler(dh); String contentType = part.getContentType(); if ((contentType == null) || (contentType.trim().length() == 0)) { contentType = dh.getContentType(); } if ((contentType == null) || (contentType.trim().length() == 0)) { contentType = "application/octet-stream"; } messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, contentType); messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_ID, "<" + contentID + ">"); messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, "binary"); // Safe and fastest for anything other than mail; for (java.util.Iterator i = part.getNonMatchingMimeHeaders( new String[] { HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.HEADER_CONTENT_ID, HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING }); i.hasNext();) { javax.xml.soap.MimeHeader header = (javax.xml.soap.MimeHeader) i.next(); messageBodyPart.setHeader(header.getName(), header.getValue()); } multipart.addBodyPart(messageBodyPart); } } catch (javax.mail.MessagingException e) { log.error(Messages.getMessage("javaxMailMessagingException00"), e); } return multipart; }
From source file:org.apache.axis2.datasource.jaxb.JAXBAttachmentMarshaller.java
public String addMtomAttachment(byte[] data, int offset, int length, String mimeType, String namespace, String localPart) {//from w ww. j a va 2 s. c o m if (offset != 0 || length != data.length) { int len = length - offset; byte[] newData = new byte[len]; System.arraycopy(data, offset, newData, 0, len); data = newData; } if (mimeType == null || mimeType.length() == 0) { mimeType = APPLICATION_OCTET; } if (log.isDebugEnabled()) { log.debug("Adding MTOM/XOP byte array attachment for element: " + "{" + namespace + "}" + localPart); } String cid = null; try { // Create MIME Body Part final InternetHeaders ih = new InternetHeaders(); final byte[] dataArray = data; ih.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, mimeType); final MimeBodyPart mbp = (MimeBodyPart) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { return new MimeBodyPart(ih, dataArray); } catch (MessagingException e) { throw new OMException(e); } } }); //Create a data source for the MIME Body Part MimePartDataSource mpds = (MimePartDataSource) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return new MimePartDataSource(mbp); } }); long dataLength = data.length; Integer value = null; if (msgContext != null) { value = (Integer) msgContext.getProperty(Constants.Configuration.MTOM_THRESHOLD); } else if (log.isDebugEnabled()) { log.debug( "The msgContext is null so the MTOM threshold value can not be determined; it will default to 0."); } int optimizedThreshold = (value != null) ? value.intValue() : 0; if (optimizedThreshold == 0 || dataLength > optimizedThreshold) { DataHandler dataHandler = new DataHandler(mpds); cid = addDataHandler(dataHandler, false); } // Add the content id to the mime body part mbp.setHeader(HTTPConstants.HEADER_CONTENT_ID, cid); } catch (MessagingException e) { throw new OMException(e); } return cid == null ? null : "cid:" + cid; }
From source file:org.apache.axis2.jaxws.marshaller.impl.alt.Attachment.java
private static DataHandler createDataHandler(Object value, Class cls, String[] mimeTypes, String cid) { if (log.isDebugEnabled()) { System.out.println("Construct data handler for " + cls + " cid=" + cid); }/*from ww w .ja v a2s . c o m*/ DataHandler dh = null; if (cls.isAssignableFrom(DataHandler.class)) { dh = (DataHandler) value; if (dh == null) { return dh; //return if DataHandler is null } try { Object content = dh.getContent(); // If the content is a Source, convert to a String due to // problems with the DataContentHandler if (content instanceof Source) { if (log.isDebugEnabled()) { System.out .println("Converting DataHandler Source content to " + "DataHandlerString content"); } byte[] bytes = (byte[]) ConvertUtils.convert(content, byte[].class); String newContent = new String(bytes); return new DataHandler(newContent, mimeTypes[0]); } } catch (Exception e) { throw ExceptionFactory.makeWebServiceException(e); } } else { try { byte[] bytes = createBytes(value, cls, mimeTypes); // Create MIME Body Part InternetHeaders ih = new InternetHeaders(); ih.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, mimeTypes[0]); MimeBodyPart mbp = new MimeBodyPart(ih, bytes); //Create a data source for the MIME Body Part MimePartDataSource ds = new MimePartDataSource(mbp); dh = new DataHandler(ds); mbp.setHeader(HTTPConstants.HEADER_CONTENT_ID, cid); } catch (Exception e) { throw ExceptionFactory.makeWebServiceException(e); } } return dh; }
From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java
/** * Fill the body of a message already created. * The result message depends on the information given. * /*from w ww. java2s . c o m*/ * @param message * @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"); } if (html != null) { htmlPart = new MimeBodyPart(); htmlPart.setContent(html, "text/html"); } 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.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 ww w . j ava 2s . 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.apache.james.transport.mailets.DSNBounce.java
private MimeBodyPart createDSN(Mail originalMail) throws MessagingException { StringBuffer buffer = new StringBuffer(); appendReportingMTA(buffer);/*from w w w. j a v a 2s. 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.apache.james.transport.mailets.DSNBounce.java
private MimeBodyPart createAttachedOriginal(Mail originalMail, TypeCode attachmentType) throws MessagingException { MimeBodyPart part = new MimeBodyPart(); MimeMessage originalMessage = originalMail.getMessage(); if (attachmentType.equals(TypeCode.HEADS)) { part.setContent(new MimeMessageUtils(originalMessage).getMessageHeaders(), "text/plain"); part.setHeader("Content-Type", "text/rfc822-headers"); } else {//from w w w . j av a 2s. c o m part.setContent(originalMessage, "message/rfc822"); } if ((originalMessage.getSubject() != null) && (originalMessage.getSubject().trim().length() > 0)) { part.setFileName(originalMessage.getSubject().trim()); } else { part.setFileName("No Subject"); } part.setDisposition("Attachment"); return part; }
From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java
private MimeMessage prepareMessageWithAttachment(String scriptContent, String subject) throws MessagingException, IOException { MimeMessage message = prepareMimeMessage(subject); MimeMultipart multipart = new MimeMultipart(); MimeBodyPart scriptPart = new MimeBodyPart(); scriptPart.setDataHandler(/*from w w w .j a v a2s. co m*/ new DataHandler(new ByteArrayDataSource(scriptContent, "application/sieve; charset=UTF-8"))); scriptPart.setDisposition(MimeBodyPart.ATTACHMENT); // setting a DataHandler with no mailcap definition is not // supported by the specs. Javamail activation still work, // but Geronimo activation translate it to text/plain. // Let's manually force the header. scriptPart.setHeader("Content-Type", "application/sieve; charset=UTF-8"); scriptPart.setFileName(SCRIPT_NAME); multipart.addBodyPart(scriptPart); message.setContent(multipart); message.saveChanges(); return message; }
From source file:org.apache.synapse.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/*from w w w . j a v a 2 s .c om*/ */ private void sendMail(MailOutTransportInfo outInfo, MessageContext msgContext) throws AxisFault, MessagingException, IOException { OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = null; try { messageFormatter = TransportUtils.getMessageFormatter(msgContext); } catch (AxisFault axisFault) { throw new BaseTransportException("Unable to get the message formatter to use"); } WSMimeMessage message = new WSMimeMessage(session); Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); // 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) { message.setFrom(outInfo.getFromAddress()); message.setReplyTo((new Address[] { outInfo.getFromAddress() })); } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) { message.setFrom(new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); message.setReplyTo(InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); } else { if (smtpFromAddress != null) { 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)) { message.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO))); } else if (outInfo.getTargetAddresses() != null) { 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)) { message.setRecipients(Message.RecipientType.CC, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC))); } else if (outInfo.getTargetAddresses() != null) { 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 InternetAddress[] trpBccArr = null; if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) { trpBccArr = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC)); } InternetAddress[] mergedBcc = new InternetAddress[(trpBccArr != null ? trpBccArr.length : 0) + (smtpBccAddresses != null ? smtpBccAddresses.length : 0)]; if (trpBccArr != null) { System.arraycopy(trpBccArr, 0, mergedBcc, 0, trpBccArr.length); } if (smtpBccAddresses != null) { System.arraycopy(smtpBccAddresses, 0, mergedBcc, mergedBcc.length, smtpBccAddresses.length); } if (mergedBcc != null) { message.setRecipients(Message.RecipientType.BCC, mergedBcc); } // set subject if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) { message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)); } else if (outInfo.getSubject() != null) { message.setSubject(outInfo.getSubject()); } else { message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction()); } // 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 ByteArrayOutputStream baos = null; String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()); DataHandler dataHandler = null; MimeMultipart mimeMultiPart = null; OMElement firstChild = msgContext.getEnvelope().getBody().getFirstElement(); if (firstChild != null) { if (BaseConstants.DEFAULT_BINARY_WRAPPER.equals(firstChild.getQName())) { baos = new ByteArrayOutputStream(); OMNode omNode = firstChild.getFirstOMChild(); if (omNode != null && omNode instanceof OMText) { Object dh = ((OMText) omNode).getDataHandler(); if (dh != null && dh instanceof DataHandler) { dataHandler = (DataHandler) dh; } } } else if (BaseConstants.DEFAULT_TEXT_WRAPPER.equals(firstChild.getQName())) { if (firstChild instanceof OMSourcedElementImpl) { baos = new ByteArrayOutputStream(); try { firstChild.serializeAndConsume(baos); } catch (XMLStreamException e) { handleException("Error serializing 'text' payload from OMSourcedElement", e); } dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()), MailConstants.TEXT_PLAIN); } else { dataHandler = new DataHandler(firstChild.getText(), MailConstants.TEXT_PLAIN); } } else { baos = new ByteArrayOutputStream(); messageFormatter.writeTo(msgContext, format, baos, true); // create the data handler dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()), contentType); String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT); if (mFormat == null) { mFormat = defaultMailFormat; } 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(); mimeBodyPart2.setDataHandler(dataHandler); mimeBodyPart2.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); mimeMultiPart.addBodyPart(mimeBodyPart1); mimeMultiPart.addBodyPart(mimeBodyPart2); } else { message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); } } } try { if (mimeMultiPart == null) { message.setDataHandler(dataHandler); } else { message.setContent(mimeMultiPart); } Transport.send(message); } catch (MessagingException e) { handleException("Error creating mail message or sending it to the configured server", e); } finally { try { if (baos != null) { baos.close(); } } catch (IOException ignore) { } } }