我想發送一封電子郵件與來自Java的圖像附件。我正在使用以下代碼段:電子郵件丟失圖像附件
String to = "[email protected]";
String from = "[email protected]";
// Which server is sending the email?
String host = "localhost";
// Setting sending mail server
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
// Providing email and password access to mail server
properties.setProperty("mail.user", "xxx");
properties.setProperty("mail.password", "yyy");
// Retrieving the mail session
Session session = Session.getDefaultInstance(properties);
// Create a default MimeMessage
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(
Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("This an email test !!!");
// Create a multipart message
Multipart mp = new MimeMultipart();
// Body text
BodyPart messageBP = new MimeBodyPart();
messageBP.setText("Some message body !!!");
mp.addBodyPart(messageBP);
// Attachment
BodyPart messageBP2 = new MimeBodyPart();
String image = "/MyImage.jpg";
InputStream stream = EmailWithAttachment.class
.getResourceAsStream(image);
DataSource source = new ByteArrayDataSource(stream, "image/*");
messageBP2.setDataHandler(new DataHandler(source));
messageBP2.setHeader("Content-ID", "My Image");
mp.addBodyPart(messageBP2);
message.setContent(mp);
// Sending the message
Transport.send(message);
電子郵件到達我的郵箱,但是當我打開它時,附件不可用。什麼可能導致這個問題?我檢查了.jar
,它包含圖像。
圖像是否被郵件基礎架構中有用的過濾器剝離?您是否使用正確的電子郵件客戶端成功發送了相同的文件? – codebox
我剛剛嘗試過,是的,當我使用Thunderbird以不同的電子郵件帳戶發送圖像時,我會看到圖像。 – JVerstry