1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.mail;
18  
19  import java.io.File;
20  import java.io.IOException;
21  import java.net.MalformedURLException;
22  import java.net.URL;
23  import java.util.HashMap;
24  import java.util.Map;
25  
26  import javax.activation.URLDataSource;
27  import javax.mail.internet.MimeMultipart;
28  
29  import org.apache.commons.mail.mocks.MockMultiPartEmailConcrete;
30  
31  /**
32   * JUnit test case for MultiPartEmail Class
33   *
34   * @since 1.0
35   * @author <a href="mailto:corey.scott@gmail.com">Corey Scott</a>
36   * @version $Id: MultiPartEmailTest.java 512622 2007-02-28 06:35:45Z dion $
37   */
38  
39  public class MultiPartEmailTest extends BaseEmailTestCase
40  {
41      /** */
42      private MockMultiPartEmailConcrete email;
43      /** File to used to test file attachmetns (Must be valid) */
44      private File testFile;
45  
46      /**
47       * @param name name
48       */
49      public MultiPartEmailTest(String name)
50      {
51          super(name);
52      }
53  
54      /**
55       * @throws Exception  */
56      protected void setUp() throws Exception
57      {
58          super.setUp();
59          // reusable objects to be used across multiple tests
60          this.email = new MockMultiPartEmailConcrete();
61          testFile = File.createTempFile("testfile", ".txt");
62      }
63  
64      /**
65       * @throws EmailException  */
66      public void testSetMsg() throws EmailException
67      {
68          // ====================================================================
69          // Test Success
70          // ====================================================================
71  
72          // without charset set
73          for (int i = 0; i < testCharsValid.length; i++)
74          {
75              this.email.setMsg(testCharsValid[i]);
76              assertEquals(testCharsValid[i], this.email.getMsg());
77          }
78  
79          // with charset set
80          this.email.setCharset(Email.US_ASCII);
81          for (int i = 0; i < testCharsValid.length; i++)
82          {
83              this.email.setMsg(testCharsValid[i]);
84              assertEquals(testCharsValid[i], this.email.getMsg());
85          }
86  
87          // ====================================================================
88          // Test Exceptions
89          // ====================================================================
90          for (int i = 0; i < testCharsNotValid.length; i++)
91          {
92              try
93              {
94                  this.email.setMsg(testCharsNotValid[i]);
95                  fail("Should have thrown an exception");
96              }
97              catch (EmailException e)
98              {
99                  assertTrue(true);
100             }
101         }
102     }
103 
104     /**
105      * @throws EmailException when a bad address or attachment is used
106      * @throws IOException when sending fails
107      */
108     public void testSend() throws EmailException, IOException
109     {
110         // ====================================================================
111         // Test Success
112         // ====================================================================
113         this.getMailServer();
114 
115         String strSubject = "Test Multipart Send Subject";
116 
117         EmailAttachment attachment = new EmailAttachment();
118         attachment.setPath(testFile.getAbsolutePath());
119         attachment.setDisposition(EmailAttachment.ATTACHMENT);
120         attachment.setName("Test_Attachment");
121         attachment.setDescription("Test Attachment Desc");
122 
123         MockMultiPartEmailConcrete testEmail =
124             new MockMultiPartEmailConcrete();
125         testEmail.setHostName(this.strTestMailServer);
126         testEmail.setSmtpPort(this.getMailServerPort());
127         testEmail.setFrom(this.strTestMailFrom);
128         testEmail.addTo(this.strTestMailTo);
129         testEmail.attach(attachment);
130         testEmail.setSubType("subType");
131 
132         if (EmailUtils.isNotEmpty(this.strTestUser)
133             && EmailUtils.isNotEmpty(this.strTestPasswd))
134         {
135             testEmail.setAuthentication(
136                 this.strTestUser,
137                 this.strTestPasswd);
138         }
139 
140         testEmail.setSubject(strSubject);
141 
142         testEmail.setMsg("Test Message");
143 
144         Map ht = new HashMap();
145         ht.put("X-Priority", "2");
146         ht.put("Disposition-Notification-To", this.strTestMailFrom);
147         ht.put("X-Mailer", "Sendmail");
148 
149         testEmail.setHeaders(ht);
150 
151         testEmail.send();
152 
153         this.fakeMailServer.stop();
154         // validate message
155         validateSend(
156             this.fakeMailServer,
157             strSubject,
158             testEmail.getMsg(),
159             testEmail.getFromAddress(),
160             testEmail.getToList(),
161             testEmail.getCcList(),
162             testEmail.getBccList(),
163             true);
164 
165         // validate attachment
166         validateSend(
167             this.fakeMailServer,
168             strSubject,
169             attachment.getName(),
170             testEmail.getFromAddress(),
171             testEmail.getToList(),
172             testEmail.getCcList(),
173             testEmail.getBccList(),
174             false);
175 
176         // ====================================================================
177         // Test Exceptions
178         // ====================================================================
179         try
180         {
181             this.getMailServer();
182 
183             this.email.send();
184             fail("Should have thrown an exception");
185         }
186         catch (EmailException e)
187         {
188             this.fakeMailServer.stop();
189         }
190     }
191 
192     /**
193      * @throws MalformedURLException when a bad attachment URL is used
194      * @throws EmailException when a bad address or attachment is used
195      */
196     public void testAttach() throws MalformedURLException, EmailException
197     {
198         EmailAttachment attachment;
199         // ====================================================================
200         // Test Success - File
201         // ====================================================================
202         attachment = new EmailAttachment();
203         attachment.setName("Test Attachment");
204         attachment.setDescription("Test Attachment Desc");
205         attachment.setPath(testFile.getAbsolutePath());
206         this.email.attach(attachment);
207 
208         // ====================================================================
209         // Test Success - URL
210         // ====================================================================
211         attachment = new EmailAttachment();
212         attachment.setName("Test Attachment");
213         attachment.setDescription("Test Attachment Desc");
214         attachment.setURL(new URL(this.strTestURL));
215         this.email.attach(attachment);
216 
217         // ====================================================================
218         // Test Exceptions
219         // ====================================================================
220         // null attachment
221         try
222         {
223             this.email.attach(null);
224             fail("Should have thrown an exception");
225         }
226         catch (EmailException e)
227         {
228             assertTrue(true);
229         }
230 
231         // bad url
232         attachment = new EmailAttachment();
233         try
234         {
235             attachment.setURL(new URL("http://bad.url"));
236             this.email.attach(attachment);
237             fail("Should have thrown an exception");
238         }
239         catch (EmailException e)
240         {
241             assertTrue(true);
242         }
243 
244         // bad file
245         attachment = new EmailAttachment();
246         try
247         {
248             attachment.setPath("");
249             this.email.attach(attachment);
250             fail("Should have thrown an exception");
251         }
252         catch (EmailException e)
253         {
254             assertTrue(true);
255         }
256     }
257 
258     /**
259      * @throws MalformedURLException when a bad attachment URL is used
260      * @throws EmailException when a bad address or attachment is used
261      */
262     public void testAttach2() throws MalformedURLException, EmailException
263     {
264         // ====================================================================
265         // Test Success - URL
266         // ====================================================================
267         this.email.attach(
268             new URL(this.strTestURL),
269             "Test Attachment",
270             "Test Attachment Desc");
271 
272         // bad name
273         this.email.attach(
274             new URL(this.strTestURL),
275             null,
276             "Test Attachment Desc");
277     }
278 
279     /**
280      * @throws MalformedURLException when a bad attachment URL is used
281      * @throws EmailException when a bad address or attachment is used
282      */
283     public void testAttach3() throws MalformedURLException, EmailException
284     {
285         // ====================================================================
286         // Test Success - URL
287         // ====================================================================
288         this.email.attach(
289             new URLDataSource(new URL(this.strTestURL)),
290             "Test Attachment",
291             "Test Attachment Desc");
292 
293         // ====================================================================
294         // Test Exceptions
295         // ====================================================================
296         // null datasource
297         try
298         {
299             URLDataSource urlDs = null;
300             this.email.attach(urlDs, "Test Attachment", "Test Attachment Desc");
301             fail("Should have thrown an exception");
302         }
303         catch (EmailException e)
304         {
305             assertTrue(true);
306         }
307 
308         // invalid datasource
309         try
310         {
311             URLDataSource urlDs = new URLDataSource(new URL("http://bad.url/"));
312             this.email.attach(urlDs, "Test Attachment", "Test Attachment Desc");
313             fail("Should have thrown an exception");
314         }
315         catch (EmailException e)
316         {
317             assertTrue(true);
318         }
319     }
320 
321     /**
322      *
323      * @throws Exception Exception
324      */
325     public void testAddPart() throws Exception
326     {
327 
328         // setup
329         this.email = new MockMultiPartEmailConcrete();
330         String strMessage = "hello";
331         String strContentType = "text/plain";
332 
333         // add part
334         this.email.addPart(strMessage, strContentType);
335 
336         // validate
337         assertEquals(
338             strContentType,
339             this.email.getContainer().getBodyPart(0).getContentType());
340         assertEquals(
341             strMessage,
342             this.email.getContainer().getBodyPart(0).getDataHandler()
343                 .getContent());
344 
345     }
346 
347     /**
348      *
349      * @throws Exception Exception
350      */
351     public void testAddPart2() throws Exception
352     {
353 
354         // setup
355         this.email = new MockMultiPartEmailConcrete();
356         String strSubtype = "subtype/abc123";
357 
358         // add part
359         this.email.addPart(new MimeMultipart(strSubtype));
360 
361         // validate
362         assertTrue(
363             this
364                 .email
365                 .getContainer()
366                 .getBodyPart(0)
367                 .getDataHandler()
368                 .getContentType()
369                 .indexOf(strSubtype)
370                 != -1);
371 
372     }
373 
374     /** @todo implement test for GetContainer */
375     public void testGetContainer()
376     {
377         assertTrue(true);
378     }
379 
380     /** init called twice should fail */
381     public void testInit()
382     {
383         // call the init function twice to trigger the IllegalStateException
384         try
385         {
386             this.email.init();
387             this.email.init();
388             fail("Should have thrown an exception");
389         }
390         catch (IllegalStateException e)
391         {
392             assertTrue(true);
393         }
394     }
395 
396     /** test get/set sub type */
397     public void testGetSetSubType()
398     {
399         for (int i = 0; i < testCharsValid.length; i++)
400         {
401             this.email.setSubType(testCharsValid[i]);
402             assertEquals(testCharsValid[i], this.email.getSubType());
403         }
404     }
405 }