44import jakarta .mail .internet .MimeMessage ;
55import org .apache .poi .poifs .filesystem .DirectoryNode ;
66import org .apache .poi .poifs .filesystem .Entry ;
7+ import org .apache .poi .poifs .filesystem .EntryUtils ;
78import org .apache .poi .poifs .filesystem .POIFSFileSystem ;
89import org .junit .jupiter .api .Test ;
910import org .junit .jupiter .api .io .TempDir ;
1011import org .junit .jupiter .params .ParameterizedTest ;
1112import org .junit .jupiter .params .provider .Arguments ;
1213import org .junit .jupiter .params .provider .MethodSource ;
14+ import org .junit .jupiter .params .provider .ValueSource ;
1315import org .simplejavamail .api .SimpleJavaMail ;
1416import org .simplejavamail .api .converter .ConfiguredEmailConverter .OutlookConversion ;
1517import org .simplejavamail .api .email .AttachmentResource ;
1618import org .simplejavamail .api .email .Email ;
19+ import org .simplejavamail .api .email .EmailProblem ;
20+ import org .simplejavamail .api .email .EmailSourceHeader ;
21+ import org .simplejavamail .api .email .EmailSourcePart ;
1722import org .simplejavamail .api .email .Recipient ;
1823import org .simplejavamail .api .outlook .OutlookEmailConversionResult ;
1924import org .simplejavamail .config .ConfigLoader ;
2025
2126import java .io .ByteArrayInputStream ;
2227import java .io .ByteArrayOutputStream ;
2328import java .io .InputStream ;
29+ import java .io .ObjectInputStream ;
30+ import java .io .ObjectOutputStream ;
2431import java .nio .ByteBuffer ;
2532import java .nio .ByteOrder ;
2633import java .nio .charset .Charset ;
@@ -137,15 +144,198 @@ void nestedMsgReceiptFieldsBelongToTheNestedMessageAndUseTheTypedRoute() throws
137144 }
138145 }
139146
147+ @ ParameterizedTest
148+ @ MethodSource ("uninterpretableNestedFields" )
149+ void nestedAddressRecoveryRetainsTheChildObservationAndSource (final String field , final String value ,
150+ final EmailProblem .Code code ) throws Exception {
151+ final byte [] directMsg = OutlookAddressImportTest .withAddressHeader (field , value );
152+ final Email direct = MAIL .converter ().fromOutlookMsg (new ByteArrayInputStream (directMsg )).toEmail ();
153+ assertThat (direct .getProblems ()).singleElement ().satisfies (problem -> {
154+ assertThat (problem .getCode ()).isEqualTo (code );
155+ assertThat (problem .getLocation ()).isEqualTo (field + "[0]" );
156+ assertThat (problem .getSourceValue ()).isEqualTo (value );
157+ });
158+ final int nestedCount = 1 ;
159+ final String nestedId = "<nested-recovery@example.org>" ;
160+ final String headers = "From: nested@example.org\r \n To: reader@example.org\r \n "
161+ + "Message-ID: " + nestedId + "\r \n " + field + ": " + value + "\r \n "
162+ + "Comments: =?X-NO-SUCH-CHARSET?Q?deliberately_unused?=\r \n " ;
163+ final byte [] msg = nestedMsg (headers );
164+ for (final Email parent : Arrays .asList (MAIL .converter ().fromOutlookMsg (new ByteArrayInputStream (msg )).toEmail (),
165+ EmailConverter .outlookMsgToEmail (new ByteArrayInputStream (msg )))) {
166+ assertNestedRecovery (parent , field , value , code , nestedCount );
167+ final Email copy = MAIL .emailBuilder ().copying (parent ).fixingMessageId ("<copy@example.org>" ).buildEmail ();
168+ assertNestedRecovery (copy , field , value , code , nestedCount );
169+ assertThat (copy .getProblems ()).containsExactlyElementsOf (parent .getProblems ());
170+ assertThat (copy .getSourceData ()).isSameAs (parent .getSourceData ());
171+
172+ final ByteArrayOutputStream serialized = new ByteArrayOutputStream ();
173+ try (ObjectOutputStream output = new ObjectOutputStream (serialized )) { output .writeObject (copy ); }
174+ try (ObjectInputStream input = new ObjectInputStream (new ByteArrayInputStream (serialized .toByteArray ()))) {
175+ final Email restored = (Email ) input .readObject ();
176+ assertNestedRecovery (restored , field , value , code , nestedCount );
177+ assertThat (restored .getProblems ()).extracting (problem -> problem .getOrigin ().getReference ())
178+ .containsExactlyElementsOf (parent .getProblems ().stream ().map (problem -> problem .getOrigin ().getReference ())
179+ .collect (java .util .stream .Collectors .toList ()));
180+ }
181+ assertThat (parent .getPlainText ()).isNotEmpty ();
182+ assertThat (parent .getDispositionNotificationToRecipients ()).isEmpty ();
183+ assertThat (parent .getReturnReceiptToRecipients ()).isEmpty ();
184+ assertThat (parent .getAttachments ()).anySatisfy (attachment ->
185+ assertThat (attachment .getDataSource ().getContentType ()).startsWith ("message/rfc822" ));
186+ }
187+ }
188+
189+ static Stream <Arguments > uninterpretableNestedFields () {
190+ return Stream .of ("Disposition-Notification-To" , "Return-Receipt-To" , "Return-Path" ).flatMap (field -> Stream .of (
191+ Arguments .of (field , "," , EmailProblem .Code .FIELD_NOT_INTERPRETED ),
192+ Arguments .of (field , "=?X-NO-SUCH-CHARSET?Q?Name?= <receipt@example.org>" , EmailProblem .Code .VALUE_NOT_DECODED )));
193+ }
194+
195+ @ ParameterizedTest
196+ @ ValueSource (strings = {"Disposition-Notification-To" , "Return-Receipt-To" , "Return-Path" })
197+ void nestedLenientAddressInterpretationRetainsTheExistingNoProblemPolicy (final String field ) throws Exception {
198+ final String value = "broken <address" ;
199+ final byte [] direct = OutlookAddressImportTest .withAddressHeader (field , value );
200+ assertThat (MAIL .converter ().fromOutlookMsg (new ByteArrayInputStream (direct )).toEmail ().getProblems ()).isEmpty ();
201+ final byte [] msg = nestedMsg ("From: nested@example.org\r \n To: reader@example.org\r \n " + field + ": " + value + "\r \n " );
202+ final Email parent = MAIL .converter ().fromOutlookMsg (new ByteArrayInputStream (msg )).toEmail ();
203+ assertThat (parent .getProblems ()).isEmpty ();
204+ for (AttachmentResource attachment : parent .getAttachments ()) {
205+ if (attachment .getDataSource ().getContentType ().startsWith ("message/rfc822" )) {
206+ final MimeMessage nested = MAIL .converter ().fromEml (attachment .readAllBytes ()).toMimeMessage ();
207+ assertThat (nested .getHeader (field , null )).contains (value );
208+ }
209+ }
210+ }
211+
212+ @ Test
213+ void anUnselectedNestedReplyToRemainsSourceEvidenceWithoutAnObservation () throws Exception {
214+ final String value = "=?X-NO-SUCH-CHARSET?Q?Name?= <reply@example.org>" ;
215+ final byte [] msg = nestedMsg ("From: nested@example.org\r \n To: reader@example.org\r \n Reply-To: " + value + "\r \n " );
216+ final Email parent = MAIL .converter ().fromOutlookMsg (new ByteArrayInputStream (msg )).toEmail ();
217+ assertThat (parent .getProblems ()).isEmpty ();
218+ final List <EmailSourceHeader > captured = new ArrayList <>();
219+ for (EmailSourcePart part : parent .getSourceData ().getParts ()) collectHeaders (part , captured );
220+ assertThat (captured ).anySatisfy (header -> {
221+ assertThat (header .getName ()).isEqualTo ("Reply-To" );
222+ assertThat (header .getRawValue ()).isEqualTo (value );
223+ });
224+ for (AttachmentResource attachment : parent .getAttachments ()) {
225+ if (attachment .getDataSource ().getContentType ().startsWith ("message/rfc822" )) {
226+ final MimeMessage nested = MAIL .converter ().fromEml (attachment .readAllBytes ()).toMimeMessage ();
227+ assertThat (nested .getHeader ("Reply-To" , null )).isNull ();
228+ }
229+ }
230+ }
231+
232+ @ ParameterizedTest
233+ @ ValueSource (booleans = {false , true })
234+ void siblingAndDeeperRecoveriesKeepDistinctOriginsEvenWhenMessageIdsAreAbsentOrEqual (final boolean withId ) throws Exception {
235+ final byte [] msg ;
236+ final String sharedId = withId ? "<shared-nested@example.org>" : null ;
237+ final String field = "Disposition-Notification-To" ;
238+ try (InputStream input = getFixture (); InputStream templateInput = getFixture ();
239+ POIFSFileSystem file = new POIFSFileSystem (input ); POIFSFileSystem template = new POIFSFileSystem (templateInput )) {
240+ final DirectoryNode firstAttachment = attachedMessage (file .getRoot ());
241+ final DirectoryNode firstChild = (DirectoryNode ) firstAttachment .getEntry ("__substg1.0_3701000D" );
242+ final DirectoryNode originalAttachment = attachedMessage (template .getRoot ());
243+ copyAttachment (originalAttachment , file .getRoot (), "__attach_version1.0_#0000F001" );
244+ copyAttachment (originalAttachment , firstChild , "__attach_version1.0_#0000F002" );
245+ final String headers = "From: nested@example.org\r \n To: reader@example.org\r \n "
246+ + (withId ? "Message-ID: " + sharedId + "\r \n " : "" ) + field + ": ,\r \n " ;
247+ assertThat (replaceNestedHeaders (file .getRoot (), true , headers )).isEqualTo (3 );
248+ replaceNestedIds (file .getRoot (), sharedId );
249+ final ByteArrayOutputStream output = new ByteArrayOutputStream ();
250+ file .writeFilesystem (output );
251+ msg = output .toByteArray ();
252+ }
253+ final Email parent = MAIL .converter ().fromOutlookMsg (new ByteArrayInputStream (msg )).toEmail ();
254+ assertNestedRecovery (parent , field , "," , EmailProblem .Code .FIELD_NOT_INTERPRETED , 3 );
255+ assertThat (parent .getProblems ()).extracting (problem -> problem .getOrigin ().getReference ()).doesNotHaveDuplicates ();
256+ assertThat (parent .getProblems ()).extracting (EmailProblem ::getLocation ).doesNotHaveDuplicates ();
257+ assertThat (parent .getProblems ()).extracting (problem -> problem .getOrigin ().getMessageId ())
258+ .containsExactly (sharedId , sharedId , sharedId );
259+ assertThat (parent .getProblems ()).anySatisfy (problem ->
260+ assertThat (problem .getLocation ().split ("/message/" , -1 )).hasSize (3 ));
261+ }
262+
263+ private static InputStream getFixture () {
264+ return OutlookReceiptHeaderRoutesTest .class .getResourceAsStream ("/test-messages/#298 Email with nested msg.msg" );
265+ }
266+
267+ private static byte [] nestedMsg (final String headers ) throws Exception {
268+ try (InputStream input = getFixture (); POIFSFileSystem file = new POIFSFileSystem (input )) {
269+ assertThat (replaceNestedHeaders (file .getRoot (), true , headers )).isEqualTo (1 );
270+ final ByteArrayOutputStream output = new ByteArrayOutputStream ();
271+ file .writeFilesystem (output );
272+ return output .toByteArray ();
273+ }
274+ }
275+
276+ private static DirectoryNode attachedMessage (final DirectoryNode node ) throws Exception {
277+ for (Entry entry : node ) {
278+ if (entry .isDirectoryEntry () && ((DirectoryNode ) entry ).hasEntry ("__substg1.0_3701000D" )) return (DirectoryNode ) entry ;
279+ }
280+ throw new AssertionError ("The fixture must contain an embedded MSG" );
281+ }
282+
283+ private static void copyAttachment (final DirectoryNode source , final DirectoryNode target , final String name ) throws Exception {
284+ final DirectoryNode copied = (DirectoryNode ) target .createDirectory (name );
285+ for (Entry entry : source ) EntryUtils .copyNodeRecursively (entry , copied );
286+ }
287+
288+ private static void replaceNestedIds (final DirectoryNode node , final String id ) throws Exception {
289+ if ("__substg1.0_3701000D" .equalsIgnoreCase (node .getName ())) {
290+ for (String type : List .of ("001E" , "001F" )) {
291+ final String name = "__substg1.0_1035" + type ;
292+ if (node .hasEntry (name )) node .getEntry (name ).delete ();
293+ }
294+ if (id != null ) node .createDocument ("__substg1.0_1035001F" ,
295+ new ByteArrayInputStream ((id + '\0' ).getBytes (StandardCharsets .UTF_16LE )));
296+ }
297+ for (Entry entry : node ) if (entry .isDirectoryEntry ()) replaceNestedIds ((DirectoryNode ) entry , id );
298+ }
299+
300+ private static void assertNestedRecovery (final Email parent , final String field , final String value ,
301+ final EmailProblem .Code code , final int count ) {
302+ assertThat (parent .getProblems ()).hasSize (count );
303+ final List <EmailSourceHeader > headers = new ArrayList <>();
304+ for (EmailSourcePart part : parent .getSourceData ().getParts ()) collectHeaders (part , headers );
305+ for (EmailProblem problem : parent .getProblems ()) {
306+ assertThat (problem .getOperation ()).isEqualTo (EmailProblem .Operation .IMPORT );
307+ assertThat (problem .getCode ()).isEqualTo (code );
308+ assertThat (problem .getLocation ()).startsWith ("source/parts[" ).endsWith ("/message/" + field + "[0]" );
309+ assertThat (problem .getSourceValue ()).isEqualTo (value );
310+ assertThat (problem .getOrigin ().getReference ()).isNotEqualTo (parent .getSourceData ().getOrigin ().getReference ());
311+ assertThat (problem .getSources ()).singleElement ().satisfies (source -> {
312+ assertThat (source ).isInstanceOf (EmailSourceHeader .class );
313+ final EmailSourceHeader header = (EmailSourceHeader ) source ;
314+ assertThat (header .getName ()).isEqualTo (field );
315+ assertThat (header .getRawValue ()).isEqualTo (value );
316+ assertThat (header .getOrigin ()).isSameAs (problem .getOrigin ());
317+ assertThat (headers ).anySatisfy (captured -> assertThat (captured ).isSameAs (header ));
318+ });
319+ }
320+ }
321+
322+ private static void collectHeaders (final EmailSourcePart part , final List <EmailSourceHeader > target ) {
323+ target .addAll (part .getHeaders ());
324+ for (EmailSourcePart child : part .getChildren ()) collectHeaders (child , target );
325+ }
326+
140327 private static int replaceNestedHeaders (final DirectoryNode node , final boolean root ) throws Exception {
328+ return replaceNestedHeaders (node , root , "From: nested@example.org\r \n To: reader@example.org\r \n "
329+ + "disposition-notification-to: nested-receipt@example.org\r \n "
330+ + "rEtUrN-rEcEiPt-To: nested-return@example.org\r \n " );
331+ }
332+
333+ private static int replaceNestedHeaders (final DirectoryNode node , final boolean root , final String headers ) throws Exception {
141334 int replaced = 0 ;
142335 if (!root && "__substg1.0_3701000D" .equalsIgnoreCase (node .getName ())) {
143336 final String type = node .hasEntry ("__substg1.0_007D001E" ) ? "001E" : "001F" ;
144337 final String stream = "__substg1.0_007D" + type ;
145338 final Charset charset = "001F" .equals (type ) ? StandardCharsets .UTF_16LE : StandardCharsets .ISO_8859_1 ;
146- final String headers = "From: nested@example.org\r \n To: reader@example.org\r \n "
147- + "disposition-notification-to: nested-receipt@example.org\r \n "
148- + "rEtUrN-rEcEiPt-To: nested-return@example.org\r \n " ;
149339 final byte [] encoded = (headers + '\0' ).getBytes (charset );
150340 node .createOrUpdateDocument (stream , new ByteArrayInputStream (encoded ));
151341 final byte [] originalProperties ;
@@ -169,7 +359,7 @@ private static int replaceNestedHeaders(final DirectoryNode node, final boolean
169359 replaced ++;
170360 }
171361 for (final Entry entry : node ) {
172- if (entry .isDirectoryEntry ()) replaced += replaceNestedHeaders ((DirectoryNode ) entry , false );
362+ if (entry .isDirectoryEntry ()) replaced += replaceNestedHeaders ((DirectoryNode ) entry , false , headers );
173363 }
174364 return replaced ;
175365 }
0 commit comments