2013-02-25 102 views
1

我被卡住的問題與this 完全相同,並且發佈的解決方案能夠解決我的問題。 但現在的問題是,收到附件時,沒有名稱。在我的方法中,我要求接收者的電子郵件ID,主題,內容,文件名和字節[]爲文件。我傳遞的文件格式沒有問題,但問題在於名稱。收件人將「noname」作爲文件名。我們如何指定我們選擇的文件名。我作爲參數傳遞的文件名不會被反映出來。請建議。從字節數組創建文件對象時指定文件名(不創建物理文件)

的代碼,我現在用的就是

File file = new File("D:/my docs/Jetty.pdf"); 
int len1 = (int)(file.length()); 
FileInputStream fis1 = null; 
try { 
    fis1 = new FileInputStream(file); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} 
byte buf1[] = new byte[len1]; 
try { 
    fis1.read(buf1); 
    EmailServiceClient.sendEmailWithAttachment("[email protected]", "[email protected]", "Hi", "PFA", "Jetty.pdf", buf1); 

    System.out.println("SENT"); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

我給這家電子郵件服務的實現放在這裏

public void sendEmailWithAttachment(String emailIdTo, String emailIdFrom, String subject, String content, 
    final String fileName, byte[] file) { 
MimeMessage message = mailSender.createMimeMessage(); 
try { 
    MimeMessageHelper helper = new MimeMessageHelper(message, true); 
    helper.setTo(emailIdTo); 
    helper.setFrom(emailIdFrom); 
    helper.setSubject(subject); 
    helper.setText(content, true); 
    helper.addInline("attachment", new ByteArrayResource(file) { 
     @Override 
     public String getFilename() { 
      return fileName; 
     } 
    }); 
    mailSender.send(message); 
} catch (MessagingException e) { 
    throw new MailParseException(e); 
}} 

請搞清楚了這一點

回答

1

從Spring文檔我可以有人幫忙說內聯元素除了contentId之外沒有特殊名稱。也許你想添加一個附件,而不是使用addAttachment方法?然後你可以爲你的文件命名。

http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/mail/javamail/MimeMessageHelper.html

+0

感謝您的回覆@toomasr但我以前的問題是我剛纔提到的鏈接。我的問題是在不創建物理文件的情況下在電子郵件中添加附件,而解決方案的確有竅門。但現在收到的電子郵件附件沒有任何名稱,我不知道如何解決這個問題。 – 2013-02-25 05:11:40

+0

謝謝@toomasr,事情奏效! :) – 2013-02-25 05:32:49