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