Java邮件 – 附件&&内嵌图像

我今天早上已经解决了一个问题: Java Mail,发送多个附件无法正常工作

这次我有一个稍微复杂的问题:我想将附件与图像结合起来。

import java.io.IOException; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class MailTest { public static void main(String[] args) throws AddressException, MessagingException, IOException { String host = "***"; String from = "***"; String to = "***"; // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", host); // Get session Session session = Session.getDefaultInstance(props, null); // Define message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Hello JavaMail"); // Handle attachment 1 MimeBodyPart messageBodyPart1 = new MimeBodyPart(); messageBodyPart1.attachFile("c:/Temp/a.txt"); // Handle attachment 2 MimeBodyPart messageBodyPart2 = new MimeBodyPart(); messageBodyPart2.attachFile("c:/Temp/b.txt"); FileDataSource fileDs = new FileDataSource("c:/Temp/gti.jpeg"); MimeBodyPart imageBodypart = new MimeBodyPart(); imageBodypart.setDataHandler(new DataHandler(fileDs)); imageBodypart.setHeader("Content-ID", ""); imageBodypart.setDisposition(MimeBodyPart.INLINE); // Handle text String body = "ElottemyimgUtana"; MimeBodyPart textPart = new MimeBodyPart(); textPart.setHeader("Content-Type", "text/plain; charset=\"utf-8\""); textPart.setContent(body, "text/html; charset=utf-8"); MimeMultipart multipart = new MimeMultipart("mixed"); multipart.addBodyPart(textPart); multipart.addBodyPart(imageBodypart); multipart.addBodyPart(messageBodyPart1); multipart.addBodyPart(messageBodyPart2); message.setContent(multipart); // Send message Transport.send(message); } } 

当我在Gmail中打开电子邮件时,一切都很好:我有两个附件,图像显示在邮件的内容中(在img标签中)。

问题在于Thunderbird和RoundCubic webmail:每个显示的图像都缺失,并在底部显示为附件。

我怎样才能做到这一点?

非常方便的是使用org.apache.commons.mail库中的ImageHtmlEmail。 (更新:它仅包含在1.3的快照中)例如:

  HtmlEmail email = new ImageHtmlEmail(); email.setHostName("mail.myserver.com"); email.addTo("jdoe@somewhere.org", "John Doe"); email.setFrom("me@apache.org", "Me"); email.setSubject("Test email with inline image"); // embed the image and get the content id URL url = new URL("http://sofzh.miximages.com/java/asf_logo_wide.gif"); String cid = email.embed(url, "Apache logo"); // set the html message email.setHtmlMsg(htmlEmailTemplate, new File("").toURI().toURL(), false); 

所以我通过让javamail去使用spring包装器来解决这个问题:

http://static.springsource.org/spring/docs/1.2.x/reference/mail.html

我不知道它在背景中做了什么魔法,但它有效。

谢谢大家!