Skip to main content
 首页 » 编程设计

c#之将 Html 文档(包含图像)作为电子邮件附件发送 C#

2024年01月25日36wayfarer

我在运行时使用 C# 发送 Html 文档(包含图像)作为电子邮件附件。
但是当我查看收到的电子邮件时,发送的 html 文档不包含任何图像。

能否指导我如何确保 html 文档与图像一起发送。

        MailMessage objMailMessage = new MailMessage(); 
        objMailMessage.From = new MailAddress("aa@gmail.com"); 
 
        string[] emailIds = objReportRequest.EmailIds.Split(','); 
        foreach (string emailId in emailIds) 
        { 
            objMailMessage.To.Add(new MailAddress(emailId)); 
        } 
 
        objMailMessage.IsBodyHtml = true;  
        objMailMessage.Body = messageBody; 
        objMailMessage.Subject = "Test Service"; 
        objMailMessage.Attachments.Add(new Attachment(filePath)); 
 
        SmtpClient objSmtpClient = new SmtpClient("smtp.gmail.com"); 
        objSmtpClient.Credentials = new NetworkCredential("aaa@gmail.com", "aaa"); 
        objSmtpClient.EnableSsl = true; 
        objSmtpClient.Send(objMailMessage); 

我收到了作为电子邮件附件的 html 文档,但没有显示图像。

谢谢!

请您参考如下方法:

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(message, null, "text/html"); 
 LinkedResource image = new LinkedResource(@".\images\sample.jpg"); 
 image.ContentId = "Image"; 
 message = "<img src=cid:Image>" + message; 
 htmlView = AlternateView.CreateAlternateViewFromString(message, null, "text/html"); 
 htmlView.LinkedResources.Add(image); 

是根据 MSDN 将图像放入 HTML 电子邮件和 html 附件的方式使用相同的对象,但我没有专门执行此操作的代码。