01: /*
02: * $Id: MailMessageAdapter.java 10489 2008-01-23 17:53:38Z dfeist $
03: * --------------------------------------------------------------------------------------
04: * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
05: *
06: * The software in this package is published under the terms of the CPAL v1.0
07: * license, a copy of which has been included with this distribution in the
08: * LICENSE.txt file.
09: */
10:
11: package org.mule.transport.email;
12:
13: import org.mule.api.MessagingException;
14: import org.mule.transport.AbstractMessageAdapter;
15:
16: import java.util.Enumeration;
17: import java.util.HashMap;
18: import java.util.Iterator;
19: import java.util.Map;
20: import java.util.TreeMap;
21:
22: import javax.mail.Header;
23: import javax.mail.Message;
24: import javax.mail.Multipart;
25: import javax.mail.Part;
26:
27: /**
28: * <code>MailMessageAdapter</code> is a wrapper for a javax.mail.Message that
29: * separates multi-part mail messages, storing all but the first part as attachments
30: * to the underlying {@link AbstractMessageAdapter}. Alternatively, you can use
31: * {@link SimpleMailMessageAdapter}, which stores the message as a single
32: * entity.
33: */
34: public class MailMessageAdapter extends SimpleMailMessageAdapter {
35:
36: private static final long serialVersionUID = -6013198455030918360L;
37: public static final String ATTACHMENT_HEADERS_PROPERTY_POSTFIX = "Headers";
38:
39: public MailMessageAdapter(Object object) throws MessagingException {
40: super (object);
41: }
42:
43: /**
44: * Store only the first body part directly; add further parts as attachments.
45: */
46: // @Override
47: protected void handleMessage(Message message) throws Exception {
48: Object content = message.getContent();
49:
50: if (content instanceof Multipart) {
51: TreeMap attachments = new TreeMap();
52: MailUtils.getAttachments((Multipart) content, attachments);
53:
54: logger.debug("Received Multipart message");
55: int i = 0;
56: for (Iterator iterator = attachments.entrySet().iterator(); iterator
57: .hasNext(); i++) {
58: Map.Entry entry = (Map.Entry) iterator.next();
59: Part part = (Part) entry.getValue();
60: String name = entry.getKey().toString();
61: if (i == 0) {
62: setMessage(part);
63: } else {
64: addAttachment(name, part.getDataHandler());
65: addAttachmentHeaders(name, part);
66: }
67:
68: }
69: } else {
70: setMessage(message);
71: }
72: }
73:
74: protected void addAttachmentHeaders(String name, Part part)
75: throws javax.mail.MessagingException {
76: Map headers = new HashMap(4);
77: for (Enumeration e = part.getAllHeaders(); e.hasMoreElements();) {
78: Header h = (Header) e.nextElement();
79: headers.put(h.getName(), h.getValue());
80: }
81: if (headers.size() > 0) {
82: setProperty(name + ATTACHMENT_HEADERS_PROPERTY_POSTFIX,
83: headers);
84: }
85: }
86:
87: }
|