0

我正在尝试从 Java 发送带有图像附件的电子邮件。我正在使用以下代码:

String to = "jverstry@gmail.com";
String from = "ffff@ooop.com";

// 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它,它包含图像。

4

2 回答 2

1

好,我知道了。我不应该传递输入流,而是传递一个字节数组并设置更精确的 MIME 类型。我修改了我的代码如下,它可以工作:

DataSource source = new ByteArrayDataSource(
    IOUtils.toByteArray(is), "image/jpeg");
于 2012-09-26T14:26:17.370 回答
0
     // Part two is attachment
     messageBodyPart = new MimeBodyPart();
     String filename = "file.txt";
     DataSource source = new FileDataSource(filename);
     messageBodyPart.setDataHandler(new DataHandler(source));
     messageBodyPart.setFileName(filename);
     multipart.addBodyPart(messageBodyPart);

来源:http ://www.tutorialspoint.com/java/java_sending_email.htm

于 2012-09-26T14:13:56.537 回答