我有一個問題已經今早解決: Java Mail, sending multiple attachments not workingJava郵件 - 附件&&內嵌圖像
這一次我有一個稍微複雜的問題:我想附加的文件與圖像相結合。
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", "<myimg>");
imageBodypart.setDisposition(MimeBodyPart.INLINE);
// Handle text
String body = "<html><body>Elotte<img src=\"cid:myimg\" width=\"600\" height=\"90\" alt=\"myimg\" />Utana</body></html>";
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上:每一個像圖片一樣顯示都丟失,並以附件的形式顯示在底部。
我該如何做這項工作?
Microsoft Outlook 2010不允許內嵌圖像!這對你來說是一個沉重的問題嗎? –
那麼我沒有使用Outlook,但雷鳥。在我將multipart從「related」改爲「mixed」之前,它正在工作。 PLS。看到鏈接的stackoverflow問題。 – dbalakirev
所以我得到這個使用這個整理: http://static.springsource.org/spring/docs/1.2.x/reference/mail.html 春天在後臺做的伎倆。 但我不能關閉這個問題,因爲我的代表不夠高。 – dbalakirev