user1884155
user1884155

Reputation: 3736

Sending a mail with attachment in Java without needing a physical attachment file

I use JavaMailSender in a Java application to send an email with an attachment. The attachment is a file located at a website (for example, http://example.com/technical_guide.pdf)

The first naive implementation was as follows:

  1. Fetch the bytes of the file from the url and create an inputstream
  2. Create a file from that inputstream
  3. add the file as an attachment to a mailmessage
  4. send the message

This worked, but step 2 had the unfortunate side-effect of creating physical files on the filesystems. Rather than deleting them (programmatically), I found that I can also pass a datasource. So now I have the following implementation:

  1. Create an URLDataSource from the file URL
  2. add the data source as attachment to a mailmessage
  3. send the message

This also works great, and I no longer see the files under my servlet container's root directory. However - I'm concerned that javaMail might still makes some files somewhere under the hood, but I'm just not aware of it.

Can anybody confirm that no physcial files are created in this process (not even under hidden folders like users/appdata/, /catalina_home/, windows/tmp/ etc.) and if so - explain how java is able to send mails without needing any files? Is it because all it needs is the "bytes" to send to the mailserver and it doesn't care where does bytes come from?

Upvotes: 2

Views: 3546

Answers (1)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

You can use the MimeMessageHelper.addAttachment(String attachmentFilename, InputStreamSource inputStreamSource) method:

helper.addAttachment("attachement", yourStream);

Basically it is not needed to have a phisical file. You can also build it in memory and stream it to the helper.

Upvotes: 4

Related Questions