Servlet发送带有图像的HTML邮件,添加附件“ noname”

时间:2018-07-15 04:08:11

标签: servlets javamail

我正在尝试使用javax.mail从servlet发送电子邮件。

麻烦是,我在html代码中有2张图片,这些图片正确显示在邮件正文中。

但是我还有2个文件(“ noname”)与此电子邮件一起附加。

这是代码:

users/show

有人可以回答吗?

非常感谢您的回答。

1 个答案:

答案 0 :(得分:0)

multipart / related应该嵌套在multipart / mixed中,其中还包含附件:

BodyPart messageBodyPart ;
// Add HTML + image      
// first part (the html)
messageBodyPart = new MimeBodyPart();
MimeMultipart related = new MimeMultipart("related");  
messageBodyPart.setContent(Constantes.html  + msg +"</h4>", "text/html");
// add it
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
related.addBodyPart(messageBodyPart);

// second part ( image 1)
BodyPart messageBodyPartSMSC = new MimeBodyPart();
DataSource fds = new FileDataSource(Constantes.imagePath + "logo1.png");

messageBodyPartSMSC.setDataHandler(new DataHandler(fds));
messageBodyPartSMSC.setHeader("Content-ID", "<logo1>");      
// add image to the multipart
messageBodyPartSMSC.setDisposition(MimeBodyPart.INLINE);
related.addBodyPart(messageBodyPart);

 // second part ( image 2)
BodyPart messageBodyPartDEVB = new MimeBodyPart();
fds = new FileDataSource(Constantes.imagePath + "logo2.png");

messageBodyPartDEVB.setDataHandler(new DataHandler(fds));
messageBodyPartDEVB.setHeader("Content-ID", "<logo2>");
messageBodyPartDEVB.setDisposition(MimeBodyPart.INLINE);
// add image to the multipart
related.addBodyPart(messageBodyPart);

MimeMultipart multipart = new MimeMultipart().
MimeBodyPart rbp = new MimeBodyPart();
rbp.setContent(related);
multipart.addBodypart(rbp);

 // add attachment (zip file) ------------------------------

BodyPart messageBodyPartZip = new MimeBodyPart();
DataSource source = new FileDataSource(fileName);
messageBodyPartZip.setDataHandler(new DataHandler(source));
messageBodyPartZip.setFileName(onlyFileName);
messageBodyPartZip.setDisposition(MimeBodyPart.ATTACHMENT);
// or replace the above 4 lines with:
// messageBodyPartZIP.attachFile(fileName);
multipart.addBodyPart(messageBodyPartZip);

// Send the complete message parts
message.setContent(multipart);

Transport.send(message);

您还可以通过将html中的图像作为嵌入式数据包括在内来简化结构。在这种情况下,您根本不需要multipart / related,并且可以将html正文部分添加为multipart / mixed中的第一个正文部分。 有关详细信息,请参见JavaMail FAQ

相关问题