2013-08-21 69 views
64

Có sự cố khi gửi hình ảnh qua email dưới dạng hình ảnh được nhúng trong nội dung. Tệp hình ảnh hiển thị dưới dạng tệp đính kèm, nhưng phần hình ảnh nội tuyến chỉ hiển thị dưới dạng dấu x màu đỏ.Gửi hình ảnh nội tuyến qua email

Dưới đây là những gì tôi có cho đến nay

LinkedResource inline = new LinkedResource(filePath); 
inline.ContentId = Guid.NewGuid().ToString(); 
MailMessage mail = new MailMessage(); 
Attachment att = new Attachment(filePath); 
att.ContentDisposition.Inline = true; 
mail.From = from_email; 
mail.To.Add(data.email); 
mail.Subject = "Client: " + data.client_id + " Has Sent You A Screenshot"; 
mail.Body = String.Format(
    "<h3>Client: " + data.client_id + " Has Sent You A Screenshot</h3>" + 
    @"<img src=""cid:{0}"" />", inline.ContentId); 

mail.IsBodyHtml = true; 
mail.Attachments.Add(att); 
+1

Bạn đang không thực sự phụ thêm các LinkedResource đến đối tượng mail; thay vào đó, bạn đang tạo nó nhưng sau đó gắn một đối tượng Đính kèm riêng biệt. –

+2

Vấn đề duy nhất với mã này là string.Format của bạn đang tham chiếu đến 'inline.ContentId', khi nó thực sự là' att.ContentId'. 'inline' là không cần thiết. Tôi thích câu hỏi của bạn cho tất cả các câu trả lời, vì bạn thực sự không cần sử dụng 'AlternateView'. –

+0

Có thể trùng lặp [C# gửi thư với hình ảnh nội tuyến bằng SmtpClient] (http://stackoverflow.com/questions/1212838/c-sharp-sending-mails-with-images-inline-using-smtpclient) –

Trả lời

45

Hãy thử điều này

string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:filename\"></body></html>"; 
AlternateView avHtml = AlternateView.CreateAlternateViewFromString 
    (htmlBody, null, MediaTypeNames.Text.Html); 

LinkedResource inline = new LinkedResource("filename.jpg", MediaTypeNames.Image.Jpeg); 
inline.ContentId = Guid.NewGuid().ToString(); 
avHtml.LinkedResources.Add(inline); 

MailMessage mail = new MailMessage(); 
mail.AlternateViews.Add(avHtml); 

Attachment att = new Attachment(filePath); 
att.ContentDisposition.Inline = true; 

mail.From = from_email; 
mail.To.Add(data.email); 
mail.Subject = "Client: " + data.client_id + " Has Sent You A Screenshot"; 
mail.Body = String.Format(
      "<h3>Client: " + data.client_id + " Has Sent You A Screenshot</h3>" + 
      @"<img src=""cid:{0}"" />", inline.ContentId); 

mail.IsBodyHtml = true; 
mail.Attachments.Add(att); 
+12

Mã này không hoạt động, hãy sử dụng mã bên dưới từ @ T30 và ghi nhớ khi bạn thêm Dạng xem thay thế vào MailMessage mà chế độ xem sẽ là phần nội dung email của bạn và bạn KHÔNG cần điền vào thuộc tính Nội dung. – Eric

1

Bạn cần phải thêm LinkedResource thành một AlternateView

AlternateView alternateView = AlternateView.CreateAlternateViewFromString("<h3>Client: " + data.client_id + " Has Sent You A Screenshot</h3>" + 
       @"<img src=""cid:{0}"" />", null, "text/html"); 
alternateView.LinkedResources.Add(inline); 
mail.AlternateViews.Add(alternateView); 
1

Hãy thử này.


protected void Page_Load(object sender, EventArgs e) 
     { 
      string Themessage = @"<html> 
           <body> 
           <table width=""100%""> 
           <tr> 
            <td style=""font-style:arial; color:maroon; font-weight:bold""> 
            Hi! <br> 
            <img src=cid:myImageID> 
            </td> 
           </tr> 
           </table> 
           </body> 
           </html>"; 
      sendHtmlEmail("[email protected]", "tomailaccount", Themessage, "Scoutfoto", "Test HTML Email", "smtp.gmail.com", 25); 
     } 

protected void sendHtmlEmail(string from_Email, string to_Email, string body, string from_Name, string Subject, string SMTP_IP, Int32 SMTP_Server_Port) 
     { 
      //create an instance of new mail message 
      MailMessage mail = new MailMessage(); 

      //set the HTML format to true 
      mail.IsBodyHtml = true; 

      //create Alrternative HTML view 
      AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html"); 

      //Add Image 
      LinkedResource theEmailImage = new LinkedResource("E:\\IMG_3332.jpg"); 
      theEmailImage.ContentId = "myImageID"; 

      //Add the Image to the Alternate view 
      htmlView.LinkedResources.Add(theEmailImage); 

      //Add view to the Email Message 
      mail.AlternateViews.Add(htmlView); 

      //set the "from email" address and specify a friendly 'from' name 
      mail.From = new MailAddress(from_Email, from_Name); 

      //set the "to" email address 
      mail.To.Add(to_Email); 

      //set the Email subject 
      mail.Subject = Subject; 

      //set the SMTP info 
      System.Net.NetworkCredential cred = new System.Net.NetworkCredential("[email protected]", "fromEmail password"); 
      SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587); 
      smtp.EnableSsl = true; 
      smtp.DeliveryMethod = SmtpDeliveryMethod.Network; 
      smtp.UseDefaultCredentials = false; 
      smtp.Credentials = cred; 
      //send the email 
      smtp.Send(mail); 
     } 
