Java Mail: How to send attachments with relative paths
It’s usual to see Java Mail tutorials with attachments. In many of them, you’ll see how these resources are added but always putting their absolute path. The key to this is to add the resources as InputStream and not as File.
The example will be divided into different parts. Let’s start with the server configuration. This example is designed to use GMail’s SMTP server by default.
Then we create the Message object with the delivery information: recipient, sender, subject, etc.
The next step is to add the message content. To do this we will create the content as an HTML template. It’s a very basic template, just for the example:
And later, we’ll add an image. This is the example of how we can add attachments with relative paths.
The image, that we want to attach, is inside our project. If we simply obtain the file path through the getFile() method of the InputStream object. It’ll fail when we try to send the email. This is because the DataSource can’t found the file/image with that path. However, if we pass the file as an InputStream we wouldn’t have any problem accessing the contents of it. But to do this we will have to create a class that extends from javax.activation.DataSource to store the InputStream. This would be its code.
Finally, all we need to do is to send the mail itself.
If you want to see all the code, you have it here.