1 /*****************************************************************
2 * Licensed to the Apache Software Foundation (ASF) under one *
3 * or more contributor license agreements. See the NOTICE file *
4 * distributed with this work for additional information *
5 * regarding copyright ownership. The ASF licenses this file *
6 * to you under the Apache License, Version 2.0 (the *
7 * "License"); you may not use this file except in compliance *
8 * with the License. You may obtain a copy of the License at *
9 * *
10 * http://www.apache.org/licenses/LICENSE-2.0 *
11 * *
12 * Unless required by applicable law or agreed to in writing, *
13 * software distributed under the License is distributed on an *
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
15 * KIND, either express or implied. See the License for the *
16 * specific language governing permissions and limitations *
17 * under the License. *
18 ****************************************************************/
19
20 package org.apache.james.transport.matchers;
21
22 import org.apache.mailet.GenericMatcher;
23 import org.apache.mailet.Mail;
24
25 import javax.mail.MessagingException;
26 import javax.mail.Multipart;
27 import javax.mail.Part;
28 import javax.mail.internet.MimeMessage;
29 import java.util.Collection;
30
31 /***
32 * Checks whether this message has an attachment
33 *
34 * @version CVS $Revision: 494012 $ $Date: 2007-01-08 10:23:58 +0000 (Mon, 08 Jan 2007) $
35 */
36 public class HasAttachment extends GenericMatcher {
37
38 /***
39 * Either every recipient is matching or neither of them.
40 * @throws MessagingException if no attachment is found and at least one exception was thrown
41 */
42 public Collection match(Mail mail) throws MessagingException {
43
44 Exception anException = null;
45
46 try {
47 MimeMessage message = mail.getMessage();
48 Object content;
49
50 /***
51 * if there is an attachment and no inline text,
52 * the content type can be anything
53 */
54 if (message.getContentType() == null) {
55 return null;
56 }
57
58 content = message.getContent();
59 if (content instanceof Multipart) {
60 Multipart multipart = (Multipart) content;
61 for (int i = 0; i < multipart.getCount(); i++) {
62 try {
63 Part part = multipart.getBodyPart(i);
64 String fileName = part.getFileName();
65 if (fileName != null) {
66 return mail.getRecipients();
67 }
68 } catch (MessagingException e) {
69 anException = e;
70 }
71 }
72 } else {
73 String fileName = message.getFileName();
74 if (fileName != null) {
75 return mail.getRecipients();
76 }
77 }
78 } catch (Exception e) {
79 anException = e;
80 }
81
82
83 if (anException != null) {
84 throw new MessagingException("Malformed message", anException);
85 }
86
87 return null;
88 }
89 }