2

I am sending a mail with a attachment, But when i am try to open the file, it's not opening and giving following error:

enter image description here

I try to do it like:

JavaMailSenderImpl mailSender = getMailSender();
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
URLDataSource url;
try {
        helper = new MimeMessageHelper(message, true);
        url = new URLDataSource(new URL("localhost:8080/test/attachment/simpldoc.docx"));
        helper.setFrom(mailFrom);
        helper.setSubject(subject);
        helper.setTo(mailTo);
        helper.setText(text, true);
        helper.addAttachment(attachmentName, url);
        mailSender.send(message);
    } 
    catch (MessagingException e) {
        e.printStackTrace();
    }
Avinash Mishra
  • 1,346
  • 3
  • 21
  • 41
  • Can you open the "details" please? – rpax Jun 12 '14 at 08:33
  • How does the URL `localhost:8080/test/attachment/simpldoc.docx` serve the file? Could you post this part as well? Because I had a quite similar error (see [this post](http://stackoverflow.com/a/10432218/1225328)): adding the `ContentLength` of the response solved it. – sp00m Jun 12 '14 at 08:35
  • 1
    try this, helper.addAttachment(attachmentName, new ClassPathResource("attachment/simpldoc.docx")); – ravikumar Jun 12 '14 at 08:38
  • @rpax In details, It says The file is corrupt cannot open. – Avinash Mishra Jun 12 '14 at 08:41
  • You should use File instead of URL to get the attachment. – Ved Jun 12 '14 at 08:41

1 Answers1

0

You are trying to pass a url object as a attachment.

You can use url.getOutputStream() to open stream and then write into a file object before attaching the file.

All of that is bad.

You should be using File to get the relevant file.

so replace

URLDataSource url;
//Code
url = new URLDataSource(new URL("localhost:8080/test/attachment/simpldoc.docx"));

with

File url;
//Code
url = new File("file://localhost:8080/test/attachment/simpldoc.docx")

That should return you the actual file and store it in url object.

Give that a go.

Aeseir
  • 7,754
  • 10
  • 58
  • 107