在电子邮件中发送内联图片

Tsu*_*asa 95 c# email smtp inline image

通过电子邮件将图像作为嵌入图像发送到正文中时出现问题.图像文件显示为附件,但是内嵌图像部分显示为红色x.

这是我到目前为止所拥有的

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);
Run Code Online (Sandbox Code Playgroud)

T30*_*T30 138

嵌入图像的最小c#代码可以是:

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("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 + @"'/>";
    AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
    alternateView.LinkedResources.Add(res);
    return alternateView;
}
Run Code Online (Sandbox Code Playgroud)

  • 小评论:无需调用`NewGuid()`,`AttachmentBase`类(其中`LinkedResource`继承)已经根据需要创建了它. (5认同)
  • 对我来说它有效,但我必须添加ContentType:LinkedResource inline = new LinkedResource(filePath,MediaTypeNames.Image.Jpeg); (3认同)
  • 我不得不在`LinkedResource`中添加一个mime类型,使其在Hotmail/Outlook.com的Web客户端中运行.FWIW,我尝试了这个以及@Microsoft DN,这样做效果更好. (2认同)
  • 将 ContentType“image/bmp”添加到 LinkedResource 以防止将图像作为附件接收。 (2认同)

Mic*_* DN 54

试试这个

 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}"" />", att.ContentId);

 mail.IsBodyHtml = true;
 mail.Attachments.Add(att);
Run Code Online (Sandbox Code Playgroud)

  • 此代码不起作用,请使用@ T30中的以下代码,并在将备用视图添加到MailMessage时请记住,该视图将是您电子邮件的正文,并且您不需要填充Body属性. (23认同)

小智 9

    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("from@gmail.com", "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("fromEmail@gmail.com", "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);
    }
Run Code Online (Sandbox Code Playgroud)


Guy*_*ton 9

除了上述评论之外,我还有以下补充评论:

  • 不要混合附件和 AlternativeView,使用其中之一。如果混合使用它们,内嵌附件将呈现为未知下载。
  • 虽然Outlook和谷歌允许标准的HTML风格"cid:att-001"但这不是在iPhone(后期2016补丁级别)工作,而用纯字母数字"cid:att-001" -> "cid:att001"

顺便说一句:Outlook(甚至 Office 2015)呈现(对于企业用户仍然是绝大多数)需要使用 TABLE TR TD 样式的 HTML,因为它不完全支持 HTML 框模型。

  • 2020 年情况仍然如此,只需将所有 LinkedResource/AlternativeView 代码替换为附件代码,因为我还需要文件附件,而这篇文章似乎是整个互联网上唯一提到这行不通的内容 (3认同)

Osk*_*erg 7

一个更简约的例子:

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("youremail@host.com"),
    To = { "recipient@host.com" },
    Subject = "yourSubject",
    AlternateViews = { alternateView }
};

var smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
Run Code Online (Sandbox Code Playgroud)


小智 5

尝试这个。


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("from@gmail.com", "tomailaccount", Themessage, "Scoutfoto", "Test HTML Email", "smtp.gmail.com", 25);
        }
Run Code Online (Sandbox Code Playgroud)
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("fromEmail@gmail.com", "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);
        }
Run Code Online (Sandbox Code Playgroud)


小智 5

有关如何将多个图像嵌入到 HTML 电子邮件中的示例。请注意,如果您尝试使用较新的 HTML 元素(例如 flexbox),您将会遇到麻烦。如果你使用一个简单的表格就可以了。当我尝试使用 Flexbox 时,样式无法识别。

public static void Main(string[] args)
    {
    var html = File.ReadAllText("c:\test.html");
    var altView = GetAlternateView(html);
    SendEmail(new List<MailRecipients> {new MailAddress(someone@email.com)}, "Hello!", "Images in Email Test!", true, altView);
}


public static bool SendEmail(List<MailAddress> recipients, string body, string subject, bool html, AlternateView view, MailPriority priority = MailPriority.Normal)
{
   try
   {
       MailMessage message = new MailMessage();
       SmtpClient smtp = new SmtpClient();
       message.From = new MailAddress(ConfigLookup.GetStringValue(ConfigNames.EmailFrom));
       recipients.ForEach(r => message.To.Add(new MailAddress(r.Address)));
       message.Subject = subject;
       message.IsBodyHtml = html;
       message.AlternateViews.Add(view);
       message.Priority = priority;
       smtp.Port = 25;
       smtp.Host = youremailhost;
       smtp.EnableSsl = yes;
       smtp.UseDefaultCredentials = false;
       smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
       smtp.Send(message);
       return true;
   }
   catch (Exception e)
   {
       return false;
   }
}    
           
