1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.james.transport.mailets;
21
22 import org.apache.mailet.base.GenericMailet;
23 import org.apache.mailet.Mail;
24 import org.apache.mailet.MailetException;
25
26 import javax.mail.MessagingException;
27 import javax.mail.internet.MimeBodyPart;
28 import javax.mail.internet.MimeMessage;
29 import javax.mail.internet.MimeMultipart;
30
31 import java.io.BufferedInputStream;
32 import java.io.ByteArrayInputStream;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.util.Iterator;
36 import java.util.Map;
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58 public class RecoverAttachment extends GenericMailet {
59
60 public static final String ATTRIBUTE_PARAMETER_NAME = "attribute";
61
62 private String attributeName = null;
63
64
65
66
67
68
69 public void init() throws MailetException {
70 attributeName = getInitParameter(ATTRIBUTE_PARAMETER_NAME);
71
72 if (attributeName == null) {
73 throw new MailetException(ATTRIBUTE_PARAMETER_NAME
74 + " is a mandatory parameter");
75 }
76
77 log("RecoverAttachment is initialised with attribute [" + attributeName
78 + "]");
79 }
80
81
82
83
84
85
86
87
88
89
90 public void service(Mail mail) throws MailetException {
91 Map attachments = (Map) mail.getAttribute(attributeName);
92 if (attachments != null) {
93
94 MimeMessage message = null;
95 try {
96 message = mail.getMessage();
97 } catch (MessagingException e) {
98 throw new MailetException(
99 "Could not retrieve message from Mail object", e);
100 }
101
102 Iterator i = attachments.values().iterator();
103 try {
104 while (i.hasNext()) {
105 byte[] bytes = (byte[]) i.next();
106 InputStream is = new BufferedInputStream(
107 new ByteArrayInputStream(bytes));
108 MimeBodyPart p = new MimeBodyPart(is);
109 if (!(message.isMimeType("multipart/*") && (message
110 .getContent() instanceof MimeMultipart))) {
111 Object content = message.getContent();
112 String contentType = message.getContentType();
113 MimeMultipart mimeMultipart = new MimeMultipart();
114 message.setContent(mimeMultipart);
115
116
117
118 message.saveChanges();
119 mimeMultipart.setParent(message);
120 MimeBodyPart bodyPart = new MimeBodyPart();
121 mimeMultipart.addBodyPart(bodyPart);
122 bodyPart.setContent(content, contentType);
123 }
124 ((MimeMultipart) message.getContent()).addBodyPart(p);
125 }
126 message.saveChanges();
127 } catch (MessagingException e) {
128 log("MessagingException in recoverAttachment", e);
129 } catch (IOException e) {
130 log("IOException in recoverAttachment", e);
131 }
132 }
133 }
134
135
136
137
138
139
140 public String getMailetInfo() {
141 return "RecoverAttachment Mailet";
142 }
143
144 }