正文发送图片,从开始到完善,总共经历了2种方法。
第一种:
.ftl模板:
<#list
imgList
as
imgList
>
<
img
src=
"data:image/png;base64,
${
imgList
.
img
}
"
>
</#list>
|
java中:
1>利用JFreeMarker获取到jpeg图片;
2>将.jpeg转为Base64的String流;
3>将String作为Map的value放入ftl能解析的容器中。
此方法在客户端能正常显示出图片样式,但是在网页登录邮箱时,图片缺失。
原因:javax.mail的
MimeBodyPart 这些处理mail的过程中,很可能由于base64的String流过长,后面的信息被截掉了。这么推理的依据是,换成png格式的String流后,每张图片能显示开头的一些像素。
第二种:
其实第一种方式并不好,选择它的原因无非是不需要修改现有的框架,但是为了兼容,只能开始对框架做修改了。
思想很简单:将正文的html和图片作为一个
MimeBodyPart ,将他们封装在
MimeMultipart 中,图片的
ContentID对应html的<img src=“cid=
ContentID">。
核心代码:
MimeMessage
message
=
new
MimeMessage
(
session
)
;
MimeMultipart
multipart
=
new
MimeMultipart
(
"mixed
”
)
;
。。。
//用于保存最终正文
MimeBodyPart
contentBody
=
new
MimeBodyPart
()
;
//用于组合文本和图片,"related"型的MimeMultipart对象
MimeMultipart
contextMulti
=
new
MimeMultipart
(
"related"
)
;
//正文的文本部分
MimeBodyPart
textBody
=
new
MimeBodyPart
()
;
textBody
.
setContent
(
content
,
"text/html; charset=utf-8"
)
;
contextMulti
.
addBodyPart
(
textBody
)
;
//正文的图片部分
String
imgpath
=
param
.
get
(
"imgpath"
)
;
if
(
StringUtil
.
isNotEmpty
(
imgpath
)){
File
imgfile
=
new
File
(
imgpath
)
;
if
(
imgfile
.
exists
()){
File
[]
fileson
=
imgfile
.
listFiles
()
;
for
(
int
i
=
0
;
i
<
fileson
.
length
;
i
++
){
MimeBodyPart
jpgBody
=
new
MimeBodyPart
()
;
FileDataSource
fds
=
new
FileDataSource
(
fileson
[
i
]
.
getAbsolutePath
())
;
jpgBody
.
setDataHandler
(
new
DataHandler
(
fds
))
;
String
name
=
fileson
[
i
]
.
getName
()
.
split
(
"
\\
."
)[
0
]
;
jpgBody
.
setContentID
(
name
)
;
//将图片名作为cid=的值
contextMulti
.
addBodyPart
(
jpgBody
)
;
}
}
}
//将上面"related"型的 MimeMultipart 对象作为邮件的正文
contentBody
.
setContent
(
contextMulti
)
;
//将正文加到最后的邮件内容中
multipart
.
addBodyPart
(
contentBody
)
;
message
.
setContent
(
multipart
)
;
|