1

I have some code

String url = http://site/some-file.pdf

HttpURLConnection fileRequest = (HttpURLConnection) new URL(fileUrl).openConnection();
            Path file = Files.createFile(Paths.get("mydirectory" + "filename" +".pdf"));
            Files.write(file, IOUtils.toByteArray(fileRequest.getInputStream()));

This code writes gets file from url and write it to my local home(disk D, for instance)

How to make it attached to mail sender without saving locally? Is it possible?

John Newell
  • 39
  • 2
  • 7
  • You can save the file into byte array instead of file system and then attach it to your mail. for saving file to byte array check [this](https://stackoverflow.com/questions/2295221/java-net-url-read-stream-to-byte), and for attaching it to mail [this](https://stackoverflow.com/questions/23083574/mail-attachments-with-byte-array) might help you. – Prabhat Jul 24 '17 at 14:07
  • You mean replace piece of code below and write 1. Saving file to byte array and attaching it to mail? – John Newell Jul 24 '17 at 14:37
  • Yes, Instead of code for saving the file from that url to D drive, write the code to save it to `ByteArray[]` and then attach that `ByteArray[]` to your mail. Check the links I provided for help. https://stackoverflow.com/questions/2295221/java-net-url-read-stream-to-byte and https://stackoverflow.com/questions/23083574/mail-attachments-with-byte-array – Prabhat Jul 24 '17 at 14:41

1 Answers1

8

You can use the javax.activation.URLDataSource:

Part attachment = new MimeBodyPart();
URL url = new URL("http://site/some-file.pdf");
URLDataSource uds = new URLDataSource(url);
attachment.setDataHandler(new DataHandler(uds));
attachment.setDisposition(Part.ATTACHMENT);
attachment.setFileName(url.getFile());

According to the documentation you can simplify that code by just using DataHandler and a URL

Part attachment = new MimeBodyPart();
URL url = new URL("http://site/some-file.pdf");
attachment.setDataHandler(new DataHandler(url));
attachment.setDisposition(Part.ATTACHMENT);
attachment.setFileName(url.getFile());
jmehrens
  • 10,580
  • 1
  • 38
  • 47
  • @jrehrens When i set url so returning 403. so how can i handle it? – Akash Chavda Nov 23 '20 at 07:02
  • @AkashChavda See: [Connecting to remote URL which requires authentication using Java](https://stackoverflow.com/questions/496651/connecting-to-remote-url-which-requires-authentication-using-java). The default authenticator might be the only option you can combine with JavaMail. Otherwise, you have to store locally. – jmehrens Nov 23 '20 at 16:04