2012-12-27 54 views
0

我有問題發送內嵌HTML到電子郵件使用SMTP/.NET郵件。我已經嘗試過標準類以及MailDefininition類,但是我一直在獲取內聯的原始代碼,而不是翻譯後的頁面。SMTP客戶端不翻譯內嵌HTML

我知道這可能是我想念的小事,下面是我的代碼。由於

 public static void SendMail(string toAddress, string subject, string messageBody) 
    { 
     MailDefinition message = new MailDefinition(); 
     message.CC = MailCCAddress; 
     message.From = "[email protected]"; 
     message.Subject = subject; 
     message.IsBodyHtml = true; 
     ListDictionary replacements = new ListDictionary(); 

     System.Net.Mail.MailMessage fileMsg; 
     fileMsg = message.CreateMailMessage(toAddress, replacements, messageBody, new System.Web.UI.Control()); 

     string _hostName = HostName; 

     SmtpClient client = new SmtpClient(_hostName); 
     client.Credentials = CredentialCache.DefaultNetworkCredentials; 
     //client.Send(message); 
     client.Send(fileMsg); 
    } 

回答

1

如果仍有問題,您也可以設置MailMessage機身編碼。例如,

//Nick's code 
MailMessage mail = new MailMessage("[email protected]", toAddress, subject, messageBody); 
mail.IsBodyHtml = true; 

//set encoding 
mail.BodyEncoding = Encoding.UTF8; //or SevenBit, etc, whatever is appropriate. 

//send 
SmtpClient client = new SmtpClient(_hostName); 
client.Send(mail); 

您也可以使用AlternateViews集合,讓你的MIME類型內容的更好的控制(這樣你就可以將其指定爲text/html等)。你也可以用這個來選擇包括這兩個一個純文本版本和一個HTML版本,如下所示:

//create the mail message 
MailMessage mail = new MailMessage("[email protected]", toAddress) { Subject = subject }; 

//first we create the Plain Text part 
AlternateView plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain"); 
//then we create the Html part 
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", null, "text/html"); 

//add both views 
mail.AlternateViews.Add(plainView); 
mail.AlternateViews.Add(htmlView); 

//send the message as before 
0
MailMessage mail = new MailMessage("[email protected]", toAddress, 
    subject, messageBody); 

mail.IsBodyHtml = true; 
SmtpClient client = new SmtpClient(_hostName); 
client.Send(mail); 

如果不工作,那麼它可能是您的消息體的一個問題。您可以嘗試調試代碼並查看messageBody是否存在問題,而不是正確的html或可能會有一些字符被轉義。