View Javadoc
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 static org.junit.Assert.*;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.net.MalformedURLException;
24  import java.net.URL;
25  import java.util.HashMap;
26  import java.util.Map;
27  
28  import javax.activation.FileDataSource;
29  import javax.activation.URLDataSource;
30  import javax.mail.internet.MimeMultipart;
31  
32  import org.apache.commons.mail.mocks.MockMultiPartEmailConcrete;
33  import org.junit.Before;
34  import org.junit.Test;
35  import org.junit.runner.RunWith;
36  import org.powermock.core.classloader.annotations.PrepareForTest;
37  import org.powermock.modules.junit4.PowerMockRunner;
38  
39  /**
40   * JUnit test case for MultiPartEmail Class.
41   *
42   * @since 1.0
43   * @version $Id: MultiPartEmailTest.java 1510687 2013-08-05 19:48:13Z britter $
44   */
45  @RunWith(PowerMockRunner.class)
46  @PrepareForTest( { MockMultiPartEmailConcrete.class, URLDataSource.class })
47  public class MultiPartEmailTest extends AbstractEmailTest
48  {
49      /** */
50      private MockMultiPartEmailConcrete email;
51      /** File to used to test file attachments (Must be valid) */
52      private File testFile;
53  
54      @Before
55      public void setUpMultiPartEmailTest() throws Exception
56      {
57          // reusable objects to be used across multiple tests
58          this.email = new MockMultiPartEmailConcrete();
59          testFile = File.createTempFile("testfile", ".txt");
60      }
61  
62      @Test
63      public void testSetMsg() throws EmailException
64      {
65          // ====================================================================
66          // Test Success
67          // ====================================================================
68  
69          // without charset set
70          for (String validChar : testCharsValid)
71          {
72              this.email.setMsg(validChar);
73              assertEquals(validChar, this.email.getMsg());
74          }
75  
76          // with charset set
77          this.email.setCharset(EmailConstants.US_ASCII);
78          for (String validChar : testCharsValid)
79          {
80              this.email.setMsg(validChar);
81              assertEquals(validChar, this.email.getMsg());
82          }
83  
84          // ====================================================================
85          // Test Exceptions
86          // ====================================================================
87          for (String invalidChar : testCharsNotValid)
88          {
89              try
90              {
91                  this.email.setMsg(invalidChar);
92                  fail("Should have thrown an exception");
93              }
94              catch (EmailException e)
95              {
96                  assertTrue(true);
97              }
98          }
99      }
100 
101     /**
102      * @throws EmailException when a bad address or attachment is used
103      * @throws IOException when sending fails
104      */
105     @Test
106     public void testSend() throws EmailException, IOException
107     {
108         // ====================================================================
109         // Test Success
110         // ====================================================================
111         this.getMailServer();
112 
113         String strSubject = "Test Multipart Send Subject";
114 
115         EmailAttachment attachment = new EmailAttachment();
116         attachment.setPath(testFile.getAbsolutePath());
117         attachment.setDisposition(EmailAttachment.ATTACHMENT);
118         attachment.setName("Test_Attachment");
119         attachment.setDescription("Test Attachment Desc");
120 
121         MockMultiPartEmailConcrete testEmail =
122             new MockMultiPartEmailConcrete();
123         testEmail.setHostName(this.strTestMailServer);
124         testEmail.setSmtpPort(this.getMailServerPort());
125         testEmail.setFrom(this.strTestMailFrom);
126         testEmail.addTo(this.strTestMailTo);
127         testEmail.attach(attachment);
128         testEmail.setSubType("subType");
129 
130         if (EmailUtils.isNotEmpty(this.strTestUser)
131             && EmailUtils.isNotEmpty(this.strTestPasswd))
132         {
133             testEmail.setAuthentication(
134                 this.strTestUser,
135                 this.strTestPasswd);
136         }
137 
138         testEmail.setSubject(strSubject);
139 
140         testEmail.setMsg("Test Message");
141 
142         Map<String, String> ht = new HashMap<String, String>();
143         ht.put("X-Priority", "2");
144         ht.put("Disposition-Notification-To", this.strTestMailFrom);
145         ht.put("X-Mailer", "Sendmail");
146 
147         testEmail.setHeaders(ht);
148 
149         testEmail.send();
150 
151         this.fakeMailServer.stop();
152         // validate message
153         validateSend(
154             this.fakeMailServer,
155             strSubject,
156             testEmail.getMsg(),
157             testEmail.getFromAddress(),
158             testEmail.getToAddresses(),
159             testEmail.getCcAddresses(),
160             testEmail.getBccAddresses(),
161             true);
162 
163         // validate attachment
164         validateSend(
165             this.fakeMailServer,
166             strSubject,
167             attachment.getName(),
168             testEmail.getFromAddress(),
169             testEmail.getToAddresses(),
170             testEmail.getCcAddresses(),
171             testEmail.getBccAddresses(),
172             false);
173 
174         // ====================================================================
175         // Test Exceptions
176         // ====================================================================
177         try
178         {
179             this.getMailServer();
180 
181             this.email.send();
182             fail("Should have thrown an exception");
183         }
184         catch (EmailException e)
185         {
186             this.fakeMailServer.stop();
187         }
188     }
189 
190     @Test
191     public void testAttach() throws Exception
192     {
193         EmailAttachment attachment;
194 
195         // ====================================================================
196         // Test Success - EmailAttachment
197         // ====================================================================
198         attachment = new EmailAttachment();
199         attachment.setName("Test Attachment");
200         attachment.setDescription("Test Attachment Desc");
201         attachment.setPath(testFile.getAbsolutePath());
202         this.email.attach(attachment);
203         assertTrue(this.email.isBoolHasAttachments());
204 
205         // ====================================================================
206         // Test Success - URL
207         // ====================================================================
208         attachment = new EmailAttachment();
209         attachment.setName("Test Attachment");
210         attachment.setDescription("Test Attachment Desc");
211         attachment.setURL(new URL(this.strTestURL));
212         this.email.attach(attachment);
213 
214         // ====================================================================
215         // Test Success - File
216         // ====================================================================
217         this.email.attach(testFile);
218         assertTrue(this.email.isBoolHasAttachments());
219 
220         // ====================================================================
221         // Test Exceptions
222         // ====================================================================
223         // null attachment
224         try
225         {
226             this.email.attach((EmailAttachment) null);
227             fail("Should have thrown an exception");
228         }
229         catch (EmailException e)
230         {
231             assertTrue(true);
232         }
233 
234         // bad url
235         attachment = new EmailAttachment();
236         try
237         {
238             attachment.setURL(createInvalidURL());
239             this.email.attach(attachment);
240             fail("Should have thrown an exception");
241         }
242         catch (EmailException e)
243         {
244             assertTrue(true);
245         }
246 
247         // bad file
248         attachment = new EmailAttachment();
249         try
250         {
251             attachment.setPath("");
252             this.email.attach(attachment);
253             fail("Should have thrown an exception");
254         }
255         catch (EmailException e)
256         {
257             assertTrue(true);
258         }
259     }
260 
261     /**
262      * @throws MalformedURLException when a bad attachment URL is used
263      * @throws EmailException when a bad address or attachment is used
264      */
265     @Test
266     public void testAttach2() throws MalformedURLException, EmailException
267     {
268         // ====================================================================
269         // Test Success - URL
270         // ====================================================================
271         this.email.attach(
272             new URL(this.strTestURL),
273             "Test Attachment",
274             "Test Attachment Desc");
275 
276         // bad name
277         this.email.attach(
278             new URL(this.strTestURL),
279             null,
280             "Test Attachment Desc");
281     }
282 
283     @Test
284     public void testAttach3() throws Exception
285     {
286         // ====================================================================
287         // Test Success - URL
288         // ====================================================================
289         this.email.attach(
290             new URLDataSource(new URL(this.strTestURL)),
291             "Test Attachment",
292             "Test Attachment Desc");
293 
294         // ====================================================================
295         // Test Exceptions
296         // ====================================================================
297         // null datasource
298         try
299         {
300             URLDataSource urlDs = null;
301             this.email.attach(urlDs, "Test Attachment", "Test Attachment Desc");
302             fail("Should have thrown an exception");
303         }
304         catch (EmailException e)
305         {
306             assertTrue(true);
307         }
308 
309         // invalid datasource
310         try
311         {
312             URLDataSource urlDs = new URLDataSource(createInvalidURL());
313             this.email.attach(urlDs, "Test Attachment", "Test Attachment Desc");
314             fail("Should have thrown an exception");
315         }
316         catch (EmailException e)
317         {
318             assertTrue(true);
319         }
320     }
321 
322     @Test
323     public void testAttachFileLocking() throws Exception {
324 
325         // ====================================================================
326         // EMAIL-120: attaching a FileDataSource may result in a locked file
327         //            resource on windows systems
328         // ====================================================================
329 
330         File tmpFile = File.createTempFile("attachment", ".eml");
331         
332         this.email.attach(
333                 new FileDataSource(tmpFile),
334                 "Test Attachment",
335                 "Test Attachment Desc");
336 
337         assertTrue(tmpFile.delete());
338     }
339     
340     @Test
341     public void testAddPart() throws Exception
342     {
343 
344         // setup
345         this.email = new MockMultiPartEmailConcrete();
346         String strMessage = "hello";
347         String strContentType = "text/plain";
348 
349         // add part
350         this.email.addPart(strMessage, strContentType);
351 
352         // validate
353         assertEquals(
354             strContentType,
355             this.email.getContainer().getBodyPart(0).getContentType());
356         assertEquals(
357             strMessage,
358             this.email.getContainer().getBodyPart(0).getDataHandler()
359                 .getContent());
360 
361     }
362 
363     @Test
364     public void testAddPart2() throws Exception
365     {
366 
367         // setup
368         this.email = new MockMultiPartEmailConcrete();
369         String strSubtype = "subtype/abc123";
370 
371         // add part
372         this.email.addPart(new MimeMultipart(strSubtype));
373 
374         // validate
375         assertTrue(
376             this
377                 .email
378                 .getContainer()
379                 .getBodyPart(0)
380                 .getDataHandler()
381                 .getContentType()
382                 .contains(strSubtype));
383 
384     }
385 
386     /** @todo implement test for GetContainer */
387     @Test
388     public void testGetContainer()
389     {
390         assertTrue(true);
391     }
392 
393     /** init called twice should fail */
394     @Test
395     public void testInit()
396     {
397         // call the init function twice to trigger the IllegalStateException
398         try
399         {
400             this.email.init();
401             this.email.init();
402             fail("Should have thrown an exception");
403         }
404         catch (IllegalStateException e)
405         {
406             assertTrue(true);
407         }
408     }
409 
410     /** test get/set sub type */
411     @Test
412     public void testGetSetSubType()
413     {
414         for (String validChar : testCharsValid)
415         {
416             this.email.setSubType(validChar);
417             assertEquals(validChar, this.email.getSubType());
418         }
419     }
420 }