Email missing image attachment

I am trying to send an email with an image attachment from Java. I am using the following piece of code:

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);

The email arrives in my mailbox, but when I open it, the attachment is not available. What could cause this issue? I have checked the .jar and it contains the image.

Upvotes: 0

Views: 661

Answers (2)

Ok, I got it. I should not pass the input stream, but a byte array and set a more precise MIME type. I modified my code as following and it works:

DataSource source = new ByteArrayDataSource(
    IOUtils.toByteArray(is), "image/jpeg");

Upvotes: 1

dngfng
dngfng

Reputation: 1943

     // 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);

source: http://www.tutorialspoint.com/java/java_sending_email.htm

Upvotes: 0

Related Questions