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.assertEquals;
20  import static org.junit.Assert.assertFalse;
21  import static org.junit.Assert.assertNull;
22  import static org.junit.Assert.assertTrue;
23  import static org.junit.Assert.fail;
24  
25  import javax.mail.Session;
26  import javax.mail.internet.InternetAddress;
27  import javax.mail.internet.MimeMessage;
28  import javax.mail.internet.MimeMultipart;
29  import javax.mail.internet.ParseException;
30  import java.io.File;
31  import java.nio.charset.Charset;
32  import java.nio.charset.IllegalCharsetNameException;
33  import java.util.ArrayList;
34  import java.util.Calendar;
35  import java.util.Collections;
36  import java.util.Date;
37  import java.util.HashMap;
38  import java.util.Hashtable;
39  import java.util.List;
40  import java.util.Map;
41  import java.util.Properties;
42  
43  import org.apache.commons.mail.mocks.MockEmailConcrete;
44  import org.junit.Before;
45  import org.junit.Test;
46  
47  /**
48   * JUnit test case for Email Class
49   *
50   * @since 1.0
51   * @version $Id: EmailTest.java 1606709 2014-06-30 12:26:06Z ggregory $
52   */
53  public class EmailTest extends AbstractEmailTest
54  {
55      private static final String[] VALID_EMAILS =
56          {
57              "me@home.com",
58              "joe.doe@apache.org",
59              "someone_here@work-address.com.au"
60          };
61  
62      /** mock for testing */
63      private MockEmailConcrete email;
64  
65      @Before
66      public void setUpEmailTest()
67      {
68          // reusable objects to be used across multiple tests
69          email = new MockEmailConcrete();
70      }
71  
72      @Test
73      public void testGetSetDebug()
74      {
75          email.setDebug(true);
76          assertTrue(email.isDebug());
77          email.setDebug(false);
78          assertFalse(email.isDebug());
79      }
80  
81      @Test
82      public void testGetSetSession() throws Exception
83      {
84  
85          final Properties properties = new Properties(System.getProperties());
86          properties.setProperty(EmailConstants.MAIL_TRANSPORT_PROTOCOL, EmailConstants.SMTP);
87  
88          properties.setProperty(
89              EmailConstants.MAIL_PORT,
90              String.valueOf(getMailServerPort()));
91          properties.setProperty(EmailConstants.MAIL_HOST, strTestMailServer);
92          properties.setProperty(EmailConstants.MAIL_DEBUG, String.valueOf(false));
93  
94          final Session mySession = Session.getInstance(properties, null);
95  
96          email.setMailSession(mySession);
97          assertEquals(mySession, email.getMailSession());
98  
99      }
100 
101     @Test
102     public void testGetSetAuthentication()
103     {
104         // setup
105         final String strUsername = "user.name";
106         final String strPassword = "user.pwd";
107         email.setAuthentication(strUsername, strPassword);
108 
109         // this is cast into DefaultAuthenticator for convenience
110         // and give us access to the getPasswordAuthentication fn
111         final DefaultAuthenticator retrievedAuth =
112             (DefaultAuthenticator) email.getAuthenticator();
113 
114         // tests
115         assertEquals(
116             strUsername,
117             retrievedAuth.getPasswordAuthentication().getUserName());
118         assertEquals(
119             strPassword,
120             retrievedAuth.getPasswordAuthentication().getPassword());
121     }
122 
123     @Test
124     public void testGetSetAuthenticator()
125     {
126         // setup
127         final String strUsername = "user.name";
128         final String strPassword = "user.pwd";
129         final DefaultAuthenticator authenticator =
130             new DefaultAuthenticator(strUsername, strPassword);
131         email.setAuthenticator(authenticator);
132 
133         // this is cast into DefaultAuthenticator for convenience
134         // and give us access to the getPasswordAuthentication fn
135         final DefaultAuthenticator retrievedAuth =
136             (DefaultAuthenticator) email.getAuthenticator();
137 
138         // tests
139         assertEquals(
140                 strUsername,
141                 retrievedAuth.getPasswordAuthentication().getUserName());
142         assertEquals(
143             strPassword,
144             retrievedAuth.getPasswordAuthentication().getPassword());
145     }
146 
147     @Test
148     public void testGetSetCharset()
149     {
150         // test ASCII and UTF-8 charsets; since every JVM is required
151         // to support these, testing them should always succeed.
152         Charset set = Charset.forName("US-ASCII");
153         email.setCharset(set.name());
154         assertEquals(set.name(), email.getCharset());
155 
156         set = Charset.forName("UTF-8");
157         email.setCharset(set.name());
158         assertEquals(set.name(), email.getCharset());
159     }
160 
161     @Test
162     public void testSetContentEmptyMimeMultipart()
163     {
164         final MimeMultipart part = new MimeMultipart();
165         email.setContent(part);
166 
167         assertEquals(part, email.getContentMimeMultipart());
168     }
169 
170     @Test
171     public void testSetContentMimeMultipart()
172     {
173         final MimeMultipart part = new MimeMultipart("abc123");
174         email.setContent(part);
175 
176         assertEquals(part, email.getContentMimeMultipart());
177     }
178 
179     @Test
180     public void testSetContentNull() throws Exception
181     {
182         email.setContent(null);
183         assertNull(email.getContentMimeMultipart());
184     }
185 
186     @Test
187     public void testSetContentObject()
188     {
189         // ====================================================================
190         // test (string object and valid content type)
191         String testObject = "test string object";
192         String testContentType = " ; charset=" + EmailConstants.US_ASCII;
193 
194         email.setContent(testObject, testContentType);
195         assertEquals(testObject, email.getContentObject());
196         assertEquals(testContentType, email.getContentType());
197 
198         // ====================================================================
199         // test (null string object and valid content type)
200         testObject = null;
201         testContentType = " ; charset=" + EmailConstants.US_ASCII + " some more here";
202 
203         email.setContent(testObject, testContentType);
204         assertEquals(testObject, email.getContentObject());
205         assertEquals(testContentType, email.getContentType());
206 
207         // ====================================================================
208         // test (string object and null content type)
209         testObject = "test string object";
210         testContentType = null;
211 
212         email.setContent(testObject, testContentType);
213         assertEquals(testObject, email.getContentObject());
214         assertEquals(testContentType, email.getContentType());
215 
216         // ====================================================================
217         // test (string object and invalid content type)
218         testObject = "test string object";
219         testContentType = " something incorrect ";
220 
221         email.setContent(testObject, testContentType);
222         assertEquals(testObject, email.getContentObject());
223         assertEquals(testContentType, email.getContentType());
224     }
225 
226     @Test
227     public void testGetSetHostName()
228     {
229         for (final String validChar : testCharsValid) {
230             email.setHostName(validChar);
231             assertEquals(validChar, email.getHostName());
232         }
233     }
234 
235     @Test
236     public void testGetSetSmtpPort()
237     {
238         email.setSmtpPort(1);
239         assertEquals(
240             1,
241             Integer.valueOf(email.getSmtpPort()).intValue());
242 
243         email.setSmtpPort(Integer.MAX_VALUE);
244         assertEquals(
245                 Integer.MAX_VALUE,
246                 Integer.valueOf(email.getSmtpPort()).intValue());
247     }
248 
249     @Test(expected = IllegalArgumentException.class)
250     public void testSetSmtpPortZero()
251     {
252         email.setSmtpPort(0);
253     }
254 
255     @Test(expected = IllegalArgumentException.class)
256     public void testSetSmptPortNegative()
257     {
258         email.setSmtpPort(-1);
259     }
260 
261     @Test(expected = IllegalArgumentException.class)
262     public void testSetSmtpPortMinValue()
263     {
264         email.setSmtpPort(Integer.MIN_VALUE);
265     }
266 
267     @Test
268     public void testSetFrom() throws Exception
269     {
270         // ====================================================================
271         // Test Success
272         // ====================================================================
273 
274         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
275         arrExpected.add(new InternetAddress("me@home.com", "me@home.com"));
276         arrExpected.add(
277             new InternetAddress(
278                 "joe.doe@apache.org",
279                 "joe.doe@apache.org"));
280         arrExpected.add(
281                 new InternetAddress(
282                         "someone_here@work-address.com.au",
283                         "someone_here@work-address.com.au"));
284 
285         for (int i = 0; i < VALID_EMAILS.length; i++)
286         {
287 
288             // set from
289             email.setFrom(VALID_EMAILS[i]);
290 
291             // retrieve and verify
292             assertEquals(arrExpected.get(i), email.getFromAddress());
293         }
294     }
295 
296     @Test
297     public void testSetFromWithEncoding() throws Exception
298     {
299         // ====================================================================
300         // Test Success (with charset set)
301         // ====================================================================
302         final String testValidEmail = "me@home.com";
303 
304         final InternetAddress inetExpected =
305             new InternetAddress("me@home.com", "me@home.com", EmailConstants.ISO_8859_1);
306 
307         // set from
308         email.setFrom(testValidEmail, testValidEmail, EmailConstants.ISO_8859_1);
309 
310         // retrieve and verify
311         assertEquals(inetExpected, email.getFromAddress());
312 
313     }
314 
315     @Test
316     public void testSetFrom2() throws Exception
317     {
318         // ====================================================================
319         // Test Success
320         // ====================================================================
321         final String[] testEmailNames = {"Name1", "", null};
322         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
323         arrExpected.add(new InternetAddress("me@home.com", "Name1"));
324         arrExpected.add(
325             new InternetAddress(
326                 "joe.doe@apache.org",
327                 "joe.doe@apache.org"));
328         arrExpected.add(
329                 new InternetAddress(
330                         "someone_here@work-address.com.au",
331                         "someone_here@work-address.com.au"));
332 
333         for (int i = 0; i < VALID_EMAILS.length; i++)
334         {
335             // set from
336             email.setFrom(VALID_EMAILS[i], testEmailNames[i]);
337 
338             // retrieve and verify
339             assertEquals(arrExpected.get(i), email.getFromAddress());
340 
341         }
342     }
343 
344     @Test(expected = IllegalCharsetNameException.class)
345     public void testSetFromBadEncoding() throws Exception {
346         email.setFrom("me@home.com", "me@home.com", "bad.encoding\uc5ec\n");
347     }
348 
349     @Test    
350     public void testAddTo() throws Exception
351     {
352         // ====================================================================
353         // Test Success
354         // ====================================================================
355 
356         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
357         arrExpected.add(new InternetAddress("me@home.com"));
358         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
359         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
360 
361         for (final String address : VALID_EMAILS) {
362             email.addTo(address);
363         }
364 
365         // retrieve and verify
366         assertEquals(arrExpected.size(), email.getToAddresses().size());
367         assertEquals(arrExpected.toString(), email.getToAddresses().toString());
368     }
369 
370     @Test
371     public void testAddToArray() throws Exception
372     {
373         // ====================================================================
374         // Test Success
375         // ====================================================================
376 
377         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
378         arrExpected.add(new InternetAddress("me@home.com"));
379         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
380         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
381 
382         //set To
383         email.addTo(VALID_EMAILS);
384 
385         // retrieve and verify
386         assertEquals(arrExpected.size(), email.getToAddresses().size());
387         assertEquals(arrExpected.toString(), email.getToAddresses().toString());
388     }
389 
390     @Test
391     public void testAddToWithEncoding() throws Exception
392     {
393         // ====================================================================
394         // Test Success
395         // ====================================================================
396         final String testCharset = EmailConstants.ISO_8859_1;
397         final String[] testEmailNames = {"Name1", "", null};
398 
399         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
400         arrExpected.add(
401             new InternetAddress(
402                 "me@home.com",
403                 "Name1",
404                 testCharset));
405         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
406         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
407 
408         for (int i = 0; i < VALID_EMAILS.length; i++)
409         {
410             // set from
411             email.addTo(VALID_EMAILS[i], testEmailNames[i], testCharset);
412         }
413 
414         // retrieve and verify
415         assertEquals(arrExpected.size(), email.getToAddresses().size());
416         assertEquals(arrExpected.toString(), email.getToAddresses().toString());
417     }
418 
419     @Test
420     public void testAddTo2() throws Exception
421     {
422         // ====================================================================
423         // Test Success
424         // ====================================================================
425 
426         final String[] testEmailNames = {"Name1", "", null};
427 
428         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
429         arrExpected.add(new InternetAddress("me@home.com", "Name1"));
430         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
431         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
432 
433         for (int i = 0; i < VALID_EMAILS.length; i++)
434         {
435             // set from
436             email.addTo(VALID_EMAILS[i], testEmailNames[i]);
437         }
438 
439         // retrieve and verify
440         assertEquals(arrExpected.size(), email.getToAddresses().size());
441         assertEquals(arrExpected.toString(), email.getToAddresses().toString());
442     }
443 
444     @Test(expected = IllegalCharsetNameException.class)
445     public void testAddToBadEncoding() throws Exception
446     {
447         email.addTo("me@home.com", "me@home.com", "bad.encoding\uc5ec\n");
448     }
449 
450     @Test
451     public void testSetTo() throws Exception
452     {
453         // ====================================================================
454         // Test Success
455         // ====================================================================
456         final List<InternetAddress> testEmailValid2 = new ArrayList<InternetAddress>();
457         testEmailValid2.add(new InternetAddress("me@home.com", "Name1"));
458         testEmailValid2.add(
459             new InternetAddress(
460                 "joe.doe@apache.org",
461                 "joe.doe@apache.org"));
462         testEmailValid2.add(
463             new InternetAddress(
464                 "someone_here@work-address.com.au",
465                 "someone_here@work-address.com.au"));
466 
467         email.setTo(testEmailValid2);
468 
469         // retrieve and verify
470         assertEquals(testEmailValid2.size(), email.getToAddresses().size());
471         assertEquals(
472                 testEmailValid2.toString(),
473                 email.getToAddresses().toString());
474     }
475 
476     @Test(expected = EmailException.class)
477     public void testSetToNull() throws Exception
478     {
479         email.setTo(null);
480     }
481 
482     @Test(expected = EmailException.class)
483     public void testSetToEmpty() throws Exception
484     {
485         email.setTo(Collections.<InternetAddress>emptyList());
486     }
487 
488     @Test
489     public void testAddCc() throws Exception
490     {
491         // ====================================================================
492         // Test Success
493         // ====================================================================
494 
495         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
496         arrExpected.add(new InternetAddress("me@home.com"));
497         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
498         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
499 
500         for (final String address : VALID_EMAILS) {
501             email.addCc(address);
502         }
503 
504         // retrieve and verify
505         assertEquals(arrExpected.size(), email.getCcAddresses().size());
506         assertEquals(arrExpected.toString(), email.getCcAddresses().toString());
507     }
508 
509     @Test
510     public void testAddCcArray() throws Exception
511     {
512         // ====================================================================
513         // Test Success
514         // ====================================================================
515 
516         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
517         arrExpected.add(new InternetAddress("me@home.com"));
518         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
519         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
520 
521         //set Cc array
522         email.addCc(VALID_EMAILS);
523 
524         // retrieve and verify
525         assertEquals(arrExpected.size(), email.getCcAddresses().size());
526         assertEquals(arrExpected.toString(), email.getCcAddresses().toString());
527     }
528 
529     @Test
530     public void testAddCcWithEncoding() throws Exception
531     {
532         // ====================================================================
533         // Test Success
534         // ====================================================================
535         final String testCharset = EmailConstants.ISO_8859_1;
536         final String[] testEmailNames = {"Name1", "", null};
537 
538         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
539         arrExpected.add(
540             new InternetAddress("me@home.com", "Name1", testCharset));
541         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
542         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
543 
544         // add valid ccs
545         for (int i = 0; i < VALID_EMAILS.length; i++)
546         {
547             email.addCc(VALID_EMAILS[i], testEmailNames[i], testCharset);
548         }
549 
550         // retrieve and verify
551         assertEquals(arrExpected.size(), email.getCcAddresses().size());
552         assertEquals(arrExpected.toString(), email.getCcAddresses().toString());
553     }
554 
555     @Test
556     public void testAddCc2() throws Exception
557     {
558         // ====================================================================
559         // Test Success
560         // ====================================================================
561 
562         final String[] testEmailNames = {"Name1", "", null};
563 
564         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
565         arrExpected.add(new InternetAddress("me@home.com", "Name1"));
566         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
567         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
568 
569         for (int i = 0; i < VALID_EMAILS.length; i++)
570         {
571             // set from
572             email.addCc(VALID_EMAILS[i], testEmailNames[i]);
573         }
574 
575         // retrieve and verify
576         assertEquals(arrExpected.size(), email.getCcAddresses().size());
577         assertEquals(arrExpected.toString(), email.getCcAddresses().toString());
578     }
579 
580     @Test(expected = IllegalCharsetNameException.class)
581     public void testAddCcBadEncoding() throws Exception
582     {
583         email.addCc("me@home.com", "me@home.com", "bad.encoding\uc5ec\n");
584     }
585 
586     @Test
587     public void testSetCc() throws Exception
588     {
589         // ====================================================================
590         // Test Success
591         // ====================================================================
592         final List<InternetAddress> testEmailValid2 = new ArrayList<InternetAddress>();
593         testEmailValid2.add(new InternetAddress("Name1 <me@home.com>"));
594         testEmailValid2.add(new InternetAddress("\"joe.doe@apache.org\" <joe.doe@apache.org>"));
595         testEmailValid2.add(
596                 new InternetAddress("\"someone_here@work.com.au\" <someone_here@work.com.au>"));
597 
598         email.setCc(testEmailValid2);
599         assertEquals(testEmailValid2, email.getCcAddresses());
600     }
601 
602     @Test(expected = EmailException.class)
603     public void testSetCcNull() throws Exception
604     {
605         email.setCc(null);
606     }
607 
608     @Test(expected = EmailException.class)
609     public void testSetCcEmpty() throws Exception
610     {
611         email.setCc(Collections.<InternetAddress>emptyList());
612     }
613 
614     @Test
615     public void testAddBcc() throws Exception
616     {
617         // ====================================================================
618         // Test Success
619         // ====================================================================
620 
621         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
622         arrExpected.add(new InternetAddress("me@home.com"));
623         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
624         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
625 
626         for (final String address : VALID_EMAILS) {
627             email.addBcc(address);
628         }
629 
630         // retrieve and verify
631         assertEquals(arrExpected.size(), email.getBccAddresses().size());
632         assertEquals(
633             arrExpected.toString(),
634             email.getBccAddresses().toString());
635     }
636 
637     @Test
638     public void testAddBccArray() throws Exception
639     {
640         // ====================================================================
641         // Test Success
642         // ====================================================================
643 
644         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
645         arrExpected.add(new InternetAddress("me@home.com"));
646         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
647         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
648 
649         // add a valid bcc
650         email.addBcc(VALID_EMAILS);
651 
652         // retrieve and verify
653         assertEquals(arrExpected.size(), email.getBccAddresses().size());
654         assertEquals(
655             arrExpected.toString(),
656             email.getBccAddresses().toString());
657     }
658 
659     @Test
660     public void testAddBccWithEncoding() throws Exception
661     {
662         // ====================================================================
663         // Test Success
664         // ====================================================================
665         final String testCharset = EmailConstants.ISO_8859_1;
666         final String[] testEmailNames = {"Name1", "", null};
667 
668         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
669         arrExpected.add(new InternetAddress("me@home.com", "Name1", testCharset));
670         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
671         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
672 
673         for (int i = 0; i < VALID_EMAILS.length; i++)
674         {
675             // set bccs
676             email.addBcc(VALID_EMAILS[i], testEmailNames[i], testCharset);
677         }
678 
679         // retrieve and verify
680         assertEquals(arrExpected.size(), email.getBccAddresses().size());
681         assertEquals(
682             arrExpected.toString(),
683             email.getBccAddresses().toString());
684     }
685 
686     @Test
687     public void testAddBcc2() throws Exception
688     {
689         // ====================================================================
690         // Test Success
691         // ====================================================================
692 
693         final String[] testEmailNames = {"Name1", "", null};
694 
695 
696         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
697         arrExpected.add(new InternetAddress("me@home.com", "Name1"));
698         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
699         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
700 
701         for (int i = 0; i < VALID_EMAILS.length; i++)
702         {
703             // set from
704             email.addBcc(VALID_EMAILS[i], testEmailNames[i]);
705         }
706 
707         // retrieve and verify
708         assertEquals(arrExpected.size(), email.getBccAddresses().size());
709         assertEquals(
710             arrExpected.toString(),
711             email.getBccAddresses().toString());
712     }
713 
714     @Test(expected = IllegalCharsetNameException.class)
715     public void testAddBccBadEncoding() throws Exception
716     {
717         email.addBcc("me@home.com", "me@home.com", "bad.encoding\uc5ec\n");
718     }
719 
720     @Test
721     public void testSetBcc() throws Exception
722     {
723         // ====================================================================
724         // Test Success
725         // ====================================================================
726         final List<InternetAddress> testInetEmailValid = new ArrayList<InternetAddress>();
727         testInetEmailValid.add(new InternetAddress("me@home.com", "Name1"));
728         testInetEmailValid.add(
729             new InternetAddress(
730                 "joe.doe@apache.org",
731                 "joe.doe@apache.org"));
732         testInetEmailValid.add(
733             new InternetAddress(
734                 "someone_here@work-address.com.au",
735                 "someone_here@work-address.com.au"));
736 
737         email.setBcc(testInetEmailValid);
738         assertEquals(testInetEmailValid, email.getBccAddresses());
739     }
740 
741     @Test(expected = EmailException.class)
742     public void testSetBccNull() throws Exception
743     {
744         email.setBcc(null);
745     }
746 
747     @Test(expected = EmailException.class)
748     public void testSetBccEmpty() throws Exception
749     {
750         email.setBcc(Collections.<InternetAddress>emptyList());
751     }
752 
753     @Test
754     public void testAddReplyTo() throws Exception
755     {
756         // ====================================================================
757         // Test Success
758         // ====================================================================
759 
760         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
761         arrExpected.add(new InternetAddress("me@home.com"));
762         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
763         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
764 
765         for (final String address : VALID_EMAILS) {
766             email.addReplyTo(address);
767         }
768 
769         // retrieve and verify
770         assertEquals(arrExpected.size(), email.getReplyToAddresses().size());
771         assertEquals(
772             arrExpected.toString(),
773             email.getReplyToAddresses().toString());
774     }
775 
776     @Test
777     public void testAddReplyToWithEncoding() throws Exception
778     {
779         // ====================================================================
780         // Test Success
781         // ====================================================================
782         final String testCharset = EmailConstants.ISO_8859_1;
783         final String[] testEmailNames = {"Name1", "", null};
784 
785         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
786         arrExpected.add(new InternetAddress("me@home.com", "Name1", testCharset));
787         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
788         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
789 
790         for (int i = 0; i < VALID_EMAILS.length; i++)
791         {
792             // set replyTo
793             email.addReplyTo(VALID_EMAILS[i], testEmailNames[i], testCharset);
794         }
795 
796         // retrieve and verify
797         assertEquals(arrExpected.size(), email.getReplyToAddresses().size());
798         assertEquals(
799             arrExpected.toString(),
800             email.getReplyToAddresses().toString());
801     }
802 
803     @Test
804     public void testAddReplyTo2() throws Exception
805     {
806         // ====================================================================
807         // Test Success
808         // ====================================================================
809 
810         final String[] testEmailNames = {"Name1", "", null};
811 
812         final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
813         arrExpected.add(new InternetAddress("me@home.com", "Name1"));
814         arrExpected.add(new InternetAddress("joe.doe@apache.org"));
815         arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
816 
817         for (int i = 0; i < VALID_EMAILS.length; i++)
818         {
819             // set replyTo
820             email.addReplyTo(VALID_EMAILS[i], testEmailNames[i]);
821         }
822 
823         // retrieve and verify
824         assertEquals(arrExpected.size(), email.getReplyToAddresses().size());
825         assertEquals(
826             arrExpected.toString(),
827             email.getReplyToAddresses().toString());
828     }
829 
830     @Test(expected = IllegalCharsetNameException.class)
831     public void testAddReplyToBadEncoding() throws Exception
832     {
833         email.addReplyTo("me@home.com", "me@home.com", "bad.encoding\uc5ec\n");
834     }
835 
836     @Test
837     public void testAddHeader()
838     {
839         // ====================================================================
840         // Test Success
841         // ====================================================================
842         final Map<String, String> headers = new HashMap<String, String>();
843         headers.put("X-Priority", "1");
844         headers.put("Disposition-Notification-To", "me@home.com");
845         headers.put("X-Mailer", "Sendmail");
846 
847         for (final Map.Entry<String, String> header : headers.entrySet()) {
848             final String name = header.getKey();
849             final String value = header.getValue();
850             email.addHeader(name, value);
851         }
852 
853         assertEquals(headers.size(), email.getHeaders().size());
854         assertEquals(headers, email.getHeaders());
855     }
856 
857     @Test(expected = IllegalArgumentException.class)
858     public void testAddHeaderEmptyName() throws Exception
859     {
860         email.addHeader("", "me@home.com");
861     }
862 
863     @Test(expected = IllegalArgumentException.class)
864     public void testAddHeaderNullName() throws Exception
865     {
866         email.addHeader(null, "me@home.com");
867     }
868 
869     @Test(expected = IllegalArgumentException.class)
870     public void testAddHeaderEmptyValue() throws Exception
871     {
872         email.addHeader("X-Mailer", "");
873     }
874 
875     @Test(expected = IllegalArgumentException.class)
876     public void testAddHeaderNullValue() throws Exception
877     {
878         email.addHeader("X-Mailer", null);
879     }
880 
881     @Test
882     public void testSetHeaders()
883     {
884         final Map<String, String> ht = new Hashtable<String, String>();
885         ht.put("X-Priority", "1");
886         ht.put("Disposition-Notification-To", "me@home.com");
887         ht.put("X-Mailer", "Sendmail");
888 
889         email.setHeaders(ht);
890 
891         assertEquals(ht.size(), email.getHeaders().size());
892         assertEquals(ht, email.getHeaders());
893     }
894 
895     @Test
896     public void testFoldingHeaders() throws Exception
897     {
898         email.setHostName(strTestMailServer);
899         email.setSmtpPort(getMailServerPort());
900         email.setFrom("a@b.com");
901         email.addTo("c@d.com");
902         email.setSubject("test mail");
903 
904         final String headerValue = "1234567890 1234567890 123456789 01234567890 123456789 0123456789 01234567890 01234567890";
905         email.addHeader("X-LongHeader", headerValue);
906         
907         assertTrue(email.getHeaders().size() == 1);
908         // the header should not yet be folded -> will be done by buildMimeMessage()
909         assertFalse(email.getHeaders().get("X-LongHeader").contains("\r\n"));
910         
911         email.buildMimeMessage();
912 
913         final MimeMessage msg = email.getMimeMessage();
914         msg.saveChanges();
915         
916         final String[] values = msg.getHeader("X-LongHeader");
917         assertEquals(1, values.length);
918         
919         // the header should be split in two lines
920         final String[] lines = values[0].split("\\r\\n");
921         assertEquals(2, lines.length);
922         
923         // there should only be one line-break
924         assertTrue(values[0].indexOf("\n") == values[0].lastIndexOf("\n"));
925     }
926 
927     @Test(expected = IllegalArgumentException.class)
928     public void testSetHeaderEmptyValue() throws Exception
929     {
930         email.setHeaders(Collections.singletonMap("X-Mailer", ""));
931     }
932 
933     @Test(expected = IllegalArgumentException.class)
934     public void testSetHeaderNullValue() throws Exception
935     {
936         email.setHeaders(Collections.singletonMap("X-Mailer", (String) null));
937     }
938 
939     @Test(expected = IllegalArgumentException.class)
940     public void testSetHeaderEmptyName() throws Exception
941     {
942         email.setHeaders(Collections.singletonMap("", "me@home.com"));
943     }
944 
945     @Test(expected = IllegalArgumentException.class)
946     public void testSetHeaderNullName() throws Exception
947     {
948         email.setHeaders(Collections.singletonMap((String) null, "me@home.com"));
949     }
950 
951     @Test
952     public void testSetSubject()
953     {
954         for (final String validChar : testCharsValid) {
955             email.setSubject(validChar);
956             assertEquals(validChar, email.getSubject());
957         }
958     }
959 
960     @Test(expected = EmailException.class)
961     public void testSendNoHostName() throws Exception
962     {
963         getMailServer();
964 
965         email = new MockEmailConcrete();
966         email.send();
967     }
968 
969     @Test
970     public void testSendBadHostName()
971     {
972         try
973         {
974             getMailServer();
975 
976             email = new MockEmailConcrete();
977             email.setSubject("Test Email #1 Subject");
978             email.setHostName("bad.host.com");
979             email.setFrom("me@home.com");
980             email.addTo("me@home.com");
981             email.addCc("me@home.com");
982             email.addBcc("me@home.com");
983             email.addReplyTo("me@home.com");
984 
985             email.setContent(
986                     "test string object",
987                     " ; charset=" + EmailConstants.US_ASCII);
988 
989             email.send();
990             fail("Should have thrown an exception");
991         }
992         catch (final EmailException e)
993         {
994             assertTrue(e.getCause() instanceof ParseException);
995             fakeMailServer.stop();
996         }
997     }
998 
999     @Test(expected = EmailException.class)
1000     public void testSendFromNotSet() throws Exception
1001     {
1002          getMailServer();
1003 
1004          email = new MockEmailConcrete();
1005          email.setHostName(strTestMailServer);
1006          email.setSmtpPort(getMailServerPort());
1007 
1008          email.send();
1009     }
1010 
1011     @Test(expected = EmailException.class)
1012     public void testSendDestinationNotSet() throws Exception
1013     {
1014         getMailServer();
1015 
1016         email = new MockEmailConcrete();
1017         email.setHostName(strTestMailServer);
1018         email.setSmtpPort(getMailServerPort());
1019         email.setFrom("me@home.com");
1020 
1021         email.send();
1022     }
1023 
1024     @Test(expected = EmailException.class)
1025     public void testSendBadAuthSet() throws Exception
1026     {
1027         getMailServer();
1028 
1029         email = new MockEmailConcrete();
1030         email.setHostName(strTestMailServer);
1031         email.setSmtpPort(getMailServerPort());
1032         email.setFrom(strTestMailFrom);
1033         email.addTo(strTestMailTo);
1034         email.setAuthentication(null, null);
1035 
1036         email.send();
1037     }
1038 
1039     @Test
1040     public void testSendCorrectSmtpPortContainedInException()
1041     {
1042         try
1043         {
1044             getMailServer();
1045 
1046             email = new MockEmailConcrete();
1047             email.setHostName("bad.host.com");
1048             email.setSSLOnConnect(true);
1049             email.setFrom(strTestMailFrom);
1050             email.addTo(strTestMailTo);
1051             email.setAuthentication(null, null);
1052             email.send();
1053             fail("Should have thrown an exception");
1054         }
1055         catch (final EmailException e)
1056         {
1057             assertTrue(e.getMessage().contains("bad.host.com:465"));
1058             fakeMailServer.stop();
1059         }
1060     }
1061 
1062     @Test
1063     public void testGetSetSentDate()
1064     {
1065         // with input date
1066 
1067         final Date dtTest = Calendar.getInstance().getTime();
1068         email.setSentDate(dtTest);
1069         assertEquals(dtTest, email.getSentDate());
1070 
1071         // with null input (this is a fudge :D)
1072         email.setSentDate(null);
1073 
1074         final Date sentDate = email.getSentDate();
1075 
1076         // Date objects are millisecond specific. If you have a slow processor,
1077         // time passes between the generation of dtTest and the new Date() in
1078         // getSentDate() and this test fails. Make sure that the difference
1079         // is less than a second...
1080         assertTrue(Math.abs(sentDate.getTime() - dtTest.getTime()) < 1000);
1081     }
1082 
1083     @Test
1084     public void testToInternetAddressArray() throws Exception
1085     {
1086         final List<InternetAddress> testInetEmailValid = new ArrayList<InternetAddress>();
1087 
1088         testInetEmailValid.add(new InternetAddress("me@home.com", "Name1"));
1089         testInetEmailValid.add(
1090                 new InternetAddress(
1091                         "joe.doe@apache.org",
1092                         "joe.doe@apache.org"));
1093         testInetEmailValid.add(
1094                 new InternetAddress(
1095                         "someone_here@work-address.com.au",
1096                         "someone_here@work-address.com.au"));
1097 
1098         email.setBcc(testInetEmailValid);
1099         assertEquals(
1100                 testInetEmailValid.size(),
1101                 email.getBccAddresses().size());
1102     }
1103 
1104     @Test
1105     public void testSetPopBeforeSmtp()
1106     {
1107         // simple test (can be improved)
1108         final boolean boolPopBeforeSmtp = true;
1109         final String strHost = "mail.home.com";
1110         final String strUsername = "user.name";
1111         final String strPassword = "user.passwd";
1112 
1113         email.setPopBeforeSmtp(
1114             boolPopBeforeSmtp,
1115             strHost,
1116             strUsername,
1117             strPassword);
1118 
1119         // retrieve and verify
1120         assertEquals(boolPopBeforeSmtp, email.isPopBeforeSmtp());
1121         assertEquals(strHost, email.getPopHost());
1122         assertEquals(strUsername, email.getPopUsername());
1123         assertEquals(strPassword, email.getPopPassword());
1124     }
1125 
1126     /**
1127      * Test: When Email.setCharset() is called, a subsequent setContent()
1128      * should use that charset for text content types unless overridden
1129      * by the contentType parameter.
1130      * See https://issues.apache.org/jira/browse/EMAIL-1.
1131      *
1132      *
1133      * Case 1:
1134      * Setting a default charset results in adding that charset info to
1135      * to the content type of a text/based content object.
1136      * @throws Exception on any error
1137      */
1138     @Test
1139     public void testDefaultCharsetAppliesToTextContent() throws Exception
1140     {
1141         email.setHostName(strTestMailServer);
1142         email.setSmtpPort(getMailServerPort());
1143         email.setFrom("a@b.com");
1144         email.addTo("c@d.com");
1145         email.setSubject("test mail");
1146 
1147         email.setCharset("ISO-8859-1");
1148         email.setContent("test content", "text/plain");
1149         email.buildMimeMessage();
1150         final MimeMessage msg = email.getMimeMessage();
1151         msg.saveChanges();
1152         assertEquals("text/plain; charset=ISO-8859-1", msg.getContentType());
1153     }
1154 
1155     /**
1156      * Case 2:
1157      * A default charset is overridden by an explicitly specified
1158      * charset in setContent().
1159      * @throws Exception on any error
1160      */
1161     @Test
1162     public void testDefaultCharsetCanBeOverriddenByContentType()
1163         throws Exception
1164     {
1165         email.setHostName(strTestMailServer);
1166         email.setSmtpPort(getMailServerPort());
1167         email.setFrom("a@b.com");
1168         email.addTo("c@d.com");
1169         email.setSubject("test mail");
1170 
1171         email.setCharset("ISO-8859-1");
1172         email.setContent("test content", "text/plain; charset=US-ASCII");
1173         email.buildMimeMessage();
1174         final MimeMessage msg = email.getMimeMessage();
1175         msg.saveChanges();
1176         assertEquals("text/plain; charset=US-ASCII", msg.getContentType());
1177     }
1178 
1179     /**
1180      * Case 3:
1181      * A non-text content object ignores a default charset entirely.
1182      * @throws Exception on any error
1183      */
1184     @Test
1185     public void testDefaultCharsetIgnoredByNonTextContent()
1186         throws Exception
1187     {
1188         email.setHostName(strTestMailServer);
1189         email.setSmtpPort(getMailServerPort());
1190         email.setFrom("a@b.com");
1191         email.addTo("c@d.com");
1192         email.setSubject("test mail");
1193 
1194         email.setCharset("ISO-8859-1");
1195         email.setContent("test content", "application/octet-stream");
1196         email.buildMimeMessage();
1197         final MimeMessage msg = email.getMimeMessage();
1198         msg.saveChanges();
1199         assertEquals("application/octet-stream", msg.getContentType());
1200     }
1201 
1202     @Test
1203     public void testCorrectContentTypeForPNG() throws Exception
1204     {
1205         email.setHostName(strTestMailServer);
1206         email.setSmtpPort(getMailServerPort());
1207         email.setFrom("a@b.com");
1208         email.addTo("c@d.com");
1209         email.setSubject("test mail");
1210 
1211         email.setCharset("ISO-8859-1");
1212         final File png = new File("./target/test-classes/images/logos/maven-feather.png");
1213         email.setContent(png, "image/png");
1214         email.buildMimeMessage();
1215         final MimeMessage msg = email.getMimeMessage();
1216         msg.saveChanges();
1217         assertEquals("image/png", msg.getContentType());
1218     }    
1219 }