0

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

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

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.

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
  • Any chance the image is being stripped out by a helpful filter in your mail infrastructure? Have you successfully sent the same file using a proper email client? – codebox Sep 26 '12 at 14:12
  • I just tried and yes, I get the image when I send it with a different email account using Thunderbird. – Jérôme Verstrynge Sep 26 '12 at 14:17

2 Answers2

1

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");
Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
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);

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

dngfng
  • 1,923
  • 17
  • 34