2011-10-18 76 views
0

我正在處理髮送電子郵件的應用程序。我想發送正文消息爲RTF格式。當我嘗試以RTF格式發送消息時,它會創建附件文件而不是正文消息。如何使用JavaMail API以RTF格式發送正文消息?

public boolean run() { 
    System.out.println("START SENDING"); 



    Transport transport = null; 
    Session mailSession = null; 
    Properties props = null; 
    try { 

     props = new Properties(); 
     props.put("mail.smtp.starttls.enable", true); 
     props.put("mail.smtp.host", smtpServer); 
     props.put("mail.smtp.port", port); 
     props.put("mail.smtp.user", user); 
     props.put("mail.smtp.password", password); 
     props.put("mail.smtp.auth", auth); 
     props.put("mail.smtp.ssl.enable", false); 
     props.put("mail.smtp.ssl.trust", "*"); 


     mailSession = Session.getInstance(props, new SMTPAuthenticator(user, password)); 

     transport = mailSession.getTransport("smtp"); 
     MimeMessage message = prepareMessage(mailSession, "UTF-8", 
       user, subject, HtmlMessage, recipientsString); 
     BodyPart messageBodyPart = new MimeBodyPart(); 
     messageBodyPart.setText(HtmlMessage); 
     Multipart multipart = new MimeMultipart(); 
     multipart.addBodyPart(messageBodyPart); 
     messageBodyPart = new MimeBodyPart(); 

     if (file != null) { 
      DataSource source = new FileDataSource(file.getAbsoluteFile()); 
      messageBodyPart.setDataHandler(new DataHandler(source)); 
      messageBodyPart.setFileName(file.getName()); 
      multipart.addBodyPart(messageBodyPart); 
      message.setContent(multipart); 
     } else { 

      /*HtmlMessage (String)*/ 
      message.setContent(HtmlMessage, "text/rtf"); 
     } 
     transport.connect(); 
     Transport.send(message); 
     System.out.println("SEND DONE"); 

    } catch (Exception ex) { 
     JOptionPane.showMessageDialog(this, "Unable to send Message."); 
     ex.printStackTrace(); 
    } finally { 

     System.out.println(mailSession.getProperty("mail.smtp.user")); 
     mailSession = null; 

     props.clear(); 
     smtpServer = null; 
     user = null; 
     password = null; 
     if (t != null && t.isAlive()) { 
      t.interrupt(); 
      t = null; 
     } 
     this.dispose(); 
    } 
    return false; 
} 
+0

你解決這個問題呢?提供的答案是否正確? –

回答

0

爲了有一個消息正文部分是固定的,而不是內聯,這樣做:

messageBodyPart.setDisposition(Part.INLINE);