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