8
protected void Page_Load(object sender, EventArgs e) 
    { 
     string Themessage = @"<html> 
          <body> 
          <table width=""100%""> 
          <tr> 
           <td style=""font-style:arial; color:maroon; font-weight:bold""> 
           Hi! <br> 
           <img src=cid:myImageID> 
           </td> 
          </tr> 
          </table> 
          </body> 
          </html>"; 
     sendHtmlEmail("[email protected]", "tomailaccount", Themessage, "Scoutfoto", "Test HTML Email", "smtp.gmail.com", 25); 
    } 

    protected void sendHtmlEmail(string from_Email, string to_Email, string body, string   from_Name, string Subject, string SMTP_IP, Int32 SMTP_Server_Port) 
    { 
     //create an instance of new mail message 
     MailMessage mail = new MailMessage(); 

     //set the HTML format to true 
     mail.IsBodyHtml = true; 

     //create Alrternative HTML view 
     AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html"); 

     //Add Image 
     LinkedResource theEmailImage = new LinkedResource("E:\\IMG_3332.jpg"); 
     theEmailImage.ContentId = "myImageID"; 

     //Add the Image to the Alternate view 
     htmlView.LinkedResources.Add(theEmailImage); 

     //Add view to the Email Message 
     mail.AlternateViews.Add(htmlView); 

     //set the "from email" address and specify a friendly 'from' name 
     mail.From = new MailAddress(from_Email, from_Name); 

     //set the "to" email address 
     mail.To.Add(to_Email); 

     //set the Email subject 
     mail.Subject = Subject; 

     //set the SMTP info 
     System.Net.NetworkCredential cred = new System.Net.NetworkCredential("[email protected]", "fromEmail password"); 
     SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587); 
     smtp.EnableSsl = true; 
     smtp.DeliveryMethod = SmtpDeliveryMethod.Network; 
     smtp.UseDefaultCredentials = false; 
     smtp.Credentials = cred; 
     //send the email 
     smtp.Send(mail); 
    } 
