2013-08-01 43 views
1

在我的程序中我必須使用java發送郵件。程序正確發送郵件,但服務器自動添加一個標誌。結果是收到的電子郵件包含正確的正文,但帶有html標籤的簽名。用java發送的郵件包含不正確的html標誌

Correct body..... 
</pre> 
<html> 
<i> 
Sent by me 
<i> 
<br> 
<br> 
</html> 

我發郵件與後續代碼:

Properties props = new Properties(); 
    props.put("mail." + protocol + ".host", smtpHost); 
    props.put("mail." + protocol + ".port", smtpPort); 
    Session session = Session.getDefaultInstance(props, null); 

    // Construct the message 
    Message msg = new MimeMessage(session); 
    msg.setFrom(new InternetAddress(user)); 
    msg.setRecipients(RecipientType.TO, loadAddress()); 
    msg.setSubject(subject); 
    msg.setText(body); 

    // Send the message 
    props.put("mail." + protocol + ".auth", "false"); 
    Transport t = session.getTransport(protocol); 
    try { 
     t.connect(); 
     t.sendMessage(msg, msg.getAllRecipients()); 
    } finally { 
     t.close(); 
    } 

編輯:我試圖插入後續代碼:

BodyPart messageBodyPart = new MimeBodyPart(); 
    messageBodyPart.setText(body); 
    Multipart multipart = new MimeMultipart(); 
    multipart.addBodyPart(messageBodyPart); 

    msg.setContent(multipart); 

但結果並沒有改變。我創建身體的功能是:

public void setBody(ArrayList<User> users) { 

    Calendar c = Calendar.getInstance(); 
    c.add(Calendar.DATE, -1); 
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 
    String formattedDate = df.format(c.getTime()); 
    subject = new String("Day " + formattedDate); 
    body += "Hi " 
     + formattedDate;  
} 

任何想法?

+0

你嘗試用[MimeBodyPart.setContent()](http://docs.oracle.com/javaee/7/api/javax/mail/ internet/MimeBodyPart.html#setContent(java.lang.Object,java.lang.String))? – NINCOMPOOP

+0

你可以參考下面的鏈接 http://stackoverflow.com/questions/9942575/sending-image-to-mail-by-java-program-without-attaching – muthukumar

+0

你可以通過你保存身體的部分嗎? – Deckard27

回答

0

最後我解決插入如下代碼:

MimeBodyPart mbp1 = new MimeBodyPart(); 
    mbp1.setContent(body, "text/html"); 
    Multipart mp = new MimeMultipart(); 
    mp.addBodyPart(mbp1); 

    msg.setContent(mp, "text/html"); 
0

嘗試使用Message類中的.setContent(Object o, String s)方法,將您的主體作爲字符串放入Object參數中,並在第二個參數中放入類似「text/html」的內容以定義內容類型。

+0

我在嘗試此解決方案,但結果不會改變 – hasmet

相關問題