List of usage examples for javax.mail.internet MimeMultipart getContentType
public synchronized String getContentType()
From source file:de.betterform.connector.serializer.MultipartRelatedSerializer.java
public void serialize(Submission submission, Node node, SerializerRequestWrapper wrapper, String defaultEncoding) throws Exception { Map cache = new HashMap(); MimeMultipart multipart = new MimeMultipart(); MimeBodyPart part = new MimeBodyPart(); multipart.addBodyPart(part);/*from w w w . j av a 2 s . c o m*/ String encoding = defaultEncoding; if (submission.getEncoding() != null) { encoding = submission.getEncoding(); } if (node.getNodeType() == Node.ELEMENT_NODE || node.getNodeType() == Node.DOCUMENT_NODE) { part.setText(new String(serializeXML(multipart, cache, submission, node, encoding), encoding), encoding); } else { part.setText(node.getTextContent()); } part.setContentID("<instance.xml@start>"); part.addHeader("Content-Type", "application/xml"); part.addHeader("Content-Transfer-Encoding", "base64"); part.setDisposition("attachment"); part.setFileName("instance.xml"); multipart.setSubType("related; type=\"" + submission.getMediatype() + "\"; start=\"instance.xml@start\""); // FIXME: Is this a global http header or a local mime header? wrapper.getBodyStream() .write(("Content-Type: " + multipart.getContentType() + "\n\nThis is a MIME message.\n") .getBytes(encoding)); multipart.writeTo(wrapper.getBodyStream()); }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Verifies the signature of the passed signed part*/ public MimeBodyPart verifySignedPart(Part signedPart, byte[] data, String contentType, X509Certificate certificate) throws Exception { BCCryptoHelper helper = new BCCryptoHelper(); String signatureTransferEncoding = null; MimeMultipart checkPart = (MimeMultipart) signedPart.getContent(); //it is sure that it is a signed part: set the type to multipart if the //parser has problems parsing it. Don't know why sometimes a parsing fails for //MimeBodyPart. This check looks if the parser is able to find more than one subpart if (checkPart.getCount() == 1) { MimeMultipart multipart = new MimeMultipart(new ByteArrayDataSource(data, contentType)); MimeMessage possibleSignedMessage = new MimeMessage(Session.getInstance(System.getProperties(), null)); possibleSignedMessage.setContent(multipart, multipart.getContentType()); possibleSignedMessage.saveChanges(); //overwrite the formerly found signed part signedPart = helper.getSignedEmbeddedPart(possibleSignedMessage); }//from w ww . ja va 2s. co m //get the content encoding of the signature MimeMultipart signedMultiPart = (MimeMultipart) signedPart.getContent(); //body part 1 is always the signature String encodingHeader[] = signedMultiPart.getBodyPart(1).getHeader("Content-Transfer-Encoding"); if (encodingHeader != null) { signatureTransferEncoding = encodingHeader[0]; } return (helper.verify(signedPart, signatureTransferEncoding, certificate)); }
From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java
/**Builds up a new message from the passed message parts * @param messageType one of the message types definfed in the class AS2Message *//*w ww. j av a2s .co m*/ public AS2Message createMessage(Partner sender, Partner receiver, AS2Payload[] payloads, int messageType, String messageId) throws Exception { if (messageId == null) { messageId = UniqueId.createMessageId(sender.getAS2Identification(), receiver.getAS2Identification()); } BCCryptoHelper cryptoHelper = new BCCryptoHelper(); AS2MessageInfo info = new AS2MessageInfo(); info.setMessageType(messageType); info.setSenderId(sender.getAS2Identification()); info.setReceiverId(receiver.getAS2Identification()); info.setSenderEMail(sender.getEmail()); info.setMessageId(messageId); info.setDirection(AS2MessageInfo.DIRECTION_OUT); info.setSignType(receiver.getSignType()); info.setEncryptionType(receiver.getEncryptionType()); info.setRequestsSyncMDN(receiver.isSyncMDN()); if (!receiver.isSyncMDN()) { info.setAsyncMDNURL(sender.getMdnURL()); } info.setSubject(receiver.getSubject()); try { info.setSenderHost(InetAddress.getLocalHost().getCanonicalHostName()); } catch (UnknownHostException e) { //nop } //create message object to return AS2Message message = new AS2Message(info); //stores all the available body parts that have been prepared List<MimeBodyPart> contentPartList = new ArrayList<MimeBodyPart>(); for (AS2Payload as2Payload : payloads) { //add payload message.addPayload(as2Payload); if (this.runtimeConnection != null) { MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection); messageAccess.initializeOrUpdateMessage(info); } //no MIME message: single payload, unsigned, no CEM if (info.getSignType() == AS2Message.SIGNATURE_NONE && payloads.length == 1 && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) { return (this.createMessageNoMIME(message, receiver)); } //MIME message MimeBodyPart bodyPart = new MimeBodyPart(); String contentType = null; if (as2Payload.getContentType() == null) { contentType = receiver.getContentType(); } else { contentType = as2Payload.getContentType(); } bodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(as2Payload.getData(), contentType))); bodyPart.addHeader("Content-Type", contentType); if (as2Payload.getContentId() != null) { bodyPart.addHeader("Content-ID", as2Payload.getContentId()); } if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) { bodyPart.addHeader("Content-Transfer-Encoding", "base64"); } else { bodyPart.addHeader("Content-Transfer-Encoding", "binary"); } //prepare filename to not violate the MIME header rules if (as2Payload.getOriginalFilename() == null) { as2Payload.setOriginalFilename(new File(as2Payload.getPayloadFilename()).getName()); } String newFilename = as2Payload.getOriginalFilename().replace(' ', '_'); newFilename = newFilename.replace('@', '_'); newFilename = newFilename.replace(':', '_'); newFilename = newFilename.replace(';', '_'); newFilename = newFilename.replace('(', '_'); newFilename = newFilename.replace(')', '_'); bodyPart.addHeader("Content-Disposition", "attachment; filename=" + newFilename); contentPartList.add(bodyPart); } Part contentPart = null; //sigle attachment? No CEM? Every CEM is in a multipart/related container if (contentPartList.size() == 1 && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) { contentPart = contentPartList.get(0); } else { //build up a new MimeMultipart container for the multiple attachments, content-type //is "multipart/related" MimeMultipart multipart = null; //CEM messages are always in a multipart container (even the response which contains only a single //payload) with the subtype "application/ediint-cert-exchange+xml". if (info.getMessageType() == AS2Message.MESSAGETYPE_CEM) { multipart = new MimeMultipart("related; type=\"application/ediint-cert-exchange+xml\""); } else { multipart = new MimeMultipart("related"); } for (MimeBodyPart bodyPart : contentPartList) { multipart.addBodyPart(bodyPart); } contentPart = new MimeMessage(Session.getInstance(System.getProperties(), null)); contentPart.setContent(multipart, multipart.getContentType()); ((MimeMessage) contentPart).saveChanges(); } //should the content be compressed and enwrapped or just enwrapped? if (receiver.getCompressionType() == AS2Message.COMPRESSION_ZLIB) { info.setCompressionType(AS2Message.COMPRESSION_ZLIB); int uncompressedSize = contentPart.getSize(); contentPart = this.compressPayload(receiver, contentPart); int compressedSize = contentPart.getSize(); //sometimes size() is unable to determine the size of the compressed body part and will return -1. Dont log the //compression ratio in this case. if (uncompressedSize == -1 || compressedSize == -1) { if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("message.compressed.unknownratio", new Object[] { info.getMessageId() }), info); } } else { if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("message.compressed", new Object[] { info.getMessageId(), AS2Tools.getDataSizeDisplay(uncompressedSize), AS2Tools.getDataSizeDisplay(compressedSize) }), info); } } } //compute content mic. Try to use sign digest as hash alg. For unsigned messages take sha-1 String digestOID = null; if (info.getSignType() == AS2Message.SIGNATURE_MD5) { digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_MD5); } else { digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_SHA1); } String mic = cryptoHelper.calculateMIC(contentPart, digestOID); if (info.getSignType() == AS2Message.SIGNATURE_MD5) { info.setReceivedContentMIC(mic + ", md5"); } else { info.setReceivedContentMIC(mic + ", sha1"); } this.enwrappInMessageAndSign(message, contentPart, sender, receiver); //encryption requested for the receiver? if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) { String cryptAlias = this.encryptionCertManager .getAliasByFingerprint(receiver.getCryptFingerprintSHA1()); this.encryptDataToMessage(message, cryptAlias, info.getEncryptionType(), receiver); } else { message.setRawData(message.getDecryptedRawData()); if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("message.notencrypted", new Object[] { info.getMessageId() }), info); } } return (message); }
From source file:com.googlecode.ddom.mime.JavaMailTest.java
private void test(boolean preamble) throws Exception { MimeMultipart multipart = new MimeMultipart(); MimeBodyPart bodyPart1 = new MimeBodyPart(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 1000; i++) { buffer.append('('); buffer.append(i);/*from w w w. jav a 2s. com*/ buffer.append(')'); } String content1 = buffer.toString(); bodyPart1 .setDataHandler(new DataHandler(new ByteArrayDataSource(content1.getBytes("UTF-8"), "text/plain"))); Map<String, String> headers1 = new HashMap<String, String>(); headers1.put("Content-ID", "<1@example.com>"); headers1.put("Content-Type", "text/plain; charset=UTF-8"); setHeaders(bodyPart1, headers1); multipart.addBodyPart(bodyPart1); MimeBodyPart bodyPart2 = new MimeBodyPart(); byte[] content2 = new byte[10000]; new Random().nextBytes(content2); bodyPart2.setDataHandler(new DataHandler(new ByteArrayDataSource(content2, "application/octet-stream"))); Map<String, String> headers2 = new HashMap<String, String>(); headers2.put("Content-ID", "<2@example.com>"); headers2.put("Content-Type", "application/octet-stream"); setHeaders(bodyPart2, headers2); multipart.addBodyPart(bodyPart2); if (preamble) { multipart.setPreamble("This is a MIME multipart."); } String boundary = new ContentType(multipart.getContentType()).getParameter("boundary"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); multipart.writeTo(baos); MultipartReader mpr = new MultipartReader(new ByteArrayInputStream(baos.toByteArray()), boundary); assertTrue(mpr.nextPart()); assertEquals(headers1, readHeaders(mpr)); assertEquals(content1, IOUtils.toString(mpr.getContent(), "UTF-8")); assertTrue(mpr.nextPart()); assertEquals(headers2, readHeaders(mpr)); assertArrayEquals(content2, IOUtils.toByteArray(mpr.getContent())); assertFalse(mpr.nextPart()); }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail from a Mail object//from w w w . j a v a 2 s . c o m */ public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({})", mail); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (mail.getFrom() != null) { InternetAddress from = new InternetAddress(mail.getFrom()); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[mail.getTo().length]; int i = 0; for (String strTo : mail.getTo()) { to[i++] = new InternetAddress(strTo); } // Build a multiparted mail with HTML and text content for better SPAM behaviour MimeMultipart content = new MimeMultipart(); if (Mail.MIME_TEXT.equals(mail.getMimeType())) { // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } else if (Mail.MIME_HTML.equals(mail.getMimeType())) { // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(mail.getContent()); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html"); htmlPart.setHeader("Content-Type", "text/html"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); } else { log.warn("Email does not specify content MIME type"); // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } for (Document doc : mail.getAttachments()) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(doc.getPath()); try { is = OKMDocument.getInstance().getContent(token, doc.getPath(), false); File tmp = File.createTempFile("okm", ".tmp"); fos = new FileOutputStream(tmp); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmp.getPath()); docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(docName); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(mail.getSubject(), "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:davmail.imap.ImapConnection.java
protected void appendBodyStructure(StringBuilder buffer, MimeMultipart multiPart) throws IOException, MessagingException { buffer.append('('); for (int i = 0; i < multiPart.getCount(); i++) { MimeBodyPart bodyPart = (MimeBodyPart) multiPart.getBodyPart(i); try {/*from w w w.j av a2 s . c o m*/ Object mimeBody = bodyPart.getContent(); if (mimeBody instanceof MimeMultipart) { appendBodyStructure(buffer, (MimeMultipart) mimeBody); } else { // no multipart, single body appendBodyStructure(buffer, bodyPart); } } catch (UnsupportedEncodingException e) { LOGGER.warn(e); // failover: send default bodystructure buffer.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL NIL NIL NIL)"); } catch (MessagingException me) { DavGatewayTray.warn(me); // failover: send default bodystructure buffer.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL NIL NIL NIL)"); } } int slashIndex = multiPart.getContentType().indexOf('/'); if (slashIndex < 0) { throw new DavMailException("EXCEPTION_INVALID_CONTENT_TYPE", multiPart.getContentType()); } int semiColonIndex = multiPart.getContentType().indexOf(';'); if (semiColonIndex < 0) { buffer.append(" \"").append(multiPart.getContentType().substring(slashIndex + 1).toUpperCase()) .append("\")"); } else { buffer.append(" \"").append( multiPart.getContentType().substring(slashIndex + 1, semiColonIndex).trim().toUpperCase()) .append("\")"); } }
From source file:org.apache.axis.attachments.MimeUtils.java
/** * This routine will get the content type from a mulit-part mime message. * * @param mp the MimeMultipart//from w w w .j a va 2 s. c om * @return the content type */ public static String getContentType(javax.mail.internet.MimeMultipart mp) { StringBuffer contentType = new StringBuffer(mp.getContentType()); // TODO (dims): Commons HttpClient croaks if we don't do this. // Need to get Commons HttpClient fixed. for (int i = 0; i < contentType.length();) { char ch = contentType.charAt(i); if (ch == '\r' || ch == '\n') contentType.deleteCharAt(i); else i++; } return contentType.toString(); }
From source file:org.masukomi.aspirin.core.Bouncer.java
/** * This generates a response to the Return-Path address, or the address of * the message's sender if the Return-Path is not available. Note that this * is different than a mail-client's reply, which would use the Reply-To or * From header.//from ww w . jav a 2s . co m * * @param mail * DOCUMENT ME! * @param message * DOCUMENT ME! * @param bouncer * DOCUMENT ME! * * @throws MessagingException * DOCUMENT ME! */ static public void bounce(MailQue que, Mail mail, String message, MailAddress bouncer) throws MessagingException { if (bouncer != null) { if (log.isDebugEnabled()) { log.debug("bouncing message to postmaster"); } MimeMessage orig = mail.getMessage(); //Create the reply message MimeMessage reply = (MimeMessage) orig.reply(false); //If there is a Return-Path header, if (orig.getHeader(RFC2822Headers.RETURN_PATH) != null) { //Return the message to that address, not to the Reply-To // address reply.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(orig.getHeader(RFC2822Headers.RETURN_PATH)[0])); } //Create the list of recipients in our MailAddress format Collection recipients = new HashSet(); Address[] addresses = reply.getAllRecipients(); for (int i = 0; i < addresses.length; i++) { recipients.add(new MailAddress((InternetAddress) addresses[i])); } //Change the sender... reply.setFrom(bouncer.toInternetAddress()); try { //Create the message body MimeMultipart multipart = new MimeMultipart(); //Add message as the first mime body part MimeBodyPart part = new MimeBodyPart(); part.setContent(message, "text/plain"); part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain"); multipart.addBodyPart(part); //Add the original message as the second mime body part part = new MimeBodyPart(); part.setContent(orig.getContent(), orig.getContentType()); part.setHeader(RFC2822Headers.CONTENT_TYPE, orig.getContentType()); multipart.addBodyPart(part); reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date())); reply.setContent(multipart); reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType()); } catch (IOException ioe) { throw new MessagingException("Unable to create multipart body", ioe); } //Send it off... //sendMail( bouncer, recipients, reply ); que.queMail(reply); } }
From source file:org.mule.service.http.impl.service.server.grizzly.HttpParser.java
public static Collection<HttpPart> parseMultipartContent(InputStream content, String contentType) throws IOException { MimeMultipart mimeMultipart = null; List<HttpPart> parts = Lists.newArrayList(); try {/*from w w w . j a v a2 s . c o m*/ mimeMultipart = new MimeMultipart(new ByteArrayDataSource(content, contentType)); } catch (MessagingException e) { throw new IOException(e); } try { int partCount = mimeMultipart.getCount(); for (int i = 0; i < partCount; i++) { BodyPart part = mimeMultipart.getBodyPart(i); String filename = part.getFileName(); String partName = filename; String[] contentDispositions = part.getHeader(CONTENT_DISPOSITION); if (contentDispositions != null) { String contentDisposition = contentDispositions[0]; if (contentDisposition.contains(NAME_ATTRIBUTE)) { partName = contentDisposition.substring( contentDisposition.indexOf(NAME_ATTRIBUTE) + NAME_ATTRIBUTE.length() + 2); partName = partName.substring(0, partName.indexOf("\"")); } } if (partName == null && mimeMultipart.getContentType().contains(MULTIPART_RELATED.toString())) { String[] contentIdHeader = part.getHeader(CONTENT_ID); if (contentIdHeader != null && contentIdHeader.length > 0) { partName = contentIdHeader[0]; } } HttpPart httpPart = new HttpPart(partName, filename, IOUtils.toByteArray(part.getInputStream()), part.getContentType(), part.getSize()); Enumeration<Header> headers = part.getAllHeaders(); while (headers.hasMoreElements()) { Header header = headers.nextElement(); httpPart.addHeader(header.getName(), header.getValue()); } parts.add(httpPart); } } catch (MessagingException e) { throw new IOException(e); } return parts; }
From source file:org.mule.transport.email.transformers.ObjectToMimeMessage.java
@Override protected void setContent(Object payload, Message msg, String contentType, MuleMessage message) throws Exception { boolean transformInboundAttachments = useInboundAttachments && message.getInboundAttachmentNames().size() > 0; boolean transformOutboundAttachments = useOutboundAttachments && message.getOutboundAttachmentNames().size() > 0; if (transformInboundAttachments || transformOutboundAttachments) { // The content type must be multipart/mixed MimeMultipart multipart = new MimeMultipart("mixed"); multipart.addBodyPart(getPayloadBodyPart(message.getPayload(), contentType)); if (transformInboundAttachments) { for (String name : message.getInboundAttachmentNames()) { // Let outbound attachments override inbound ones if (!transformOutboundAttachments || message.getOutboundAttachment(name) == null) { BodyPart part = getBodyPartForAttachment(message.getInboundAttachment(name), name); // Check message props for extra headers addBodyPartHeaders(part, name, message); multipart.addBodyPart(part); }//from w w w . j a v a 2 s . com } } if (transformOutboundAttachments) { for (String name : message.getOutboundAttachmentNames()) { BodyPart part = getBodyPartForAttachment(message.getOutboundAttachment(name), name); // Check message props for extra headers addBodyPartHeaders(part, name, message); multipart.addBodyPart(part); } } // the payload must be set to the constructed MimeMultipart message payload = multipart; // the ContentType of the message to be sent, must be the multipart content type contentType = multipart.getContentType(); } // now the message will contain the multipart payload, and the multipart // contentType super.setContent(payload, msg, contentType, message); }