1
MailMessage mail = new MailMessage(); 
    //set the addresses 
    mail.From = new MailAddress("[email protected]"); 
    mail.To.Add("[email protected]"); 

    //set the content 
    mail.Subject = "Sucessfully Sent the HTML and Content of mail"; 

    //first we create the Plain Text part 
    string plainText = "Non-HTML Plain Text Message for Non-HTML enable mode"; 
    AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainText, null, "text/plain"); 
    XmlTextReader reader = new XmlTextReader(@"E:\HTMLPage.htm"); 
    string[] address = new string[30]; 
    string finalHtml = ""; 
    var i = -1; 
    while (reader.Read()) 
    { 
     if (reader.NodeType == XmlNodeType.Element) 
     { // The node is an element. 
      if (reader.AttributeCount <= 1) 
      { 
       if (reader.Name == "img") 
       { 
        finalHtml += "<" + reader.Name; 
        while (reader.MoveToNextAttribute()) 
        { 
         if (reader.Name == "src") 
         { 
          i++; 
          address[i] = reader.Value; 
          address[i] = address[i].Remove(0, 8); 
          finalHtml += " " + reader.Name + "=" + "cid:chartlogo" + i.ToString(); 
         } 
         else 
         { 
          finalHtml += " " + reader.Name + "='" + reader.Value + "'"; 
         } 
        } 
        finalHtml += ">"; 
       } 
       else 
       { 
        finalHtml += "<" + reader.Name; 
        while (reader.MoveToNextAttribute()) 
        { 
         finalHtml += " " + reader.Name + "='" + reader.Value + "'"; 
        } 
        finalHtml += ">"; 
       } 
      } 

     } 
     else if (reader.NodeType == XmlNodeType.Text) 
     { //Display the text in each element. 
      finalHtml += reader.Value; 
     } 
     else if (reader.NodeType == XmlNodeType.EndElement) 
     { 
      //Display the end of the element. 
      finalHtml += "</" + reader.Name; 
      finalHtml += ">"; 
     } 

    } 

    AlternateView htmlView = AlternateView.CreateAlternateViewFromString(finalHtml, null, "text/html"); 
    LinkedResource[] logo = new LinkedResource[i + 1]; 
    for (int j = 0; j <= i; j++) 
    { 
     logo[j] = new LinkedResource(address[j]); 
     logo[j].ContentId = "chartlogo" + j; 
     htmlView.LinkedResources.Add(logo[j]); 
    } 
    mail.AlternateViews.Add(plainView); 
    mail.AlternateViews.Add(htmlView); 
    SmtpClient smtp = new SmtpClient(); 
    smtp.Host = "smtp.gmail.com"; 
    smtp.Port = 587; 
    smtp.Credentials = new NetworkCredential(
     "[email protected]", "Password"); 
    smtp.EnableSsl = true; 
    Console.WriteLine(); 
    smtp.Send(mail); 
} 
89

Các tối thiểu C# mã để nhúng một hình ảnh có thể là:

MailMessage mailWithImg = getMailWithImg(); 
MySMTPClient.Send(mailWithImg); //* Set up your SMTPClient before! 

private MailMessage getMailWithImg() { 
    MailMessage mail = new MailMessage(); 
    mail.IsBodyHtml = true; 
    mail.AlternateViews.Add(getEmbeddedImage("c:/image.png")); 
    mail.From = new MailAddress("[email protected]"); 
    mail.To.Add("[email protected]"); 
    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 + @"'/>"; 
    AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html); 
    alternateView.LinkedResources.Add(res); 
    return alternateView; 
} 
+2

Tôi phải thêm một loại mime vào 'LinkedResource' để làm cho nó hoạt động trong ứng dụng web của Hotmail/Outlook.com. FWIW, tôi đã thử điều này cũng như @Microsoft DN và điều này làm việc tốt hơn. – gregtheross

+3

Đối với tôi nó hoạt động, nhưng tôi phải thêm ContentType: LinkedResource inline = new LinkedResource (tệpPath, MediaTypeNames.Image.Jpeg); –

+2

Nhận xét nhỏ: không cần phải gọi 'NewGuid()', lớp 'AttachmentBase' (mà' LinkedResource' được kế thừa từ) đã tạo nó nếu cần. – Andrew

0

Ngoài những ý kiến ​​trên, tôi có addi sau đây nhận xét tional:

  • Không trộn lẫn Tệp đính kèm và AlternativeView, sử dụng hoặc cách khác. Nếu bạn trộn chúng, các tệp đính kèm nội dòng sẽ được hiển thị dưới dạng tải xuống không xác định.
  • Trong khi Outlook và Google cho phép chuẩn HTML mang phong cách "cid:att-001" này KHÔNG cơ quan trên iPhone (cuối 2016 vá mức), thay vì sử dụng alpha tinh khiết số "cid:att-001" -> "cid:att001"

Là một sang một bên. Triển vọng Outlook (thậm chí Office 2015) (vẫn là đa số rõ ràng cho người dùng kinh doanh) yêu cầu sử dụng TABLE TR TD style HTML vì nó không hỗ trợ đầy đủ mô hình hộp HTML.

