Java源码示例:javax.mail.internet.MimePart
示例1
/**
* Set the given text directly as content in non-multipart mode
* or as default body part in multipart mode.
* The "html" flag determines the content type to apply.
* <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
* else, mail readers might not be able to resolve inline references correctly.
* @param text the text for the message
* @param html whether to apply content type "text/html" for an
* HTML mail, using default content type ("text/plain") else
* @throws MessagingException in case of errors
*/
public void setText(String text, boolean html) throws MessagingException {
Assert.notNull(text, "Text must not be null");
MimePart partToUse;
if (isMultipart()) {
partToUse = getMainPart();
}
else {
partToUse = this.mimeMessage;
}
if (html) {
setHtmlTextToMimePart(partToUse, text);
}
else {
setPlainTextToMimePart(partToUse, text);
}
}
示例2
/**
* Set the given text directly as content in non-multipart mode
* or as default body part in multipart mode.
* The "html" flag determines the content type to apply.
* <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
* else, mail readers might not be able to resolve inline references correctly.
* @param text the text for the message
* @param html whether to apply content type "text/html" for an
* HTML mail, using default content type ("text/plain") else
* @throws MessagingException in case of errors
*/
public void setText(String text, boolean html) throws MessagingException {
Assert.notNull(text, "Text must not be null");
MimePart partToUse;
if (isMultipart()) {
partToUse = getMainPart();
}
else {
partToUse = this.mimeMessage;
}
if (html) {
setHtmlTextToMimePart(partToUse, text);
}
else {
setPlainTextToMimePart(partToUse, text);
}
}
示例3
/**
* Compute body part size with failover.
* @param bodyPart MIME body part
* @return body part size or 0 on error
*/
private int getBodyPartSize(MimePart bodyPart) {
int bodySize = 0;
try {
bodySize = bodyPart.getSize();
if (bodySize == -1) {
// failover, try to get size
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bodyPart.writeTo(baos);
bodySize = baos.size();
}
} catch (IOException | MessagingException e) {
LOGGER.warn("Unable to get body part size " + e.getMessage(), e);
}
return bodySize;
}
示例4
@PublicAtsApi
public List<InputStream> getAllStreams() throws PackageException {
boolean storeReconnected = false;
try {
// store should be opened for actions including getting InputStream.
storeReconnected = reconnectStoreIfClosed();
ArrayList<InputStream> streams = new ArrayList<InputStream>();
try {
for (MimePart part : parts) {
streams.add(part.getInputStream());
}
} finally {
closeStoreConnection(storeReconnected);
}
return streams;
} catch (MessagingException me) {
throw new PackageException("Could not read mime parts", me);
} catch (IOException ioe) {
throw new PackageException("Could not read mime parts", ioe);
}
}
示例5
/**
* Get the specified header value from a specified MIME part
*
* @param headerName
* @param partNum
* @param headerIndex
* @return
* @throws PackageException
*/
@PublicAtsApi
public String getPartHeader(
String headerName,
int partNum,
int headerIndex ) throws PackageException {
try {
String[] headers;
if (partNum >= parts.size()) {
throw new NoSuchMimePartException("No MIME part at position '" + partNum + "'");
}
MimePart part = parts.get(partNum);
headers = part.getHeader(headerName);
if ( (headers != null) && (headers.length > headerIndex)) {
return headers[headerIndex];
} else {
throw new NoSuchHeaderException(headerName, partNum, headerIndex);
}
} catch (MessagingException me) {
throw new PackageException(me);
}
}
示例6
/**
* Get all header values from a specified MIME part
*
* @param headerName
* @param partNum
* @return
* @throws PackageException
*/
@PublicAtsApi
public String[] getPartHeaderValues(
String headerName,
int partNum ) throws PackageException {
try {
String[] headers;
if (partNum >= parts.size()) {
throw new NoSuchMimePartException("No MIME part at position '" + partNum + "'");
}
MimePart part = parts.get(partNum);
headers = part.getHeader(headerName);
if ( (headers != null) && (headers.length > 0)) {
return headers;
} else {
throw new NoSuchHeaderException(headerName, partNum);
}
} catch (MessagingException me) {
throw new PackageException(me);
}
}
示例7
/**
* Get a MIME part based on it's index and type
*
* @param partIndex
* the index of the MIME part
* @param isAttachment
* the type - true if the part is attachment, false otherwise
* @return the mime part
* @throws NoSuchMimePartException
* if there is no such part
*/
@PublicAtsApi
public MimePart getPart(
int partIndex,
boolean isAttachment ) throws NoSuchMimePartException {
// first check if there is part at this position at all
if (isAttachment) {
if (partIndex >= attachmentPartIndices.size()) {
throw new NoSuchMimePartException("No attachment at position '" + partIndex + "'");
}
} else {
if (partIndex >= regularPartIndices.size()) {
throw new NoSuchMimePartException("No regular part at position '" + partIndex + "'");
}
}
MimePart part;
if (isAttachment) {
part = getPart(attachmentPartIndices.get(partIndex));
} else {
part = getPart(regularPartIndices.get(partIndex));
}
return part;
}
示例8
/**
* Get the content type of a regular part
*
* @param partIndex
* the index of the regular part
* @return the content type as string
* @throws PackageException
*/
@PublicAtsApi
public String getRegularPartContentType(
int partIndex ) throws PackageException {
// first check if there is part at this position at all
if (partIndex >= regularPartIndices.size()) {
throw new NoSuchMimePartException("No regular part at position '" + partIndex + "'");
}
try {
MimePart part = getPart(regularPartIndices.get(partIndex));
// get the content type header
ContentType contentType = new ContentType(part.getContentType());
return contentType.getBaseType();
} catch (MessagingException me) {
throw new PackageException(me);
}
}
示例9
/**
* Get the character set of a regular part
*
* @param partIndex
* the index of the part
* @return the charset
* @throws PackageException
*/
@PublicAtsApi
public String getRegularPartCharset(
int partIndex ) throws PackageException {
// first check if there is part at this position at all
if (partIndex >= regularPartIndices.size()) {
throw new NoSuchMimePartException("No regular part at position '" + partIndex + "'");
}
try {
MimePart part = getPart(regularPartIndices.get(partIndex));
// get the content type header
ContentType contentType = new ContentType(part.getContentType());
return contentType.getParameter("charset");
} catch (MessagingException me) {
throw new PackageException(me);
}
}
示例10
/**
* Set/modify attachment file name
*
* @param attachmentPartIndex index among attachment parts only
* @param fileName the file name. Add one or reset existing one
* @throws NoSuchMimePartException if not such attachment part is found
* @throws PackageException in case of other mail messaging exception
*/
@PublicAtsApi
public void setAttachmentFileName(
int attachmentPartIndex,
String fileName ) throws PackageException {
// first check if there is part at this position at all
if (attachmentPartIndex >= attachmentPartIndices.size()) {
throw new NoSuchMimePartException("No attachment at position '" + attachmentPartIndex + "'");
}
try {
MimePart part = getPart(attachmentPartIndices.get(attachmentPartIndex));
// set the attachment file name
part.setFileName(fileName);
// must save now
this.message.saveChanges();
} catch (MessagingException me) {
throw new PackageException(me);
}
}
示例11
/**
* Get an attachment's file name
*
* @param partIndex
* @return
* @throws PackageException
*/
@PublicAtsApi
public String getAttachmentFileName(
int partIndex ) throws PackageException {
// first check if there is part at this position at all
if (partIndex >= attachmentPartIndices.size()) {
throw new NoSuchMimePartException("No attachment at position '" + partIndex + "'");
}
try {
MimePart part = getPart(attachmentPartIndices.get(partIndex));
// get the attachment file name
String fileName = part.getFileName();
if (fileName == null) {
throw new PackageException("Could not determine file name for attachment at position "
+ partIndex);
}
return fileName;
} catch (MessagingException me) {
throw new PackageException(me);
}
}
示例12
/**
* Get the attachment content type
*
* @param partIndex
* @return
* @throws PackageException
*/
@PublicAtsApi
public String getAttachmentContentType(
int partIndex ) throws PackageException {
// first check if there is part at this position at all
if (partIndex >= attachmentPartIndices.size()) {
throw new NoSuchMimePartException("No attachment at position '" + partIndex + "'");
}
try {
MimePart part = getPart(attachmentPartIndices.get(partIndex));
// get the content type header
ContentType contentType = new ContentType(part.getContentType());
return contentType.getBaseType();
} catch (MessagingException me) {
throw new PackageException(me);
}
}
示例13
/**
* Get the attachment character set
*
* @param partIndex
* the index of the attachment
* @return the character set for this attachment, null if there is no such
* @throws PackageException
*/
@PublicAtsApi
public String getAttachmentCharset(
int partIndex ) throws PackageException {
// first check if there is part at this position at all
if (partIndex >= attachmentPartIndices.size()) {
throw new NoSuchMimePartException("No attachment at position '" + partIndex + "'");
}
try {
MimePart part = getPart(attachmentPartIndices.get(partIndex));
// get the content type header
ContentType contentType = new ContentType(part.getContentType());
return contentType.getParameter("charset");
} catch (MessagingException me) {
throw new PackageException(me);
}
}
示例14
/**
* Return the attachment data
*
* @param partIndex
* the index of the attachment
* @return an InputStream with the attachment data
* @throws PackageException
*/
@PublicAtsApi
public InputStream getAttachmentPartData(
int partIndex ) throws PackageException {
try {
boolean storeReconnected = reconnectStoreIfClosed();
// store should be opened for actions including getting InputStream. Hence store open is not in getPart
try {
MimePart part = getPart(partIndex, true);
return part.getInputStream();
} finally {
closeStoreConnection(storeReconnected);
}
} catch (MessagingException me) {
throw new PackageException("Error getting attachment data for part " + partIndex, me);
} catch (IOException ioe) {
throw new PackageException("Error getting attachment data for part " + partIndex, ioe);
}
}
示例15
@Test
public void setBody_multiParts_with_textPart_only() throws Exception {
// create a new message and add TEXT part to it
MimePackage newMailMessage = new MimePackage();
newMailMessage.addPart("text plain body", MimePackage.PART_TYPE_TEXT_PLAIN);
MimePart textPart = newMailMessage.getPart(0, false);
assertEquals(textPart.getContent(), "text plain body");
assertEquals(textPart.getContentType(), "text/plain; charset=us-ascii");
// modify the only part
newMailMessage.setBody("new body");
// verify the modifications
MimePart newTextPart = newMailMessage.getPart(0, false);
assertEquals(newTextPart.getContent(), "new body");
assertEquals(newTextPart.getContentType(), "text/plain; charset=us-ascii");
// verify there are no more parts
try {
newMailMessage.getPart(1, false);
assertTrue("There is more than 1 part, while we expect to have just 1", false);
} catch (NoSuchMimePartException e) {}
}
示例16
@Test
public void setBody_multiParts_with_htmlPart_only() throws Exception {
// create a new message and add HTML part to it
MimePackage newMailMessage = new MimePackage();
newMailMessage.addPart("html body", MimePackage.PART_TYPE_TEXT_HTML);
MimePart htmlPart = newMailMessage.getPart(0, false);
assertEquals(htmlPart.getContent(), "html body");
assertEquals(htmlPart.getContentType(), "text/html; charset=us-ascii");
// modify the only part
newMailMessage.setBody("new body");
// verify the modifications
MimePart newHtmlPart = newMailMessage.getPart(0, false);
assertEquals(newHtmlPart.getContent(), "new body");
assertEquals(newHtmlPart.getContentType(), "text/html; charset=us-ascii");
// verify there are no more parts
try {
newMailMessage.getPart(1, false);
assertTrue("There is more than 1 part, while we expect to have just 1", false);
} catch (NoSuchMimePartException e) {}
}
示例17
/**
* Set the given text directly as content in non-multipart mode
* or as default body part in multipart mode.
* The "html" flag determines the content type to apply.
* <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
* else, mail readers might not be able to resolve inline references correctly.
* @param text the text for the message
* @param html whether to apply content type "text/html" for an
* HTML mail, using default content type ("text/plain") else
* @throws MessagingException in case of errors
*/
public void setText(String text, boolean html) throws MessagingException {
Assert.notNull(text, "Text must not be null");
MimePart partToUse;
if (isMultipart()) {
partToUse = getMainPart();
}
else {
partToUse = this.mimeMessage;
}
if (html) {
setHtmlTextToMimePart(partToUse, text);
}
else {
setPlainTextToMimePart(partToUse, text);
}
}
示例18
/**
* Set the given text directly as content in non-multipart mode
* or as default body part in multipart mode.
* The "html" flag determines the content type to apply.
* <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
* else, mail readers might not be able to resolve inline references correctly.
* @param text the text for the message
* @param html whether to apply content type "text/html" for an
* HTML mail, using default content type ("text/plain") else
* @throws MessagingException in case of errors
*/
public void setText(String text, boolean html) throws MessagingException {
Assert.notNull(text, "Text must not be null");
MimePart partToUse;
if (isMultipart()) {
partToUse = getMainPart();
}
else {
partToUse = this.mimeMessage;
}
if (html) {
setHtmlTextToMimePart(partToUse, text);
}
else {
setPlainTextToMimePart(partToUse, text);
}
}
示例19
/**
* Attempt to repair the given contentType if broken.
* @param mp Mimepart holding the contentType
* @param contentType ContentType
* @return fixed contentType String
* @throws MessagingException
*/
public static String cleanContentType(MimePart mp, String contentType) throws MessagingException {
ContentType ct = parseContentType(contentType);
if (ct == null) {
ct = getParsableContentType(contentType);
}
if (ct.getBaseType().equalsIgnoreCase("text/plain") || ct.getBaseType().equalsIgnoreCase("text/html")) {
Charset charset = parseCharset(ct);
if (charset == null) {
Logger.debug("Charset of the ContentType could not be read, try to decode the contentType as quoted-printable");
ContentType ctTmp = decodeContentTypeAsQuotedPrintable(contentType);
if (parseCharset(ctTmp) != null) {
ct = ctTmp;
} else {
ct.setParameter("charset", ContentTypeCleaner.DEFAULT_CHARSET);
}
}
}
return ct.toString();
}
示例20
@Override
public void setContent(MimePart message, Multipart multipart, Email email, Content content) throws ContentHandlerException {
try {
MultiContent multiContent = (MultiContent) content;
MimeMultipart mp = new MimeMultipart("alternative");
for (Content c : multiContent.getContents()) {
delegate.setContent(message, mp, email, c);
}
// add the part
MimeBodyPart part = new MimeBodyPart();
part.setContent(mp);
multipart.addBodyPart(part);
} catch (MessagingException e) {
throw new ContentHandlerException("Failed to generate alternative content", content, e);
}
}
示例21
private void convertPart(MimePart part) throws MessagingException, IOException {
if ("8bit".equals(part.getEncoding())) {
// The content may already be in encoded the form (likely with mail
// created from a
// stream). In that case, just changing the encoding to
// quoted-printable will mangle
// the result when this is transmitted. We must first convert the
// content into its
// native format, set it back, and only THEN set the transfer
// encoding to force the
// content to be encoded appropriately.
// if the part doesn't contain text it will be base64 encoded.
String contentTransferEncoding = part.isMimeType("text/*") ? "quoted-printable" : "base64";
part.setContent(part.getContent(), part.getContentType());
part.setHeader("Content-Transfer-Encoding", contentTransferEncoding);
part.addHeader("X-MIME-Autoconverted", "from 8bit to "
+ contentTransferEncoding + " by " + mailetContext.getServerInfo());
} else if (part.isMimeType("multipart/*")) {
MultipartUtil.retrieveBodyParts((MimeMultipart) part.getContent())
.forEach(Throwing.consumer(bodyPart -> convertPart((MimePart) bodyPart)));
}
}
示例22
/**
* Checks whether the MimePart contains an object of the given mime type.
*
* @param part the current MimePart
* @param mimeType the mime type to check
* @return {@code true} if the MimePart matches the given mime type, {@code false} otherwise
* @throws MessagingException parsing the MimeMessage failed
* @throws IOException parsing the MimeMessage failed
*/
private boolean isMimeType(final MimePart part, final String mimeType)
throws MessagingException, IOException
{
// Do not use part.isMimeType(String) as it is broken for MimeBodyPart
// and does not really check the actual content type.
try
{
final ContentType ct = new ContentType(part.getDataHandler().getContentType());
return ct.match(mimeType);
}
catch (final ParseException ex)
{
return part.getContentType().equalsIgnoreCase(mimeType);
}
}
示例23
private void setPlainTextToMimePart(MimePart mimePart, String text) throws MessagingException {
if (getEncoding() != null) {
mimePart.setText(text, getEncoding());
}
else {
mimePart.setText(text);
}
}
示例24
private void setHtmlTextToMimePart(MimePart mimePart, String text) throws MessagingException {
if (getEncoding() != null) {
mimePart.setContent(text, CONTENT_TYPE_HTML + CONTENT_TYPE_CHARSET_SUFFIX + getEncoding());
}
else {
mimePart.setContent(text, CONTENT_TYPE_HTML);
}
}
示例25
private void setPlainTextToMimePart(MimePart mimePart, String text) throws MessagingException {
if (getEncoding() != null) {
mimePart.setText(text, getEncoding());
}
else {
mimePart.setText(text);
}
}
示例26
private void setHtmlTextToMimePart(MimePart mimePart, String text) throws MessagingException {
if (getEncoding() != null) {
mimePart.setContent(text, CONTENT_TYPE_HTML + CONTENT_TYPE_CHARSET_SUFFIX + getEncoding());
}
else {
mimePart.setContent(text, CONTENT_TYPE_HTML);
}
}
示例27
/**
* If a Content-Type handler has been specified,
* call it to clean up the Content-Type value.
*
* @param mp the MimePart
* @param contentType the Content-Type value
* @return the cleaned Content-Type value
*/
public static String cleanContentType(MimePart mp, String contentType) {
if (cleanContentType != null) {
try {
return (String)cleanContentType.invoke(null,
new Object[] { mp, contentType });
} catch (Exception ex) {
return contentType;
}
} else
return contentType;
}
示例28
private boolean isPartAttachment(
MimePart part ) throws PackageException {
try {
String disposition = part.getDisposition();
if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
return true;
}
} catch (MessagingException me) {
throw new PackageException("Could not determine if part is an attachment", me);
}
return false;
}
示例29
private MimePart getPart(
int index ) throws NoSuchMimePartException {
if (index >= parts.size()) {
throw new NoSuchMimePartException("No MIME part at position '" + index + "'");
}
MimePart part = this.parts.get(index);
if (part != null) {
return part;
} else {
throw new NoSuchMimePartException("No part at position '" + index + "'");
}
}
示例30
@Test
public void setBody_multiParts_with_textAndHtmlParts() throws Exception {
// create a new message and add TEXT and HTML parts to it
MimePackage newMailMessage = new MimePackage();
newMailMessage.addPart("text plain body", MimePackage.PART_TYPE_TEXT_PLAIN);
newMailMessage.addPart("html body", MimePackage.PART_TYPE_TEXT_HTML);
MimePart textPart = newMailMessage.getPart(0, false);
assertEquals(textPart.getContent(), "text plain body");
assertEquals(textPart.getContentType(), "text/plain; charset=us-ascii");
MimePart htmlPart = newMailMessage.getPart(1, false);
assertEquals(htmlPart.getContent(), "html body");
assertEquals(htmlPart.getContentType(), "text/html; charset=us-ascii");
// modify both parts
newMailMessage.setBody("new body");
// verify the modifications
MimePart newTextPart = newMailMessage.getPart(0, false);
assertEquals(newTextPart.getContent(), "new body");
assertEquals(newTextPart.getContentType(), "text/plain; charset=us-ascii");
MimePart newHtmlPart = newMailMessage.getPart(1, false);
assertEquals(newHtmlPart.getContent(), "new body");
assertEquals(newHtmlPart.getContentType(), "text/html; charset=us-ascii");
// verify there are no more parts
try {
newMailMessage.getPart(2, false);
assertTrue("There is more than 2 parts, while we expect to have just 2", false);
} catch (NoSuchMimePartException e) {}
}