private AlternateView GetAlternateView(string html)
{
    var logoPath = ConfigLookup.GetStringValue(ConfigNames.LogoPath);
    LinkedResource logoResource = new LinkedResource(logoPath);
    
    // ContentID must match the 'cid:contentId' in the html
    logoResource.ContentId = "logo";
    
    // Without a Mime type the images will show up as attached .bin files
    logoResource.ContentType = new ContentType("image/png");
    logoResource.TransferEncoding = TransferEncoding.Base64;

    var heroPath = ConfigLookup.GetStringValue(ConfigNames.HeroPath);
    LinkedResource heroResource = new LinkedResource(heroPath);
    
    // ContentID must match the 'cid:contentId' in the html
    heroResource.ContentId = "hero";
    
    // Without a Mime type the images will show up as attached .bin files
    heroResource.ContentType = new ContentType("image/png");
    heroResource.TransferEncoding = TransferEncoding.Base64;
                        
    AlternateView alternateView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
    alternateView.LinkedResources.Add(logoResource);
    alternateView.LinkedResources.Add(heroResource);
    return alternateView;
}
           
Run Code Online (Sandbox Code Playgroud)

在 Html 中,将图像链接到 LinkedResource 的主要内容是“cid:contentId”必须匹配:

<a href="https://somesite.com" target="_blank" style="color:#033254;">
    <img src="cid:logo" width="218" alt="Company logo" style="max-width:100%;height:auto;" />
</a>
<a href="https://somesite.com" target="_blank" style="color:#033254;">
    <img src="cid:hero" width="218" alt="Company hero" style="max-width:100%;height:auto;" />
</a>
Run Code Online (Sandbox Code Playgroud)

完整的 HTML:

<!DOCTYPE html>
<html lang="en" xmlns="https://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <meta name="x-apple-disable-message-reformatting">
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <title>Shipping Confirmation from Products Company</title>
    </head>
    <body style="margin:0;padding:0;word-spacing:normal;">
        <div role="article" aria-roledescription="email" lang="en" style="-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;background-color:#ffffff;">
            <table width="100%" align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" >
                <tr>
                    <td align="center">
                        <div class="outer" style="width:96%;max-width:660px;margin:20px auto;background-color:#ffffff;">
                            <table role="presentation" width="100%" border="0" cellpadding="0" cellspacing="0">
                                <tr style="background-color:rgb(35, 68, 107);">
                                    <td align="center" style="padding:20px 0;">
                                        <a href="https://yahoo.com" target="_blank" style="color:#033254;">
                                        <img src="cid:logo" width="218" alt="Products Company logo" style="max-width:100%;height:auto;" />
                                        </a>
                                    </td>
                                </tr>
                                <tr style="background-color:#ffffff;;">
                                    <td align="center" style="padding:20px 0;">
                                        <a href="https://yahoo.com" target="_blank" style="color:#033254;">
                                        <img src="cid:hero" width="400" alt="Products Company hero" style="max-width:100%;height:auto;" />
                                        </a>
                                    </td>
                                </tr>
                                <tr style="background-color:rgb(35, 68, 107);">
                                    <td style="padding:32px; text-align:center;">
                                        <h1 style="margin-top:0;margin-bottom:16px;font-family:Arial,sans-serif;font-size:24px;line-height:30px;letter-spacing:1px;font-weight:bold;color:#ffffff;">
                                            Shipping Confirmation
                                        </h1>
                                        <hr style="border:0;background-color:rgb(35, 68, 107);border-bottom:.5px solid #ffffff;width:66%;"/>
                                        <h3 style="margin:16px 0;font-family:Arial,sans-serif;font-size:18px;line-height:24px;letter-spacing:1px;font-weight:bold;color:#ffffff;">Order# {0}</h3>
                                        <h3 style="margin:16px 0;font-family:Arial,sans-serif;font-size:18px;line-height:24px;letter-spacing:1px;font-weight:bold;color:#ffffff;">{1}</h3>
                                        <p style="margin:24px 0 8px;font-family:Arial,sans-serif;font-size:16px;line-height:22px;letter-spacing:.5px;color:#ffffff;">Thank you for your order!</p>
                                        <p style="margin:8px 0 8px;font-family:Arial,sans-serif;font-size:16px;line-height:22px;letter-spacing:.5px;color:#ffffff;">Good news! It's on its way.</p>
                                        <p style="margin:8px 0 8px;font-family:Arial,sans-serif;font-size:16px;line-height:22px;letter-spacing:.5px;color:#ffffff;">You can find the shipping details below.</p>
                                        <h3 style="margin:16px 0;font-family:Arial,sans-serif;font-size:18px;line-height:24px;letter-spacing:1px;font-weight:bold;color:#ffffff;">
                                            <a style="color:#ffffff;" href="https://www.ups.com/mobile/track?trackingNumber={2}">
                                            [Track my package!]
                                            </a>
                                        </h3>
                                        <p style="margin:32px 0 8px;font-family:Arial,sans-serif;font-size:16px;line-height:22px;letter-spacing:.5px;font-weight:bold;color:#ffffff;">Please contact Customer Service if you have any questions.</p>
                                        <p style="margin:8px 0 8px;font-family:Arial,sans-serif;font-size:16px;line-height:22px;letter-spacing:.5px;color:#ffffff;">Customer Service:
                                            <a style="color:#ffffff;" href="tel:18003665412">1-800-888-8888</a> ext. 8888
                                        </p>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)