-1

Giải pháp khác là đính kèm hình ảnh dưới dạng tệp đính kèm và sau đó tham chiếu mã html bằng cách sử dụng cid. HTML Code:

<html> 
<head> 
</head> 
<body> 
    <img width=100 height=100 id=""1"" src=""cid:Logo.jpg""> 
</body> 
</html> 

C# Code:

EmailMessage email = new EmailMessage(service); 
email.Subject = "Email with Image"; 
email.Body = new MessageBody(BodyType.HTML, html); 
email.ToRecipients.Add("[email protected]"); 
string file = @"C:\Users\acv\Pictures\Logo.jpg"; 
email.Attachments.AddFileAttachment("Logo.jpg", file); 
email.Attachments[0].IsInline = true; 
email.Attachments(0).ContentId = "Logo.jpg"; 
email.SendAndSaveCopy(); 
0

gửi 2 hình ảnh đang vb.net chuyển đổi cho C# Chuyển đổi trực tuyến.

Public Function SendEmail(Optional ByVal p_AsHTML As Boolean = False, Optional ByVal p_themEmail As String = "") As Boolean 
      Dim client As SmtpClient = New SmtpClient ''("FMSERVER.FMINNOVATIONS.COM.AU") 
      'Dim fromAddress As MailAddress = New MailAddress(Me.FromEmail, "WSMenterprise") 
      'Dim toAddress As MailAddress 
      Try 
       Dim aMessage As New MailMessage() 
       '(New MailAddress(Me.FromEmail, "WSMenterprise"), New MailAddress(anAdd)) 
       If _fromAddress IsNot Nothing Then 
        If _fromName IsNot Nothing Then 
         aMessage.From = New MailAddress(_fromAddress, _fromName) 
        Else 
         aMessage.From = New MailAddress(_fromAddress) 
        End If 
       End If 
       For Each anAdd As String In _To 
        aMessage.To.Add(New MailAddress(anAdd)) 
       Next 
       For Each cc As String In _CC 
        aMessage.CC.Add(New MailAddress(cc)) 
       Next 
       For Each bcc As String In _BCC 
        aMessage.Bcc.Add(New MailAddress(bcc)) 
       Next 
       aMessage.Subject = _Subject 
       aMessage.IsBodyHtml = p_AsHTML 

       If _EmailLogo Is Nothing Then 
        aMessage.Body = _Body 
       Else 
        If p_themEmail.ToString().ToLower.Contains("dexus") Then 

         Dim htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), Nothing, "text/html") 
         Dim logo As New LinkedResource(_EmailLogo) 
         logo.ContentId = "Dexuslogo1" 
         Dim logo1 As New LinkedResource(_EmailLogo1) 
         logo1.ContentId = "Dexuslogo2" 
         htmlView.LinkedResources.Add(logo) 
         htmlView.LinkedResources.Add(logo1) 
         aMessage.AlternateViews.Add(htmlView) 

        Else 

         Dim htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), Nothing, "text/html") 
         Dim logo As New LinkedResource(_EmailLogo) 
         logo.ContentId = "companylogo" 
         htmlView.LinkedResources.Add(logo) 
         aMessage.AlternateViews.Add(htmlView) 
        End If 
       End If 

       For Each anAttach As Attachment In _Attachments 
        aMessage.Attachments.Add(anAttach) 
       Next 

       If _ReplyTo IsNot Nothing Then aMessage.ReplyToList.Add(New MailAddress(_ReplyTo)) 
       client.Host = "smtpi.cbre.com.au" 
       client.UseDefaultCredentials = True 
       client.Send(aMessage) 
      Catch exRecipUnk As SmtpFailedRecipientException 
       Return False 
      Catch exSmtp As SmtpException 
       ''exSmtp.StatusCode 
       Return False 
      Catch ex As Exception 
       Return False 
      End Try 
      Return True 
     End Function 
    If p_Gmap_code = "DE" Then 
       Dim p_Theme As New Theme("Dexus") 
       Dim passwordlink As String = "" 
       Dim DexuslogoImage1 As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\Dexus_Notice_Logo.png") 
       Dim DexuslogoImage2 As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\DexusTenantNotice.png") 

       passwordlink = "<a href='" + p_Theme.TenantLoginPage + "?accesstype=email&te=" + a.Encrypt(p_TenantEmail) + "' target='_blank'>here.</a><br/>" 
       bodys += "<div align='Center'><table border='0' cellpadding='0' cellspacing='0'><tr style='height:50px;'><td width='623px' ></td><td valign='top' width='180'><p align='right'><a href='http://www.dexus.com/'><img border='0' height='50' src=cid:Dexuslogo1 width='174' alt=''/></a></p></td></tr><tr><td colspan='2' width='803' style='height:25px;'></td></tr> <tr><td width='623px'><p align='left' style='font-family:Arial;font-size:14pt;'><strong> Your Dexus Response Password is about to expire</strong></p></td>" 
       bodys += " <td width='180'><p align='right' style='font-family:Arial;font-size:10pt;'>" + DateTime.Now.ToString("dd/MM/yyyy") + " </p>" 
       bodys += "</td></tr><tr><td colspan='2' width='803' style='height:30px;'> </td></tr> <tr> <td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'>" 
       bodys += "<p>" + wishes + " " + p_TenantName.Trim().ToString() + "</p>" 
       bodys += "</td></tr><tr><td colspan='2' width='803' style='height:25px;'></td> </tr><tr><td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'>" 
       bodys += "Your Dexus Response password is about to expire in " + p_remaindays.ToString() + " days.<br /><br /> To reset your password and update your details, please click " + passwordlink.ToString() + "<br /><br />Please note that if you do not update your password by " + p_date + ",then your account will be set to inactive and you will not be able to access Dexus Response.</br></br>Please contact Dexus Response if you require assistance in accessing the portal.</p></td>" 'edit 
       bodys += " </tr><tr><td colspan='2' width='803' style='height:30px;'></td></tr><tr><td colspan='2' width='803'><table align='left' border='0' cellpadding='0' cellspacing='0'><tr><td width='802' style='font-family:Arial;font-size:10pt;'><p><strong>Dexus Response</strong></p></td></tr><tr><td width='802' style='font-family:Arial;font-size:10pt;'><p><a href='mailto:[email protected]'>[email protected]</a> <strong>|</strong> 1300 339 870 <strong>|</strong> <a href='https://response.dexus.com/'>response.dexus.com</a></p></td></tr></table></td></tr><tr><td colspan='2' width='803' style='height:15px;'></td></tr><tr> <td colspan='2' width='803'><p> </p><p><a href='https://response.dexus.com/' border='0' target='_blank'><img border='0' height='133'" 
       bodys += "src=cid:Dexuslogo2 alt='' width='800' /></a></p></td></tr><tr><td colspan='2' width='803' style='height:10px;'></td></tr><tr><td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'><p><a href='http://www.dexus.com/who-we-are/terms-and-conditions' style=' color:#000000;'>Terms and Conditions</a><strong> | </strong><a href='http://www.dexus.com/who-we-are/privacy-policy' style=' color:#000000;'> Privacy Policy</a></p></td></tr><tr><td colspan='2' width='803' style='height:40px;'></td></tr><tr><td colspan='2' width='803'><p></p></td></tr><tr><td colspan='2' width='803' style='height:10px;'></td></tr><tr></tr><tr><td colspan='2' width='803' style='height:20px;'></td></tr></table></div>" 

       email = New Common.Email(emailHeading, bodys, p_Theme.EmailFrom, DexuslogoImage1, DexuslogoImage2) 
       email.ToEmail = p_TenantEmail 
       email.SendEmail(True, p_Theme.EmailFrom) 
0

Một thậm chí tối giản hơn ví dụ:

var linkedResource = new LinkedResource(@"C:\Image.jpg", MediaTypeNames.Image.Jpeg); 

// My mail provider would not accept an email with only an image, adding hello so that the content looks less suspicious. 
var htmlBody = $"hello<img src=\"cid:{linkedResource.ContentId}\"/>"; 
var alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html); 
alternateView.LinkedResources.Add(linkedResource); 

var mailMessage = new MailMessage 
{ 
    From = new MailAddress("[email protected]"), 
    To = { "[email protected]" }, 
    Subject = "yourSubject", 
    AlternateViews = { alternateView } 
}; 

var smtpClient = new SmtpClient(); 
smtpClient.Send(mailMessage); 
Các vấn đề liên quan