嵌入式電子郵件圖像故障排除:Content ID 方法
將圖像直接嵌入電子郵件正文中可以提高可讀性和用戶參與度。 這是通過將圖像鏈接到唯一的內容 ID 來實現的。但是,可能會出現問題,導致圖像顯示為破碎的紅色“X”,而不是正確渲染。
解決方案:使用 Content ID 正確嵌入圖像
以下代碼提供了使用 Content ID 嵌入圖像的強大解決方案:
<code class="language-csharp">MailMessage mailWithImg = GetMailWithImg(); MySMTPClient.Send(mailWithImg); // Ensure MySMTPClient is properly configured beforehand private MailMessage GetMailWithImg() { MailMessage mail = new MailMessage(); mail.IsBodyHtml = true; mail.AlternateViews.Add(GetEmbeddedImage("c:/image.png")); mail.From = new MailAddress("yourAddress@yourDomain"); mail.To.Add("recipient@hisDomain"); mail.Subject = "yourSubject"; return mail; } private AlternateView GetEmbeddedImage(string filePath) { LinkedResource res = new LinkedResource(filePath); res.ContentId = Guid.NewGuid().ToString(); string htmlBody = $"<img src=\"cid:{res.ContentId}\">"; //Simplified HTML AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html); alternateView.LinkedResources.Add(res); return alternateView; }</code>
說明:
此改進的代碼片段可確保正確的圖像嵌入:
GetMailWithImg()
設置電子郵件,啟用 HTML 格式並添加嵌入圖像。 GetEmbeddedImage()
處理圖像加載,通過 Guid.NewGuid()
分配唯一的內容 ID,並正確格式化 HTML <img>
標記。 請注意簡化和更正的 HTML。 AlternateView
已正確構造並添加到 MailMessage
中。 此方法的優點:
這種方法將圖像直接嵌入到電子郵件中,提高了視覺吸引力並避免了單獨附件的需要。 這會帶來更乾淨、更專業的電子郵件演示。
以上是為什麼我的嵌入式電子郵件圖像顯示為紅色 X 而不是渲染?的詳細內容。更多資訊請關注PHP中文網其他相關文章!