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.mail2.jakarta;
18  
19  import static org.junit.jupiter.api.Assertions.assertEquals;
20  import static org.junit.jupiter.api.Assertions.assertThrows;
21  import static org.junit.jupiter.api.Assertions.assertTrue;
22  
23  import java.io.File;
24  import java.io.IOException;
25  import java.net.MalformedURLException;
26  import java.net.URL;
27  import java.nio.file.Path;
28  import java.util.HashMap;
29  import java.util.Map;
30  
31  import org.apache.commons.mail2.core.EmailConstants;
32  import org.apache.commons.mail2.core.EmailException;
33  import org.apache.commons.mail2.core.EmailUtils;
34  import org.apache.commons.mail2.jakarta.mocks.MockMultiPartEmailConcrete;
35  import org.junit.jupiter.api.BeforeEach;
36  import org.junit.jupiter.api.Test;
37  
38  import jakarta.activation.FileDataSource;
39  import jakarta.activation.URLDataSource;
40  import jakarta.mail.internet.MimeMultipart;
41  
42  public class MultiPartEmailTest extends AbstractEmailTest {
43  
44      /** */
45      private MockMultiPartEmailConcrete email;
46  
47      /** File to used to test file attachments (Must be valid) */
48      private File testFile;
49  
50      /** File to used to test file attachments (Must be valid) */
51      private Path testPath;
52  
53      @BeforeEach
54      public void setUpMultiPartEmailTest() throws Exception {
55          // reusable objects to be used across multiple tests
56          email = new MockMultiPartEmailConcrete();
57          testFile = File.createTempFile("testfile", ".txt");
58          testPath = testFile.toPath();
59      }
60  
61      @Test
62      public void testAddPart() throws Exception {
63          // setup
64          email = new MockMultiPartEmailConcrete();
65          final String strMessage = "hello";
66          final String strContentType = "text/plain";
67          // add part
68          email.addPart(strMessage, strContentType);
69          // validate
70          assertEquals(strContentType, email.getContainer().getBodyPart(0).getContentType());
71          assertEquals(strMessage, email.getContainer().getBodyPart(0).getDataHandler().getContent());
72      }
73  
74      @Test
75      public void testAddPart2() throws Exception {
76          // setup
77          email = new MockMultiPartEmailConcrete();
78          final String strSubtype = "subtype/abc123";
79          // add part
80          email.addPart(new MimeMultipart(strSubtype));
81          // validate
82          assertTrue(email.getContainer().getBodyPart(0).getDataHandler().getContentType().contains(strSubtype));
83      }
84  
85      /**
86       * @throws MalformedURLException when a bad attachment URL is used
87       * @throws EmailException        when a bad address or attachment is used
88       */
89      @Test
90      public void testAttach2() throws MalformedURLException, EmailException {
91          // Test Success - URL
92          email.attach(new URL(strTestURL), "Test Attachment", "Test Attachment Desc");
93          // bad name
94          email.attach(new URL(strTestURL), null, "Test Attachment Desc");
95      }
96  
97      @Test
98      public void testAttach3() throws Exception {
99          // Test Success - URL
100         email.attach(new URLDataSource(new URL(strTestURL)), "Test Attachment", "Test Attachment Desc");
101         // Test Exceptions
102         // null datasource
103         assertThrows(EmailException.class, () -> email.attach((URLDataSource) null, "Test Attachment", "Test Attachment Desc"));
104         // invalid datasource
105         assertThrows(EmailException.class, () -> email.attach(new URLDataSource(createInvalidURL()), "Test Attachment", "Test Attachment Desc"));
106     }
107 
108     @Test
109     public void testAttachFile() throws Exception {
110         final EmailAttachment attachment1;
111         // Test Success - EmailAttachment
112         attachment1 = new EmailAttachment();
113         attachment1.setName("Test Attachment");
114         attachment1.setDescription("Test Attachment Desc");
115         attachment1.setPath(testFile.getAbsolutePath());
116         email.attach(attachment1);
117         assertTrue(email.isBoolHasAttachments());
118         // Test Success - URL
119         final EmailAttachment attachment2 = new EmailAttachment();
120         attachment2.setName("Test Attachment");
121         attachment2.setDescription("Test Attachment Desc");
122         attachment2.setURL(new URL(strTestURL));
123         email.attach(attachment2);
124         // Test Success - File
125         email.attach(testFile);
126         assertTrue(email.isBoolHasAttachments());
127         // Test Exceptions
128         // null attachment
129         assertThrows(EmailException.class, () -> email.attach((EmailAttachment) null));
130         // bad url
131         final EmailAttachment attachment3 = new EmailAttachment();
132         attachment3.setURL(createInvalidURL());
133         assertThrows(EmailException.class, () -> email.attach(attachment3));
134 
135         // bad file
136         final EmailAttachment attachment4 = new EmailAttachment();
137         attachment4.setPath("");
138         assertThrows(EmailException.class, () -> email.attach(attachment4));
139     }
140 
141     @Test
142     public void testAttachFileLocking() throws Exception {
143         // EMAIL-120: attaching a FileDataSource may result in a locked file
144         // resource on windows systems
145         final File tmpFile = File.createTempFile("attachment", ".eml");
146         email.attach(new FileDataSource(tmpFile), "Test Attachment", "Test Attachment Desc");
147         assertTrue(tmpFile.delete());
148     }
149 
150     @Test
151     public void testAttachPath() throws Exception {
152         final EmailAttachment attachment1;
153         // Test Success - EmailAttachment
154         attachment1 = new EmailAttachment();
155         attachment1.setName("Test Attachment");
156         attachment1.setDescription("Test Attachment Desc");
157         attachment1.setPath(testPath.toAbsolutePath().toString());
158         email.attach(attachment1);
159         assertTrue(email.isBoolHasAttachments());
160         // Test Success - URL
161         final EmailAttachment attachment2 = new EmailAttachment();
162         attachment2.setName("Test Attachment");
163         attachment2.setDescription("Test Attachment Desc");
164         attachment2.setURL(new URL(strTestURL));
165         email.attach(attachment2);
166         // Test Success - File
167         email.attach(testPath);
168         assertTrue(email.isBoolHasAttachments());
169         // Test Exceptions
170         // null attachment
171         assertThrows(EmailException.class, () -> email.attach((EmailAttachment) null));
172 
173         // bad url
174         final EmailAttachment attachment3 = new EmailAttachment();
175         attachment3.setURL(createInvalidURL());
176         assertThrows(EmailException.class, () -> email.attach(attachment3));
177 
178         // bad file
179         final EmailAttachment attachment4 = new EmailAttachment();
180         attachment4.setPath("");
181         assertThrows(EmailException.class, () -> email.attach(attachment4));
182     }
183 
184     /** TODO implement test for GetContainer */
185     @Test
186     public void testGetContainer() {
187         assertTrue(true);
188     }
189 
190     /** Test get/set sub type */
191     @Test
192     public void testGetSetSubType() {
193         for (final String validChar : testCharsValid) {
194             email.setSubType(validChar);
195             assertEquals(validChar, email.getSubType());
196         }
197     }
198 
199     /** Init called twice should fail */
200     @Test
201     public void testInit() {
202         email.init();
203         // call the init function twice to trigger the IllegalStateException
204         assertThrows(IllegalStateException.class, email::init);
205     }
206 
207     /**
208      * @throws EmailException when a bad address or attachment is used
209      * @throws IOException    when sending fails
210      */
211     @Test
212     public void testSend() throws EmailException, IOException {
213         // Test Success
214         getMailServer();
215 
216         final String strSubject = "Test Multipart Send Subject";
217 
218         final EmailAttachment attachment = new EmailAttachment();
219         attachment.setPath(testFile.getAbsolutePath());
220         attachment.setDisposition(EmailAttachment.ATTACHMENT);
221         attachment.setName("Test_Attachment");
222         attachment.setDescription("Test Attachment Desc");
223 
224         final MockMultiPartEmailConcrete testEmail = new MockMultiPartEmailConcrete();
225         testEmail.setHostName(strTestMailServer);
226         testEmail.setSmtpPort(getMailServerPort());
227         testEmail.setFrom(strTestMailFrom);
228         testEmail.addTo(strTestMailTo);
229         testEmail.attach(attachment);
230         testEmail.setSubType("subType");
231 
232         if (EmailUtils.isNotEmpty(strTestUser) && EmailUtils.isNotEmpty(strTestPasswd)) {
233             testEmail.setAuthentication(strTestUser, strTestPasswd);
234         }
235 
236         testEmail.setSubject(strSubject);
237 
238         testEmail.setMsg("Test Message");
239 
240         final Map<String, String> ht = new HashMap<>();
241         ht.put("X-Priority", "2");
242         ht.put("Disposition-Notification-To", strTestMailFrom);
243         ht.put("X-Mailer", "Sendmail");
244 
245         testEmail.setHeaders(ht);
246 
247         testEmail.send();
248 
249         stopServer();
250         // validate message
251         validateSend(fakeMailServer, strSubject, testEmail.getMsg(), testEmail.getFromAddress(), testEmail.getToAddresses(), testEmail.getCcAddresses(),
252                 testEmail.getBccAddresses(), true);
253 
254         // validate attachment
255         validateSend(fakeMailServer, strSubject, attachment.getName(), testEmail.getFromAddress(), testEmail.getToAddresses(), testEmail.getCcAddresses(),
256                 testEmail.getBccAddresses(), false);
257         // Test Exceptions
258         getMailServer();
259         assertThrows(EmailException.class, email::send);
260     }
261 
262     @Test
263     public void testSetMsg() throws EmailException {
264         // Test Success
265 
266         // without charset set
267         for (final String validChar : testCharsValid) {
268             email.setMsg(validChar);
269             assertEquals(validChar, email.getMsg());
270         }
271 
272         // with charset set
273         email.setCharset(EmailConstants.US_ASCII);
274         for (final String validChar : testCharsValid) {
275             email.setMsg(validChar);
276             assertEquals(validChar, email.getMsg());
277         }
278         // Test Exceptions
279         for (final String invalidChar : testCharsNotValid) {
280             assertThrows(EmailException.class, () -> email.setMsg(invalidChar));
281 
282         }
283     }
284 }