简体   繁体   中英

How to get the attachment full path of an email in java

Almost all java examples showing how to send an email set dummy file path. But actually we don't know the path before file selection. I have already known input=file can't get the full path of the file due to security problems. Then how can I get the path as email function must use path?

Here is the part in most examples that would use file path

String path = "D:\\jar\\java-json.jar";
String fileName = "java-json.jar";
DataSource source = new FileDataSource(path);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);

Have you tried Apache Commons Email library? It has features for email attachments, and it has built-in support for java servlet integration.

OK, at last it shows most java email examples on Internet are not useful for web browsers as web browser can't get full path of a file. At last I use the InputStream to get the file and put it into the DataSource. These two lines are the keys:

InputStream filecontent = filePart.getInputStream();
DataSource source = new ByteArrayDataSource(filecontent, "Text/txt");

If you are using 'java-mail-1.4.*.jar' then simply do this... you use 'JFileChooser' to create file chooser popups, then may be (say) in your actionListner method for a button do the following -

 filepath = fc.getSelectedFile().getAbsolutePath();

where 'filepath' is a String, and 'fc' is a object to 'JFileChooser' class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM