2011-12-07 25 views
1

我有從本地主機SMTP與iText的創建PDF附件,我提出以下How to create an in-memory PDF report and send as an email attachment using iText and Java,它正在發送電子郵件了網頁的鏈接,但是當我得到的電子郵件,我看不到發件人名稱/地址。(未知發件人)發送與Java應用程序在iText的創建PDF附件的電子郵件時

它顯示爲來自「(未知發件人)」在我的Gmail收件箱,如果我打回復「到」盒子是完全空白的。在Hotmail顯示爲「(未知)」,但當我打開它,發件人顯示爲「[email protected]代表(未知)」

當我通過telnet在服務器上測試SMTP時,我所編寫的發件人名稱通過很好。我怎樣才能得到它顯示了當應用程序發送電子郵件?

下面是發送電子郵件的代碼:使用mimeMessage.setFrom(...)而不是mimeMessage.setSender(...)

String smtpHost = "localhost"; 
    int smtpPort = 25; 
    String sender = "[email protected]"; 
    String[] recipient = pdfEmail.replaceAll("\\ ", "").split(","); 
    String content = "whatever"; 
    String subject = "whatever"; 

    Properties props = new Properties(); 
    props.put("mail.smtp.host", smtpHost); 
    props.put("mail.smtp.user", sender); 
    props.put("mail.smtp.port", smtpPort); 

    Session session = Session.getDefaultInstance(props, null); 

    ByteArrayOutputStream outputStream = null; 

    try {   
     //construct the text body part 
     MimeBodyPart textBodyPart = new MimeBodyPart(); 
     textBodyPart.setText(content); 

     //now write the PDF content to the output stream 
     outputStream = new ByteArrayOutputStream(); 
     writePdf(outputStream); //creates PDF 
     byte[] bytes = outputStream.toByteArray(); 

     //construct the pdf body part 
     DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf"); 
     MimeBodyPart pdfBodyPart = new MimeBodyPart(); 
     pdfBodyPart.setDataHandler(new DataHandler(dataSource)); 
     pdfBodyPart.setFileName("test.pdf"); 

     //construct the mime multi part 
     MimeMultipart mimeMultipart = new MimeMultipart(); 
     mimeMultipart.addBodyPart(textBodyPart); 
     mimeMultipart.addBodyPart(pdfBodyPart); 

     //create the sender/recipient addresses 
     InternetAddress iaSender = new InternetAddress(sender);  
     InternetAddress[] toAddress = new InternetAddress[recipient.length]; 

     // To get the array of addresses 
     for(int i=0; i < recipient.length; i++) { 
      toAddress[i] = new InternetAddress(recipient[i]); 
     } 

     //construct the mime message 
     MimeMessage mimeMessage = new MimeMessage(session); 

     for(int i=0; i < toAddress.length; i++) { 
      mimeMessage.addRecipient(Message.RecipientType.TO, toAddress[i]); 
     } 

     mimeMessage.setSender(iaSender); 
     mimeMessage.setSubject(subject); 
     mimeMessage.setRecipients(Message.RecipientType.TO, toAddress); 
     mimeMessage.setContent(mimeMultipart); 

     //send off the email   
     Transport.send(mimeMessage); 

    } catch(Exception ex) { 
     ex.printStackTrace(); 
    } finally { 
     //clean off 
     if(null != outputStream) { 
      try { outputStream.close(); outputStream = null; } 
      catch(Exception ex) { } 
     } 

    } 
} 

回答

3

嘗試。

+0

我欠你......這是非常有益的 –

相關問題