-
Notifications
You must be signed in to change notification settings - Fork 101
/
MimeBodyPart.java
1743 lines (1610 loc) · 58.3 KB
/
MimeBodyPart.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1997, 2023 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package jakarta.mail.internet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.activation.DataHandler;
import jakarta.activation.DataSource;
import jakarta.activation.FileDataSource;
import jakarta.mail.BodyPart;
import jakarta.mail.EncodingAware;
import jakarta.mail.FolderClosedException;
import jakarta.mail.Header;
import jakarta.mail.IllegalWriteException;
import jakarta.mail.Message;
import jakarta.mail.MessageRemovedException;
import jakarta.mail.MessagingException;
import jakarta.mail.Multipart;
import jakarta.mail.Part;
import jakarta.mail.Session;
import jakarta.mail.util.LineOutputStream;
import jakarta.mail.util.StreamProvider;
import jakarta.mail.util.StreamProvider.EncoderTypes;
/**
* This class represents a MIME body part. It implements the
* <code>BodyPart</code> abstract class and the <code>MimePart</code>
* interface. MimeBodyParts are contained in <code>MimeMultipart</code>
* objects. <p>
*
* MimeBodyPart uses the <code>InternetHeaders</code> class to parse
* and store the headers of that body part.
*
* <hr><strong>A note on RFC 822 and MIME headers</strong><p>
*
* RFC 822 header fields <strong>must</strong> contain only
* US-ASCII characters. MIME allows non ASCII characters to be present
* in certain portions of certain headers, by encoding those characters.
* RFC 2047 specifies the rules for doing this. The MimeUtility
* class provided in this package can be used to to achieve this.
* Callers of the <code>setHeader</code>, <code>addHeader</code>, and
* <code>addHeaderLine</code> methods are responsible for enforcing
* the MIME requirements for the specified headers. In addition, these
* header fields must be folded (wrapped) before being sent if they
* exceed the line length limitation for the transport (1000 bytes for
* SMTP). Received headers may have been folded. The application is
* responsible for folding and unfolding headers as appropriate.
*
* @author John Mani
* @author Bill Shannon
* @author Kanwar Oberoi
* @see jakarta.mail.Part
* @see jakarta.mail.internet.MimePart
* @see jakarta.mail.internet.MimeUtility
*/
public class MimeBodyPart extends BodyPart implements MimePart {
// Paranoia:
// allow this last minute change to be disabled if it causes problems
private static final boolean setDefaultTextCharset =
MimeUtility.getBooleanSystemProperty(
"mail.mime.setdefaulttextcharset", true);
private static final boolean setContentTypeFileName =
MimeUtility.getBooleanSystemProperty(
"mail.mime.setcontenttypefilename", true);
private static final boolean encodeFileName =
MimeUtility.getBooleanSystemProperty("mail.mime.encodefilename", false);
private static final boolean decodeFileName =
MimeUtility.getBooleanSystemProperty("mail.mime.decodefilename", false);
private static final boolean ignoreMultipartEncoding =
MimeUtility.getBooleanSystemProperty(
"mail.mime.ignoremultipartencoding", true);
private static final boolean allowutf8 =
MimeUtility.getBooleanSystemProperty("mail.mime.allowutf8", true);
// Paranoia:
// allow this last minute change to be disabled if it causes problems
static final boolean cacheMultipart = // accessed by MimeMessage
MimeUtility.getBooleanSystemProperty("mail.mime.cachemultipart", true);
/**
* The DataHandler object representing this Part's content.
*/
protected DataHandler dh;
/**
* Byte array that holds the bytes of the content of this Part.
*/
protected byte[] content;
/**
* If the data for this body part was supplied by an
* InputStream that implements the SharedInputStream interface,
* <code>contentStream</code> is another such stream representing
* the content of this body part. In this case, <code>content</code>
* will be null.
*
* @since JavaMail 1.2
*/
protected InputStream contentStream;
/**
* The InternetHeaders object that stores all the headers
* of this body part.
*/
protected InternetHeaders headers;
/**
* If our content is a Multipart of Message object, we save it
* the first time it's created by parsing a stream so that changes
* to the contained objects will not be lost.
*
* If this field is not null, it's return by the {@link #getContent}
* method. The {@link #getContent} method sets this field if it
* would return a Multipart or MimeMessage object. This field is
* is cleared by the {@link #setDataHandler} method.
*
* @since JavaMail 1.5
*/
protected Object cachedContent;
/**
* An empty MimeBodyPart object is created.
* This body part maybe filled in by a client constructing a multipart
* message.
*/
public MimeBodyPart() {
super();
headers = new InternetHeaders();
}
/**
* Constructs a MimeBodyPart by reading and parsing the data from
* the specified input stream. The parser consumes data till the end
* of the given input stream. The input stream must start at the
* beginning of a valid MIME body part and must terminate at the end
* of that body part. <p>
*
* Note that the "boundary" string that delimits body parts must
* <strong>not</strong> be included in the input stream. The intention
* is that the MimeMultipart parser will extract each body part's bytes
* from a multipart stream and feed them into this constructor, without
* the delimiter strings.
*
* @param is the body part Input Stream
* @exception MessagingException for failures
*/
public MimeBodyPart(InputStream is) throws MessagingException {
if (!(is instanceof ByteArrayInputStream) &&
!(is instanceof BufferedInputStream) &&
!(is instanceof SharedInputStream))
is = new BufferedInputStream(is);
headers = new InternetHeaders(is);
if (is instanceof SharedInputStream) {
SharedInputStream sis = (SharedInputStream)is;
contentStream = sis.newStream(sis.getPosition(), -1);
} else {
try {
content = MimeUtility.getBytes(is);
} catch (IOException ioex) {
throw new MessagingException("Error reading input stream", ioex);
}
}
}
/**
* Constructs a MimeBodyPart using the given header and
* content bytes. <p>
*
* Used by providers.
*
* @param headers The header of this part
* @param content bytes representing the body of this part.
* @exception MessagingException for failures
*/
public MimeBodyPart(InternetHeaders headers, byte[] content)
throws MessagingException {
super();
this.headers = headers;
this.content = content;
}
/**
* Return the size of the content of this body part in bytes.
* Return -1 if the size cannot be determined. <p>
*
* Note that this number may not be an exact measure of the
* content size and may or may not account for any transfer
* encoding of the content. <p>
*
* This implementation returns the size of the <code>content</code>
* array (if not null), or, if <code>contentStream</code> is not
* null, and the <code>available</code> method returns a positive
* number, it returns that number as the size. Otherwise, it returns
* -1.
*
* @return size in bytes, or -1 if not known
*/
@Override
public int getSize() throws MessagingException {
if (content != null)
return content.length;
if (contentStream != null) {
try {
int size = contentStream.available();
// only believe the size if it's greate than zero, since zero
// is the default returned by the InputStream class itself
if (size > 0)
return size;
} catch (IOException ex) {
// ignore it
}
}
return -1;
}
/**
* Return the number of lines for the content of this Part.
* Return -1 if this number cannot be determined. <p>
*
* Note that this number may not be an exact measure of the
* content length and may or may not account for any transfer
* encoding of the content. <p>
*
* This implementation returns -1.
*
* @return number of lines, or -1 if not known
*/
@Override
public int getLineCount() throws MessagingException {
return -1;
}
/**
* Returns the value of the RFC 822 "Content-Type" header field.
* This represents the content type of the content of this
* body part. This value must not be null. If this field is
* unavailable, "text/plain" should be returned. <p>
*
* This implementation uses <code>getHeader(name)</code>
* to obtain the requisite header field.
*
* @return Content-Type of this body part
*/
@Override
public String getContentType() throws MessagingException {
String s = getHeader("Content-Type", null);
s = MimeUtil.cleanContentType(this, s);
if (s == null)
s = "text/plain";
return s;
}
/**
* Is this Part of the specified MIME type? This method
* compares <strong>only the <code>primaryType</code> and
* <code>subType</code></strong>.
* The parameters of the content types are ignored. <p>
*
* For example, this method will return <code>true</code> when
* comparing a Part of content type <strong>"text/plain"</strong>
* with <strong>"text/plain; charset=foobar"</strong>. <p>
*
* If the <code>subType</code> of <code>mimeType</code> is the
* special character '*', then the subtype is ignored during the
* comparison.
*
* @exception MessagingException for failures
*/
@Override
public boolean isMimeType(String mimeType) throws MessagingException {
return isMimeType(this, mimeType);
}
/**
* Returns the disposition from the "Content-Disposition" header field.
* This represents the disposition of this part. The disposition
* describes how the part should be presented to the user. <p>
*
* If the Content-Disposition field is unavailable,
* null is returned. <p>
*
* This implementation uses <code>getHeader(name)</code>
* to obtain the requisite header field.
*
* @exception MessagingException for failures
* @see #headers
*/
@Override
public String getDisposition() throws MessagingException {
return getDisposition(this);
}
/**
* Set the disposition in the "Content-Disposition" header field
* of this body part. If the disposition is null, any existing
* "Content-Disposition" header field is removed.
*
* @exception IllegalWriteException if the underlying
* implementation does not support modification
* @exception IllegalStateException if this body part is
* obtained from a READ_ONLY folder.
* @exception MessagingException for other failures
*/
@Override
public void setDisposition(String disposition) throws MessagingException {
setDisposition(this, disposition);
}
/**
* Returns the content transfer encoding from the
* "Content-Transfer-Encoding" header
* field. Returns <code>null</code> if the header is unavailable
* or its value is absent. <p>
*
* This implementation uses <code>getHeader(name)</code>
* to obtain the requisite header field.
*
* @see #headers
*/
@Override
public String getEncoding() throws MessagingException {
return getEncoding(this);
}
/**
* Returns the value of the "Content-ID" header field. Returns
* <code>null</code> if the field is unavailable or its value is
* absent. <p>
*
* This implementation uses <code>getHeader(name)</code>
* to obtain the requisite header field.
*/
@Override
public String getContentID() throws MessagingException {
return getHeader("Content-Id", null);
}
/**
* Set the "Content-ID" header field of this body part.
* If the <code>cid</code> parameter is null, any existing
* "Content-ID" is removed.
*
* @param cid the Content-ID
* @exception IllegalWriteException if the underlying
* implementation does not support modification
* @exception IllegalStateException if this body part is
* obtained from a READ_ONLY folder.
* @exception MessagingException for other failures
* @since JavaMail 1.3
*/
public void setContentID(String cid) throws MessagingException {
if (cid == null)
removeHeader("Content-ID");
else
setHeader("Content-ID", cid);
}
/**
* Return the value of the "Content-MD5" header field. Returns
* <code>null</code> if this field is unavailable or its value
* is absent. <p>
*
* This implementation uses <code>getHeader(name)</code>
* to obtain the requisite header field.
*/
@Override
public String getContentMD5() throws MessagingException {
return getHeader("Content-MD5", null);
}
/**
* Set the "Content-MD5" header field of this body part.
*
* @exception IllegalWriteException if the underlying
* implementation does not support modification
* @exception IllegalStateException if this body part is
* obtained from a READ_ONLY folder.
*/
@Override
public void setContentMD5(String md5) throws MessagingException {
setHeader("Content-MD5", md5);
}
/**
* Get the languages specified in the Content-Language header
* of this MimePart. The Content-Language header is defined by
* RFC 1766. Returns <code>null</code> if this header is not
* available or its value is absent. <p>
*
* This implementation uses <code>getHeader(name)</code>
* to obtain the requisite header field.
*/
@Override
public String[] getContentLanguage() throws MessagingException {
return getContentLanguage(this);
}
/**
* Set the Content-Language header of this MimePart. The
* Content-Language header is defined by RFC 1766.
*
* @param languages array of language tags
*/
@Override
public void setContentLanguage(String[] languages)
throws MessagingException {
setContentLanguage(this, languages);
}
/**
* Returns the "Content-Description" header field of this body part.
* This typically associates some descriptive information with
* this part. Returns null if this field is unavailable or its
* value is absent. <p>
*
* If the Content-Description field is encoded as per RFC 2047,
* it is decoded and converted into Unicode. If the decoding or
* conversion fails, the raw data is returned as is. <p>
*
* This implementation uses <code>getHeader(name)</code>
* to obtain the requisite header field.
*
* @return content description
*/
@Override
public String getDescription() throws MessagingException {
return getDescription(this);
}
/**
* Set the "Content-Description" header field for this body part.
* If the description parameter is <code>null</code>, then any
* existing "Content-Description" fields are removed. <p>
*
* If the description contains non US-ASCII characters, it will
* be encoded using the platform's default charset. If the
* description contains only US-ASCII characters, no encoding
* is done and it is used as is. <p>
*
* Note that if the charset encoding process fails, a
* MessagingException is thrown, and an UnsupportedEncodingException
* is included in the chain of nested exceptions within the
* MessagingException.
*
* @param description content description
* @exception IllegalWriteException if the underlying
* implementation does not support modification
* @exception IllegalStateException if this body part is
* obtained from a READ_ONLY folder.
* @exception MessagingException otherwise; an
* UnsupportedEncodingException may be included
* in the exception chain if the charset
* conversion fails.
*/
@Override
public void setDescription(String description) throws MessagingException {
setDescription(description, null);
}
/**
* Set the "Content-Description" header field for this body part.
* If the description parameter is <code>null</code>, then any
* existing "Content-Description" fields are removed. <p>
*
* If the description contains non US-ASCII characters, it will
* be encoded using the specified charset. If the description
* contains only US-ASCII characters, no encoding is done and
* it is used as is. <p>
*
* Note that if the charset encoding process fails, a
* MessagingException is thrown, and an UnsupportedEncodingException
* is included in the chain of nested exceptions within the
* MessagingException.
*
* @param description Description
* @param charset Charset for encoding
* @exception IllegalWriteException if the underlying
* implementation does not support modification
* @exception IllegalStateException if this body part is
* obtained from a READ_ONLY folder.
* @exception MessagingException otherwise; an
* UnsupportedEncodingException may be included
* in the exception chain if the charset
* conversion fails.
*/
public void setDescription(String description, String charset)
throws MessagingException {
setDescription(this, description, charset);
}
/**
* Get the filename associated with this body part. <p>
*
* Returns the value of the "filename" parameter from the
* "Content-Disposition" header field of this body part. If its
* not available, returns the value of the "name" parameter from
* the "Content-Type" header field of this body part.
* Returns <code>null</code> if both are absent. <p>
*
* If the <code>mail.mime.decodefilename</code> System property
* is set to true, the {@link MimeUtility#decodeText
* MimeUtility.decodeText} method will be used to decode the
* filename. While such encoding is not supported by the MIME
* spec, many mailers use this technique to support non-ASCII
* characters in filenames. The default value of this property
* is false.
*
* @return filename
*/
@Override
public String getFileName() throws MessagingException {
return getFileName(this);
}
/**
* Set the filename associated with this body part, if possible. <p>
*
* Sets the "filename" parameter of the "Content-Disposition"
* header field of this body part. For compatibility with older
* mailers, the "name" parameter of the "Content-Type" header is
* also set. <p>
*
* If the <code>mail.mime.encodefilename</code> System property
* is set to true, the {@link MimeUtility#encodeText
* MimeUtility.encodeText} method will be used to encode the
* filename. While such encoding is not supported by the MIME
* spec, many mailers use this technique to support non-ASCII
* characters in filenames. The default value of this property
* is false.
*
* @param filename the file name
* @exception IllegalWriteException if the underlying
* implementation does not support modification
* @exception IllegalStateException if this body part is
* obtained from a READ_ONLY folder.
* @exception MessagingException for other failures
*/
@Override
public void setFileName(String filename) throws MessagingException {
setFileName(this, filename);
}
/**
* Return a decoded input stream for this body part's "content". <p>
*
* This implementation obtains the input stream from the DataHandler.
* That is, it invokes getDataHandler().getInputStream();
*
* @return an InputStream
* @exception IOException this is typically thrown by the
* DataHandler. Refer to the documentation for
* jakarta.activation.DataHandler for more details.
* @exception MessagingException for other failures
*
* @see #getContentStream
* @see jakarta.activation.DataHandler#getInputStream
*/
@Override
public InputStream getInputStream()
throws IOException, MessagingException {
return getDataHandler().getInputStream();
}
/**
* Produce the raw bytes of the content. This method is used
* when creating a DataHandler object for the content. Subclasses
* that can provide a separate input stream for just the Part
* content might want to override this method.
*
* @return an InputStream containing the raw bytes
* @exception MessagingException for failures
* @see #content
* @see MimeMessage#getContentStream
*/
protected InputStream getContentStream() throws MessagingException {
if (contentStream != null)
return ((SharedInputStream)contentStream).newStream(0, -1);
if (content != null)
return new ByteArrayInputStream(content);
throw new MessagingException("No MimeBodyPart content");
}
/**
* Return an InputStream to the raw data with any Content-Transfer-Encoding
* intact. This method is useful if the "Content-Transfer-Encoding"
* header is incorrect or corrupt, which would prevent the
* <code>getInputStream</code> method or <code>getContent</code> method
* from returning the correct data. In such a case the application may
* use this method and attempt to decode the raw data itself. <p>
*
* This implementation simply calls the <code>getContentStream</code>
* method.
*
* @return an InputStream containing the raw bytes
* @exception MessagingException for failures
* @see #getInputStream
* @see #getContentStream
* @since JavaMail 1.2
*/
public InputStream getRawInputStream() throws MessagingException {
return getContentStream();
}
/**
* Return a DataHandler for this body part's content. <p>
*
* The implementation provided here works just like the
* the implementation in MimeMessage.
* @see MimeMessage#getDataHandler
*/
@Override
public DataHandler getDataHandler() throws MessagingException {
if (dh == null)
dh = new MimePartDataHandler(this);
return dh;
}
/**
* Return the content as a Java object. The type of the object
* returned is of course dependent on the content itself. For
* example, the native format of a text/plain content is usually
* a String object. The native format for a "multipart"
* content is always a Multipart subclass. For content types that are
* unknown to the DataHandler system, an input stream is returned
* as the content. <p>
*
* This implementation obtains the content from the DataHandler.
* That is, it invokes getDataHandler().getContent();
* If the content is a Multipart or Message object and was created by
* parsing a stream, the object is cached and returned in subsequent
* calls so that modifications to the content will not be lost.
*
* @return Object
* @exception IOException this is typically thrown by the
* DataHandler. Refer to the documentation for
* jakarta.activation.DataHandler for more details.
* @exception MessagingException for other failures
*/
@Override
public Object getContent() throws IOException, MessagingException {
if (cachedContent != null)
return cachedContent;
Object c;
try {
c = getDataHandler().getContent();
} catch (IOException e) {
if (e.getCause() instanceof FolderClosedException) {
FolderClosedException fce = (FolderClosedException) e.getCause();
throw new FolderClosedException(fce.getFolder(), e.getMessage());
} else if(e.getCause() instanceof MessagingException) {
throw new MessageRemovedException(e.getMessage());
} else {
throw e;
}
}
if (cacheMultipart &&
(c instanceof Multipart || c instanceof Message) &&
(content != null || contentStream != null)) {
cachedContent = c;
/*
* We may abandon the input stream so make sure
* the MimeMultipart has consumed the stream.
*/
if (c instanceof MimeMultipart)
((MimeMultipart)c).parse();
}
return c;
}
/**
* This method provides the mechanism to set this body part's content.
* The given DataHandler object should wrap the actual content.
*
* @param dh The DataHandler for the content
* @exception IllegalWriteException if the underlying
* implementation does not support modification
* @exception IllegalStateException if this body part is
* obtained from a READ_ONLY folder.
*/
@Override
public void setDataHandler(DataHandler dh)
throws MessagingException {
this.dh = dh;
cachedContent = null;
MimeBodyPart.invalidateContentHeaders(this);
}
/**
* A convenience method for setting this body part's content. <p>
*
* The content is wrapped in a DataHandler object. Note that a
* DataContentHandler class for the specified type should be
* available to the Jakarta Mail implementation for this to work right.
* That is, to do <code>setContent(foobar, "application/x-foobar")</code>,
* a DataContentHandler for "application/x-foobar" should be installed.
* Refer to the Java Activation Framework for more information.
*
* @param o the content object
* @param type Mime type of the object
* @exception IllegalWriteException if the underlying
* implementation does not support modification of
* existing values
* @exception IllegalStateException if this body part is
* obtained from a READ_ONLY folder.
*/
@Override
public void setContent(Object o, String type)
throws MessagingException {
if (o instanceof Multipart) {
setContent((Multipart)o);
} else {
setDataHandler(new DataHandler(o, type));
}
}
/**
* Convenience method that sets the given String as this
* part's content, with a MIME type of "text/plain". If the
* string contains non US-ASCII characters, it will be encoded
* using the platform's default charset. The charset is also
* used to set the "charset" parameter. <p>
*
* Note that there may be a performance penalty if
* <code>text</code> is large, since this method may have
* to scan all the characters to determine what charset to
* use. <p>
*
* If the charset is already known, use the
* <code>setText</code> method that takes the charset parameter.
*
* @param text the text content to set
* @exception MessagingException if an error occurs
* @see #setText(String text, String charset)
*/
@Override
public void setText(String text) throws MessagingException {
setText(text, null);
}
/**
* Convenience method that sets the given String as this part's
* content, with a MIME type of "text/plain" and the specified
* charset. The given Unicode string will be charset-encoded
* using the specified charset. The charset is also used to set
* the "charset" parameter.
*
* @param text the text content to set
* @param charset the charset to use for the text
* @exception MessagingException if an error occurs
*/
@Override
public void setText(String text, String charset)
throws MessagingException {
setText(this, text, charset, "plain");
}
/**
* Convenience method that sets the given String as this part's
* content, with a primary MIME type of "text" and the specified
* MIME subtype. The given Unicode string will be charset-encoded
* using the specified charset. The charset is also used to set
* the "charset" parameter.
*
* @param text the text content to set
* @param charset the charset to use for the text
* @param subtype the MIME subtype to use (e.g., "html")
* @exception MessagingException if an error occurs
* @since JavaMail 1.4
*/
@Override
public void setText(String text, String charset, String subtype)
throws MessagingException {
setText(this, text, charset, subtype);
}
/**
* This method sets the body part's content to a Multipart object.
*
* @param mp The multipart object that is the Message's content
* @exception IllegalWriteException if the underlying
* implementation does not support modification of
* existing values.
* @exception IllegalStateException if this body part is
* obtained from a READ_ONLY folder.
*/
@Override
public void setContent(Multipart mp) throws MessagingException {
setDataHandler(new DataHandler(mp, mp.getContentType()));
mp.setParent(this);
}
/**
* Use the specified file to provide the data for this part.
* The simple file name is used as the file name for this
* part and the data in the file is used as the data for this
* part. The encoding will be chosen appropriately for the
* file data. The disposition of this part is set to
* {@link Part#ATTACHMENT Part.ATTACHMENT}.
*
* @param file the File object to attach
* @exception IOException errors related to accessing the file
* @exception MessagingException message related errors
* @since JavaMail 1.4
*/
public void attachFile(File file) throws IOException, MessagingException {
FileDataSource fds = new FileDataSource(file);
this.setDataHandler(new DataHandler(fds));
this.setFileName(fds.getName());
this.setDisposition(ATTACHMENT);
}
/**
* Use the specified file to provide the data for this part.
* The simple file name is used as the file name for this
* part and the data in the file is used as the data for this
* part. The encoding will be chosen appropriately for the
* file data.
*
* @param file the name of the file to attach
* @exception IOException errors related to accessing the file
* @exception MessagingException message related errors
* @since JavaMail 1.4
*/
public void attachFile(String file) throws IOException, MessagingException {
File f = new File(file);
attachFile(f);
}
/**
* Use the specified file with the specified Content-Type and
* Content-Transfer-Encoding to provide the data for this part.
* If contentType or encoding are null, appropriate values will
* be chosen.
* The simple file name is used as the file name for this
* part and the data in the file is used as the data for this
* part. The disposition of this part is set to
* {@link Part#ATTACHMENT Part.ATTACHMENT}.
*
* @param file the File object to attach
* @param contentType the Content-Type, or null
* @param encoding the Content-Transfer-Encoding, or null
* @exception IOException errors related to accessing the file
* @exception MessagingException message related errors
* @since JavaMail 1.5
*/
public void attachFile(File file, String contentType, String encoding)
throws IOException, MessagingException {
DataSource fds = new EncodedFileDataSource(file, contentType, encoding);
this.setDataHandler(new DataHandler(fds));
this.setFileName(fds.getName());
this.setDisposition(ATTACHMENT);
}
/**
* Use the specified file with the specified Content-Type and
* Content-Transfer-Encoding to provide the data for this part.
* If contentType or encoding are null, appropriate values will
* be chosen.
* The simple file name is used as the file name for this
* part and the data in the file is used as the data for this
* part. The disposition of this part is set to
* {@link Part#ATTACHMENT Part.ATTACHMENT}.
*
* @param file the name of the file
* @param contentType the Content-Type, or null
* @param encoding the Content-Transfer-Encoding, or null
* @exception IOException errors related to accessing the file
* @exception MessagingException message related errors
* @since JavaMail 1.5
*/
public void attachFile(String file, String contentType, String encoding)
throws IOException, MessagingException {
attachFile(new File(file), contentType, encoding);
}
/**
* A FileDataSource class that allows us to specify the
* Content-Type and Content-Transfer-Encoding.
*/
private static class EncodedFileDataSource extends FileDataSource
implements EncodingAware {
private String contentType;
private String encoding;
public EncodedFileDataSource(File file, String contentType,
String encoding) {
super(file);
this.contentType = contentType;
this.encoding = encoding;
}
// overrides DataSource.getContentType()
@Override
public String getContentType() {
return contentType != null ? contentType : super.getContentType();
}
// implements EncodingAware.getEncoding()
@Override
public String getEncoding() {
return encoding;
}
}
/**
* Save the contents of this part in the specified file. The content
* is decoded and saved, without any of the MIME headers.
*
* @param file the File object to write to
* @exception IOException errors related to accessing the file
* @exception MessagingException message related errors
* @since JavaMail 1.4
*/
public void saveFile(File file) throws IOException, MessagingException {
OutputStream out = null;
InputStream in = null;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
in = this.getInputStream();
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
} finally {
// close streams, but don't mask original exception, if any
try {
if (in != null)
in.close();
} catch (IOException ex) { }
try {
if (out != null)
out.close();
} catch (IOException ex) { }
}
}
/**
* Save the contents of this part in the specified file. The content
* is decoded and saved, without any of the MIME headers.
*
* @param file the name of the file to write to
* @exception IOException errors related to accessing the file
* @exception MessagingException message related errors
* @since JavaMail 1.4
*/
public void saveFile(String file) throws IOException, MessagingException {
File f = new File(file);
saveFile(f);
}
/**
* Output the body part as an RFC 822 format stream.
*
* @exception IOException if an error occurs writing to the
* stream or if an error is generated
* by the jakarta.activation layer.
* @exception MessagingException for other failures
* @see jakarta.activation.DataHandler#writeTo
*/
@Override
public void writeTo(OutputStream os)
throws IOException, MessagingException {