[英]How to add inline images and attach files in Java mail
I am using the Java mail API for e-mailing. 我正在使用Java邮件API进行电子邮件发送。 I have to e-mail a message that contains both inline images specified by HTML's
<img>
tag and some attached files. 我必须通过电子邮件发送一条消息,其中包含HTML的
<img>
标签和一些附加文件指定的内嵌图像。
What content type I should use for MimeMultipart
that contains the parts for inline images and attachment files? 我应该为
MimeMultipart
使用哪种内容类型,其中包含内嵌图像和附件文件的部分?
MimeMultipart multipartInline = new MimeMultipart(?);
There's three different types of multipart content to consider here: 这里有三种不同类型的多部分内容:
You can nest these different types in all sorts of interesting ways. 您可以以各种有趣的方式嵌套这些不同的类型。
To answer the original question, you want a message with this structure: 要回答原始问题,您需要具有此结构的消息:
main message
multipart/mixed
multipart/related
text/html - main html content
image/jpg - an image referenced by the html
application/pdf - or whatever, for the first attachment
The html part will want to reference the image part using a "cid:" URL reference, and the image part will need a corresponding Content-ID header. html部分将要使用“cid:”URL引用引用图像部分,图像部分将需要相应的Content-ID标头。 RFC2387 has more details.
RFC2387有更多细节。 You can probably find some examples by searching the JavaMail forum .
您可以通过搜索JavaMail论坛找到一些示例。
You must use one or two headers for each attach: 每个附加必须使用一个或两个标头:
If it's a normal attach: 如果这是正常的附着:
If it's an inline attach (image for your mail) 如果是内联附件(邮件图片)
This is extracted for a small sending program I've programmed some time ago: 这是为我前段时间编写的小型发送程序提取的:
bodyPart
is a MimeBodyPart
. bodyPart
是一个MimeBodyPart
。
bodyPart.setHeader("Content-Disposition", disp + "; filename=" + encodedFileName);
bodyPart.setHeader("Content-Transfer-Encoding", "base64");
if (att.getContextId() != null && att.getContextId().length() > 0)
bodyPart.setHeader("Content-ID", "<" + att.getContextId() + ">");
In it: disp has inline
or attachment
, and att.getContextId()
has some arbitrary ID for the inlined attach. 其中:disp具有
inline
或attachment
,而att.getContextId()
具有内联附加的任意ID。
My recipe for an HTML mail 我的HTML邮件食谱
message has via .setContent(...)
mainMultipart is a MimeMultiPart("alternative")
and has via .addBodyPart(...)
textBodyPart is a MimeBodyPart with content-type "text/plain"
relatedMultipart is a MimeMultipart("related")
and has via .addBodyPart(...)
htmlBodyPart "text/html; charset=utf-8"
INLINED-ATTACH1
INLINED-ATTACH2
NORMAL-ATTACH1
NORMAL-ATTACH2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.