1   /*
2    * Copyright 2001-2005 The Apache Software Foundation
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.apache.commons.mail;
17  
18  import java.io.File;
19  import java.io.FileWriter;
20  import java.io.IOException;
21  import java.util.Date;
22  import java.util.Iterator;
23  import java.util.List;
24  
25  import javax.mail.Multipart;
26  import javax.mail.internet.InternetAddress;
27  
28  import junit.framework.TestCase;
29  
30  import org.apache.commons.mail.settings.EmailConfiguration;
31  
32  import com.dumbster.smtp.SimpleSmtpServer;
33  import com.dumbster.smtp.SmtpMessage;
34  
35  /**
36   * Base test case for Email test classes
37   *
38   * @since 1.0
39   * @author <a href="mailto:corey.scott@gmail.com">Corey Scott</a>
40   * @author <a href="mailto:epugh@opensourceconnections.com">Eric Pugh</a>
41   * @version $Id: BaseEmailTestCase.java 279300 2005-09-07 11:43:52Z henning $
42   */
43  
44  public class BaseEmailTestCase extends TestCase
45  {
46      private static int mailServerPort = EmailConfiguration.MAIL_SERVER_PORT;
47  
48      /** The fake Dumbster email server */
49      protected SimpleSmtpServer fakeMailServer = null;
50  
51      /** Mail server used for testing */
52      protected String strTestMailServer = EmailConfiguration.MAIL_SERVER;
53      /** From address for the test email */
54      protected String strTestMailFrom = EmailConfiguration.TEST_FROM;
55      /** Destination address for the test email */
56      protected String strTestMailTo = EmailConfiguration.TEST_TO;
57      /** Mailserver username (set if needed) */
58      protected String strTestUser = EmailConfiguration.TEST_USER;
59      /** Mailserver strTestPasswd (set if needed) */
60      protected String strTestPasswd = EmailConfiguration.TEST_PASSWD;
61      /** URL to used to test URL attachmetns (Must be valid) */
62      protected String strTestURL = EmailConfiguration.TEST_URL;
63  
64      /** Padding at end of body added by dumbser/send */
65      public static final int BODY_END_PAD = 3;
66      /** Padding at start of body added by dumbser/send */
67      public static final int BODY_START_PAD = 2;
68  
69      /** Where to save email output **/
70      private File emailOutputDir;
71  
72      protected int getMailServerPort()
73      {
74          return mailServerPort;
75      }
76  
77      /** Test characters acceptable to email */
78      protected String[] testCharsValid =
79      {
80              " ",
81              "a",
82              "A",
83              "\uc5ec",
84              "0123456789",
85              "012345678901234567890",
86              "\n"
87      };
88  
89      /** Array of test strings */
90      protected String[] testCharsNotValid = { "", null };
91  
92      /**
93       * @param name name
94       */
95      public BaseEmailTestCase(String name)
96      {
97          super(name);
98          emailOutputDir = new File("target/test-emails");
99          if (!emailOutputDir.exists())
100         {
101             emailOutputDir.mkdirs();
102         }
103     }
104 
105     /** */
106     protected void setUp()
107     {
108 
109     }
110 
111     /** */
112     protected void tearDown()
113     {
114         //stop the fake email server (if started)
115         if (this.fakeMailServer != null && !this.fakeMailServer.isStopped())
116         {
117             this.fakeMailServer.stop();
118             assertTrue(this.fakeMailServer.isStopped());
119         }
120 
121         this.fakeMailServer = null;
122     }
123 
124     /**
125      *
126      * @param email email
127      * @throws IOException Exception
128      */
129     protected void saveEmailToFile(SmtpMessage email) throws IOException
130     {
131         File emailFile =
132             new File(emailOutputDir, "email" + new Date().getTime() + ".txt");
133         FileWriter fw = new FileWriter(emailFile);
134         fw.write(email.toString());
135         fw.close();
136     }
137 
138     /**
139      * @param intMsgNo the message to retrieve
140      * @return message as string
141      */
142     public String getMessageAsString(int intMsgNo)
143     {
144         assertTrue(this.fakeMailServer.getReceivedEmailSize() >= intMsgNo);
145         Iterator emailIter = fakeMailServer.getReceivedEmail();
146         SmtpMessage emailMessage = null;
147         for (int intCurMsg = 0; intCurMsg < intMsgNo; intCurMsg++)
148         {
149             emailMessage = (SmtpMessage) emailIter.next();
150         }
151 
152         if (emailMessage != null)
153         {
154             return emailMessage.toString();
155         }
156         fail("Message note found");
157         return "";
158     }
159 
160     /** */
161     public void getMailServer()
162     {
163         if (this.fakeMailServer == null || this.fakeMailServer.isStopped())
164         {
165             mailServerPort++;
166 
167             this.fakeMailServer =
168                     SimpleSmtpServer.start(getMailServerPort());
169 
170             assertFalse(this.fakeMailServer.isStopped());
171 
172             Date dtStartWait = new Date();
173             while (this.fakeMailServer.isStopped())
174             {
175                 // test for connected
176                 if (this.fakeMailServer != null
177                     && !this.fakeMailServer.isStopped())
178                 {
179                     break;
180                 }
181 
182                 // test for timeout
183                 if ((dtStartWait.getTime() + EmailConfiguration.TIME_OUT)
184                     <= new Date().getTime())
185                 {
186                     fail("Mail server failed to start");
187                 }
188             }
189         }
190     }
191 
192     /**
193      * Validate the message was sent properly
194      * @param mailServer reference to the fake mail server
195      * @param strSubject expected subject
196      * @param fromAdd expected from address
197      * @param toAdd list of expected to addresses
198      * @param ccAdd list of expected cc addresses
199      * @param bccAdd list of expected bcc addresses
200      * @param boolSaveToFile true will output to file, false doesnt
201      * @return SmtpMessage email to check
202      * @throws IOException Exception
203      */
204     protected SmtpMessage validateSend(
205         SimpleSmtpServer mailServer,
206         String strSubject,
207         InternetAddress fromAdd,
208         List toAdd,
209         List ccAdd,
210         List bccAdd,
211         boolean boolSaveToFile)
212         throws IOException
213     {
214         assertTrue(mailServer.getReceivedEmailSize() == 1);
215         Iterator emailIter = fakeMailServer.getReceivedEmail();
216         SmtpMessage emailMessage = (SmtpMessage) emailIter.next();
217 
218         if (boolSaveToFile)
219         {
220             this.saveEmailToFile(emailMessage);
221         }
222 
223         // test subject
224         assertEquals(strSubject, emailMessage.getHeaderValue("Subject"));
225 
226         //test from address
227         assertEquals(fromAdd.toString(), emailMessage.getHeaderValue("From"));
228 
229         //test to address
230         assertTrue(
231             toAdd.toString().indexOf(emailMessage.getHeaderValue("To")) != -1);
232 
233         //test cc address
234         if (ccAdd.size() > 0)
235         {
236             assertTrue(
237                 ccAdd.toString().indexOf(emailMessage.getHeaderValue("Cc"))
238                     != -1);
239         }
240 
241         //test bcc address
242         if (bccAdd.size() > 0)
243         {
244             assertTrue(
245                 bccAdd.toString().indexOf(emailMessage.getHeaderValue("Bcc"))
246                     != -1);
247         }
248 
249         return emailMessage;
250     }
251 
252     /**
253      * Validate the message was sent properly
254      * @param mailServer reference to the fake mail server
255      * @param strSubject expected subject
256      * @param content the expected message content
257      * @param fromAdd expected from address
258      * @param toAdd list of expected to addresses
259      * @param ccAdd list of expected cc addresses
260      * @param bccAdd list of expected bcc addresses
261      * @param boolSaveToFile true will output to file, false doesnt
262      * @throws IOException Exception
263      */
264     protected void validateSend(
265         SimpleSmtpServer mailServer,
266         String strSubject,
267         Multipart content,
268         InternetAddress fromAdd,
269         List toAdd,
270         List ccAdd,
271         List bccAdd,
272         boolean boolSaveToFile)
273         throws IOException
274     {
275         // test other properties
276         SmtpMessage emailMessage = this.validateSend(
277             mailServer,
278             strSubject,
279             fromAdd,
280             toAdd,
281             ccAdd,
282             bccAdd,
283             boolSaveToFile);
284 
285         // test message content
286 
287         // get sent email content
288         String strSentContent =
289             content.getContentType();
290         // get received email content (chop off the auto-added \n
291         // and -- (front and end)
292         String strMessageBody =
293             emailMessage.getBody().substring(
294                 BaseEmailTestCase.BODY_START_PAD,
295                 emailMessage.getBody().length()
296                     - BaseEmailTestCase.BODY_END_PAD);
297         assertTrue(strMessageBody.indexOf(strSentContent) != -1);
298     }
299 
300     /**
301      * Validate the message was sent properly
302      * @param mailServer reference to the fake mail server
303      * @param strSubject expected subject
304      * @param strMessage the expected message as a string
305      * @param fromAdd expected from address
306      * @param toAdd list of expected to addresses
307      * @param ccAdd list of expected cc addresses
308      * @param bccAdd list of expected bcc addresses
309      * @param boolSaveToFile true will output to file, false doesnt
310      * @throws IOException Exception
311      */
312     protected void validateSend(
313         SimpleSmtpServer mailServer,
314         String strSubject,
315         String strMessage,
316         InternetAddress fromAdd,
317         List toAdd,
318         List ccAdd,
319         List bccAdd,
320         boolean boolSaveToFile)
321         throws IOException
322     {
323         // test other properties
324         SmtpMessage emailMessage = this.validateSend(
325             mailServer,
326             strSubject,
327             fromAdd,
328             toAdd,
329             ccAdd,
330             bccAdd,
331             true);
332 
333         // test message content
334         assertTrue(emailMessage.getBody().indexOf(strMessage) != -1);
335     }
336 }