【问题标题】:How to send a non-local attachment with JavaMail如何使用 JavaMail 发送非本地附件
【发布时间】:2011-07-07 13:27:30
【问题描述】:

我正在使用 jsp、servlet 和所有有趣的东西构建一个应用程序。现在,我有一个表单,它将表单中的所有信息传递给使用 JavaMail API 发送的 html 电子邮件。它有效,但我正在尝试发送附件,而我现在设置它的方式不起作用...

<div class="section">Upload Files: <input id="fileUpload" type="file" /></div>

我获取此输入的值,将其传递给我的 servlet 并尝试发送电子邮件。问题是当文件发送时,servlet 找不到文件,因为这个标签给了它路径

C:\fakepath\file.doc

任何帮助都会很棒。

【问题讨论】:

    标签: java jsp jakarta-mail attachment


    【解决方案1】:

    我想通了。 fakepath 是浏览器中的一项安全功能。使用 tomcat 会发生什么,该文件实际上存储在 tomcat 文件夹内的临时文件夹中。所以我只需要使用一个 tomcat 库,commons.fileupload,然后我用它来从文件中提取数据,而不管 fakepath 的位置。

    //Handle File Upload for the attachment
               ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
    
                try{
                List fileItemsList = servletFileUpload.parseRequest(request);
    
                //TODO: Take datafile input from the field and pass the file name so that we can view the file name
    
                Iterator it = fileItemsList.iterator();
                while (it.hasNext()){
                  FileItem fileItem = (FileItem)it.next();
                  if (fileItem.isFormField()){
                    /* The file item contains a simple name-value pair of a form field */
                  }
                  else{ //do what you want with the file}
    

    然后我将它传递给我的邮件实用程序,将文件名更改为正确的名称以具有正确的扩展名,并且它起作用了。当然,您必须将表单编码为多部分表单,并且您还必须使 Mime 消息多部分。但毕竟它相当简单。

        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(body, "text/html");
    
    
    
        MimeBodyPart attachFilePart = new MimeBodyPart();
        FileDataSource fds = 
            new FileDataSource(file);
        attachFilePart.setDataHandler(new DataHandler(fds));
        attachFilePart.setFileName(fileName);
    
    
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(textPart);
        mp.addBodyPart(attachFilePart);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      • 2013-06-13
      • 2013-06-12
      • 2013-04-27
      相关资源
      最近更新 更多