2012-07-26 4 views
1

파일 업로드를 위해 아파치 공유 파일 업로드를 사용하고 있습니다. 이 파일을 이메일에 첨부하고 싶습니다. 임시 파일에 쓰고 싶지 않지만 데이터를 메모리에 보관하고 첨부 파일로 보내려고합니다. 나는 여기서 방향이 필요해. 미리 감사드립니다업로드 된 파일을 이메일로 첨부하십시오.

DiskFileItemFactory factory = new DiskFileItemFactory(); 
       PortletFileUpload upload = new PortletFileUpload(factory); 
       List items = upload.parseRequest(request); 

       Iterator iter = items.iterator(); 

       while(iter.hasNext()) { 
        FileItem item = (FileItem) iter.next(); 
        if(item.isFormField()) { 

         String name = item.getFieldName(); 
         String value = item.getString(); 
         response.setRenderParameter(name, value); 

        } else { 

         String fieldName = item.getFieldName(); 
         String fileName = item.getName(); 
         //String contentType = item.getContentType(); 
         boolean isInMemory = item.isInMemory(); 
         long sizeInBytes = item.getSize(); 

         InputStream uploadedStream = item.getInputStream(); 

        } 
       } 

UPDATE I가 첨부 파일과 작업 벌금 이메일을 보내는 다음과 같은 방법 서명.

sendWithFileAttachment (String[] recipients, 
      String subject, 
      File message, 
      String from, 
      String filename) { 

      BodyPart messageBodyPart = new MimeBodyPart(); 

    // Fill the message 
    messageBodyPart.setText("Pardon Ideas"); 

    Multipart multipart = new MimeMultipart(); 
    multipart.addBodyPart(messageBodyPart); 

    // Part two is attachment 
    messageBodyPart = new MimeBodyPart(); 
    DataSource source = new FileDataSource(message); 
    messageBodyPart.setDataHandler(new DataHandler(source)); 
    messageBodyPart.setFileName(filename); 
    multipart.addBodyPart(messageBodyPart); 

    // Put parts in message 

    msg.setContent(multipart); 

    Transport.send(msg); 

}

업데이트 2 : 난 당신의 코드를 실행 한 후 아래의 오류를 얻고있다. 당신은 당신은 스트림을 통해 자신의 콘텐츠를 할 수 있도록 (당신이 가장 가능성이 내가 가정 사용)의 MimeBodyPart를 재정의해야이

HIT ME! 15782 
Jul 31, 2012 11:17:56 AM test.test.EmailUtility1$InputStreamMimeBodyPart getContentStream 
SEVERE: null 
Throwable occurred: java.io.IOException: Stream closed 
    at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:156) 
    at java.io.BufferedInputStream.reset(BufferedInputStream.java:425) 
    at test.test.EmailUtility1$InputStreamMimeBodyPart.getContentStream(EmailUtility1.java:174) 
    at javax.mail.internet.MimePartDataSource.getInputStream(MimePartDataSource.java:94) 
    at javax.activation.DataHandler.writeTo(DataHandler.java:302) 
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350) 
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:845) 
    at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:361) 
    at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:85) 
    at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:881) 
    at javax.activation.DataHandler.writeTo(DataHandler.java:314) 
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350) 
    at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1683) 
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:585) 
    at javax.mail.Transport.send0(Transport.java:169) 
    at javax.mail.Transport.send(Transport.java:98) 
    at test.test.EmailUtility1.sendWithFileAttachment(EmailUtility1.java:155) 
    at test.test.TestEmail.main(TestEmail.java:32) 
Exception in thread "main" javax.mail.MessagingException: IOException while sending message; 
    nested exception is: 
    java.io.IOException: Stream closed 
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:625) 
    at javax.mail.Transport.send0(Transport.java:169) 
    at javax.mail.Transport.send(Transport.java:98) 
    at test.test.EmailUtility1.sendWithFileAttachment(EmailUtility1.java:155) 
    at test.test.TestEmail.main(TestEmail.java:32) 
Caused by: java.io.IOException: Stream closed 
    at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:156) 
    at java.io.BufferedInputStream.read(BufferedInputStream.java:319) 
    at java.io.FilterInputStream.read(FilterInputStream.java:101) 

답변

1

좀 도와 주시겠습니까.

public void sendWithFileAttachment(String recipient, 
       String subject, 
       InputStream message, 
       String from, 
       String filename) throws MessagingException { 
    MimeMessage msg = new MimeMessage(getSession()); 

    // set the from and to address 
    InternetAddress addressFrom = new InternetAddress(from); 
    msg.setFrom(addressFrom); 

    InternetAddress addressTo = new InternetAddress(recipient); 
    msg.setRecipient(Message.RecipientType.TO, addressTo); 

    BodyPart messageBodyPart = new MimeBodyPart(); 

    // Fill the message 
    messageBodyPart.setText("Pardon Ideas"); 

    Multipart multipart = new MimeMultipart(); 
    multipart.addBodyPart(messageBodyPart); 

    // Part two is attachment 
    messageBodyPart = new InputStreamMimeBodyPart(message); 
    messageBodyPart.setFileName(filename); 
    multipart.addBodyPart(messageBodyPart); 

    // Put parts in message 

    msg.setContent(multipart); 

    Transport.send(msg); 
    // important: you need to close the message stream manually 
    try { 
     message.close(); 
    } catch (IOException ex) { 
     // meh. So what. 
    } 

} 

private class InputStreamMimeBodyPart extends MimeBodyPart { 

private InputStream inputStream; 

    public InputStreamMimeBodyPart(InputStream source) { 
     this.inputStream = source; 
     if(!inputStream.markSupported()) { 
      throw new IllegalArgumentException("only streams with mark supported are ok"); 
     } 
     inputStream.mark(Integer.MAX_VALUE); // remeber the whole stream. 
    } 

    @Override 
    protected InputStream getContentStream() throws MessagingException { 
     throw new IllegalStateException("getContentStream is not implemented on purpose."); 
    } 

    @Override 
    public void writeTo(OutputStream os) throws IOException, MessagingException { 
     System.out.println("writing to somewhere."); 
     byte[] buf = new byte[32]; 
     int length; 
     inputStream.reset(); 
     while((length = inputStream.read(buf)) > -1) { 
      os.write(buf, 0, length); 
     } 
    } 
} 

private Session getSession() { 
    // here you do authentication etc. 
    Properties properties = new Properties(); 
    return Session.getInstance(properties); 
} 
+0

업데이트를 찾아주세요. – user525146

+0

도와 주실 수 있나요? – user525146

+0

@ user525146 여기 있습니다. 당신은 당신의 질문에 귀하의 방법 중 일부를 생략하여 적응해야 할 것입니다. InputStreams가 반드시 마크 기능을 지원해야한다는 것을 알아야한다. 왜냐하면이 구현 (내 컴퓨터에서)에서 메일 API는 'getContentStream'을 두 번 호출하기 때문입니다. 나는 그것이 왜 그렇게하는지 알아 내지 못했지만, 그렇게 할 이유가없는 한, 나는 걱정하지 않을 것입니다. –

관련 문제