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.URL;
22  
23  import javax.activation.FileDataSource;
24  
25  import org.apache.commons.mail.mocks.MockHtmlEmailConcrete;
26  import org.apache.commons.mail.settings.EmailConfiguration;
27  
28  /**
29   * JUnit test case for HtmlEmail Class
30   *
31   * @since 1.0
32   * @author <a href="mailto:corey.scott@gmail.com">Corey Scott</a>
33   * @version $Id: HtmlEmailTest.java 545815 2007-06-09 23:46:00Z bspeakmon $
34   */
35  
36  public class HtmlEmailTest extends BaseEmailTestCase
37  {
38      /** */
39      private MockHtmlEmailConcrete email;
40  
41      /**
42       * @param name name
43       */
44      public HtmlEmailTest(String name)
45      {
46          super(name);
47      }
48  
49      /**
50       * @throws Exception  */
51      protected void setUp() throws Exception
52      {
53          super.setUp();
54          // reusable objects to be used across multiple tests
55          this.email = new MockHtmlEmailConcrete();
56      }
57  
58      /**
59       * @throws EmailException  */
60      public void testGetSetTextMsg() throws EmailException
61      {
62          // ====================================================================
63          // Test Success
64          // ====================================================================
65          for (int i = 0; i < testCharsValid.length; i++)
66          {
67              this.email.setTextMsg(testCharsValid[i]);
68              assertEquals(testCharsValid[i], this.email.getTextMsg());
69          }
70  
71          // ====================================================================
72          // Test Exception
73          // ====================================================================
74          for (int i = 0; i < this.testCharsNotValid.length; i++)
75          {
76              try
77              {
78                  this.email.setTextMsg(this.testCharsNotValid[i]);
79                  fail("Should have thrown an exception");
80              }
81              catch (EmailException e)
82              {
83                  assertTrue(true);
84              }
85          }
86  
87      }
88  
89      /**
90       * @throws EmailException if setting the message fails
91       */
92      public void testGetSetHtmlMsg() throws EmailException
93      {
94          // ====================================================================
95          // Test Success
96          // ====================================================================
97          for (int i = 0; i < testCharsValid.length; i++)
98          {
99              this.email.setHtmlMsg(testCharsValid[i]);
100             assertEquals(testCharsValid[i], this.email.getHtmlMsg());
101         }
102 
103         // ====================================================================
104         // Test Exception
105         // ====================================================================
106         for (int i = 0; i < this.testCharsNotValid.length; i++)
107         {
108             try
109             {
110                 this.email.setHtmlMsg(this.testCharsNotValid[i]);
111                 fail("Should have thrown an exception");
112             }
113             catch (EmailException e)
114             {
115                 assertTrue(true);
116             }
117         }
118 
119     }
120 
121     /**
122      * @throws EmailException  */
123     public void testGetSetMsg() throws EmailException
124     {
125         // ====================================================================
126         // Test Success
127         // ====================================================================
128         for (int i = 0; i < testCharsValid.length; i++)
129         {
130             this.email.setMsg(testCharsValid[i]);
131             assertEquals(testCharsValid[i], this.email.getTextMsg());
132 
133             assertTrue(
134                 this.email.getHtmlMsg().indexOf(testCharsValid[i]) != -1);
135         }
136 
137         // ====================================================================
138         // Test Exception
139         // ====================================================================
140         for (int i = 0; i < this.testCharsNotValid.length; i++)
141         {
142             try
143             {
144                 this.email.setMsg(this.testCharsNotValid[i]);
145                 fail("Should have thrown an exception");
146             }
147             catch (EmailException e)
148             {
149                 assertTrue(true);
150             }
151         }
152 
153     }
154 
155     /**
156      *
157      * @throws Exception Exception
158      */
159     public void testEmbedUrl() throws Exception
160     {
161         // ====================================================================
162         // Test Success
163         // ====================================================================
164 
165         String strEmbed =
166             this.email.embed(new URL(this.strTestURL), "Test name");
167         assertNotNull(strEmbed);
168         assertEquals(HtmlEmail.CID_LENGTH, strEmbed.length());
169 
170         // if we embed the same name again, do we get the same content ID
171         // back?
172         String testCid =
173             this.email.embed(new URL(this.strTestURL), "Test name");
174         assertEquals(strEmbed, testCid);
175 
176         // if we embed the same URL under a different name, is the content ID
177         // unique?
178         String newCid =
179             this.email.embed(new URL(this.strTestURL), "Test name 2");
180         assertFalse(strEmbed.equals(newCid));
181 
182         // ====================================================================
183         // Test Exceptions
184         // ====================================================================
185 
186         // Does an invalid URL throw an exception?
187         try
188         {
189             this.email.embed(new URL("http://bad.url"), "Bad URL");
190             fail("Should have thrown an exception");
191         }
192         catch (EmailException e)
193         {
194             // expected
195         }
196 
197         // if we try to embed a different URL under a previously used name,
198         // does it complain?
199         try
200         {
201             this.email.embed(new URL("http://www.google.com"), "Test name");
202             fail("shouldn't be able to use an existing name with a different URL!");
203         }
204         catch (EmailException e)
205         {
206             // expected
207         }
208     }
209 
210     public void testEmbedFile() throws Exception
211     {
212         // ====================================================================
213         // Test Success
214         // ====================================================================
215 
216         File file = File.createTempFile("testEmbedFile", "txt");
217         file.deleteOnExit();
218         String strEmbed = this.email.embed(file);
219         assertNotNull(strEmbed);
220         assertEquals("generated CID has wrong length",
221                 HtmlEmail.CID_LENGTH, strEmbed.length());
222 
223         // if we embed the same file again, do we get the same content ID
224         // back?
225         String testCid =
226             this.email.embed(file);
227         assertEquals("didn't get same CID after embedding same file twice",
228                 strEmbed, testCid);
229 
230         // if we embed a new file, is the content ID unique?
231         File otherFile = File.createTempFile("testEmbedFile2", "txt");
232         otherFile.deleteOnExit();
233         String newCid = this.email.embed(otherFile);
234         assertFalse("didn't get unique CID from embedding new file",
235                 strEmbed.equals(newCid));
236     }
237 
238     public void testEmbedUrlAndFile() throws Exception
239     {
240         File tmpFile = File.createTempFile("testfile", "txt");
241         tmpFile.deleteOnExit();
242         String fileCid = this.email.embed(tmpFile);
243 
244         URL fileUrl = tmpFile.toURL();
245         String urlCid = this.email.embed(fileUrl, "urlName");
246 
247         assertFalse("file and URL cids should be different even for same resource",
248                 fileCid.equals(urlCid));
249     }
250 
251     public void testEmbedDataSource() throws Exception
252     {
253         File tmpFile = File.createTempFile("testEmbedDataSource", "txt");
254         tmpFile.deleteOnExit();
255         FileDataSource dataSource = new FileDataSource(tmpFile);
256 
257         // does embedding a datasource without a name fail?
258         try
259         {
260             this.email.embed(dataSource, "");
261             fail("embedding with an empty string for a name should fail");
262         }
263         catch (EmailException e)
264         {
265             // expected
266         }
267 
268         // properly embed the datasource
269         String cid = this.email.embed(dataSource, "testname");
270 
271         // does embedding the same datasource under the same name return
272         // the original cid?
273         String sameCid = this.email.embed(dataSource, "testname");
274         assertEquals("didn't get same CID for embedding same datasource twice",
275                 cid, sameCid);
276 
277         // does embedding another datasource under the same name fail?
278         File anotherFile = File.createTempFile("testEmbedDataSource2", "txt");
279         anotherFile.deleteOnExit();
280         FileDataSource anotherDS = new FileDataSource(anotherFile);
281         try
282         {
283             this.email.embed(anotherDS, "testname");
284         }
285         catch (EmailException e)
286         {
287             // expected
288         }
289     }
290 
291     /**
292      * @throws EmailException when bad addresses and attachments are used
293      * @throws IOException if creating a temp file, URL or sending fails
294      */
295     public void testSend() throws EmailException, IOException
296     {
297         EmailAttachment attachment = new EmailAttachment();
298         File testFile = null;
299 
300         /** File to used to test file attachments (Must be valid) */
301         testFile = File.createTempFile("commons-email-testfile", ".txt");
302         testFile.deleteOnExit();
303 
304         // ====================================================================
305         // Test Success
306         // ====================================================================
307         this.getMailServer();
308 
309         String strSubject = "Test HTML Send #1 Subject (w charset)";
310 
311         this.email = new MockHtmlEmailConcrete();
312         this.email.setHostName(this.strTestMailServer);
313         this.email.setSmtpPort(this.getMailServerPort());
314         this.email.setFrom(this.strTestMailFrom);
315         this.email.addTo(this.strTestMailTo);
316 
317         /** File to used to test file attachmetns (Must be valid) */
318         attachment.setName("Test Attachment");
319         attachment.setDescription("Test Attachment Desc");
320         attachment.setPath(testFile.getAbsolutePath());
321         this.email.attach(attachment);
322 
323         this.email.setAuthentication(this.strTestUser, this.strTestPasswd);
324 
325         this.email.setCharset(Email.ISO_8859_1);
326         this.email.setSubject(strSubject);
327 
328         URL url = new URL(EmailConfiguration.TEST_URL);
329         String cid = this.email.embed(url, "Apache Logo");
330 
331         String strHtmlMsg =
332             "<html>The Apache logo - <img src=\"cid:" + cid + "\"><html>";
333 
334         this.email.setHtmlMsg(strHtmlMsg);
335         this.email.setTextMsg(
336             "Your email client does not support HTML emails");
337 
338         this.email.send();
339         this.fakeMailServer.stop();
340         // validate txt message
341         validateSend(
342             this.fakeMailServer,
343             strSubject,
344             this.email.getTextMsg(),
345             this.email.getFromAddress(),
346             this.email.getToList(),
347             this.email.getCcList(),
348             this.email.getBccList(),
349             true);
350 
351         // validate html message
352         validateSend(
353             this.fakeMailServer,
354             strSubject,
355             this.email.getHtmlMsg(),
356             this.email.getFromAddress(),
357             this.email.getToList(),
358             this.email.getCcList(),
359             this.email.getBccList(),
360             false);
361 
362         // validate attachment
363         validateSend(
364             this.fakeMailServer,
365             strSubject,
366             attachment.getName(),
367             this.email.getFromAddress(),
368             this.email.getToList(),
369             this.email.getCcList(),
370             this.email.getBccList(),
371             false);
372 
373         this.getMailServer();
374 
375         this.email = new MockHtmlEmailConcrete();
376         this.email.setHostName(this.strTestMailServer);
377         this.email.setSmtpPort(this.getMailServerPort());
378         this.email.setFrom(this.strTestMailFrom);
379         this.email.addTo(this.strTestMailTo);
380 
381         if (this.strTestUser != null && this.strTestPasswd != null)
382         {
383             this.email.setAuthentication(
384                 this.strTestUser,
385                 this.strTestPasswd);
386         }
387 
388         strSubject = "Test HTML Send #1 Subject (wo charset)";
389         this.email.setSubject(strSubject);
390         this.email.setTextMsg("Test message");
391 
392         this.email.send();
393         this.fakeMailServer.stop();
394         // validate txt message
395         validateSend(
396             this.fakeMailServer,
397             strSubject,
398             this.email.getTextMsg(),
399             this.email.getFromAddress(),
400             this.email.getToList(),
401             this.email.getCcList(),
402             this.email.getBccList(),
403             true);
404     }
405 
406     /**
407      *
408      * @throws Exception Exception
409      */
410     public void testSend2() throws Exception
411     {
412         // ====================================================================
413         // Test Success
414         // ====================================================================
415 
416         this.getMailServer();
417 
418         this.email = new MockHtmlEmailConcrete();
419         this.email.setHostName(this.strTestMailServer);
420         this.email.setSmtpPort(this.getMailServerPort());
421         this.email.setFrom(this.strTestMailFrom);
422         this.email.addTo(this.strTestMailTo);
423 
424         if (this.strTestUser != null && this.strTestPasswd != null)
425         {
426             this.email.setAuthentication(
427                 this.strTestUser,
428                 this.strTestPasswd);
429         }
430 
431         String strSubject = "Test HTML Send #2 Subject (wo charset)";
432         this.email.setSubject(strSubject);
433         this.email.setMsg("Test txt msg");
434 
435         this.email.send();
436         this.fakeMailServer.stop();
437         // validate txt message
438         validateSend(
439             this.fakeMailServer,
440             strSubject,
441             this.email.getTextMsg(),
442             this.email.getFromAddress(),
443             this.email.getToList(),
444             this.email.getCcList(),
445             this.email.getBccList(),
446             true);
447 
448         // validate html message
449         validateSend(
450             this.fakeMailServer,
451             strSubject,
452             this.email.getHtmlMsg(),
453             this.email.getFromAddress(),
454             this.email.getToList(),
455             this.email.getCcList(),
456             this.email.getBccList(),
457             false);
458 
459         this.getMailServer();
460 
461         this.email = new MockHtmlEmailConcrete();
462         this.email.setHostName(this.strTestMailServer);
463         this.email.setFrom(this.strTestMailFrom);
464         this.email.setSmtpPort(this.getMailServerPort());
465         this.email.addTo(this.strTestMailTo);
466 
467         if (this.strTestUser != null && this.strTestPasswd != null)
468         {
469             this.email.setAuthentication(
470                 this.strTestUser,
471                 this.strTestPasswd);
472         }
473 
474         strSubject = "Test HTML Send #2 Subject (w charset)";
475         this.email.setCharset(Email.ISO_8859_1);
476         this.email.setSubject(strSubject);
477         this.email.setMsg("Test txt msg");
478 
479         this.email.send();
480         this.fakeMailServer.stop();
481         // validate txt message
482         validateSend(
483             this.fakeMailServer,
484             strSubject,
485             this.email.getTextMsg(),
486             this.email.getFromAddress(),
487             this.email.getToList(),
488             this.email.getCcList(),
489             this.email.getBccList(),
490             true);
491 
492         // validate html message
493         validateSend(
494             this.fakeMailServer,
495             strSubject,
496             this.email.getHtmlMsg(),
497             this.email.getFromAddress(),
498             this.email.getToList(),
499             this.email.getCcList(),
500             this.email.getBccList(),
501             false);
502 
503     }
504 
505 }