[英]Image not showing in gmail mail body after sending it from asp.net c# net.mail as mail.body
[英]Embed image in mail body using C# and Asp.Net
我试图将图像嵌入到 Outlook 电子邮件中。 基本上,我想每天为生日祝福创建一个 Windows 服务。 服务将向所有相关员工发送生日祝福。 对于每一天,图像模板都会不同,并且每天都会有一种背景颜色。
我试图使用此链接中的代码片段,但面临两个问题:
我附上了我尝试到现在的 C# 代码:
private void SendHtmlFormattedEmail(string recepientEmail, string subject, string body)
{
string path = Server.MapPath("~/Images/TestLogo.png");
Configuration config = System.Web.Configuration.WebConfigurationManager
.OpenWebConfiguration("~/");
var settings = (System.Net.Configuration.MailSettingsSectionGroup)
config.GetSectionGroup("system.net/mailSettings");
var smtp = settings.Smtp;
System.Net.Configuration.SmtpNetworkElement network = smtp.Network;
var outlookApp = new Microsoft.Office.Interop.Outlook.Application();
var mailitem = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
mailitem.To = network.TargetName;
mailitem.Subject = subject;
Microsoft.Office.Interop.Outlook.Attachment attachment = mailitem.Attachments.Add(path, OlAttachmentType.olEmbeddeditem, null, "Test Image");
string imageCid = "TestLogo.png@123";
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", imageCid);
mailitem.BodyFormat = OlBodyFormat.olFormatRichText;
mailitem.HTMLBody = String.Format("<body bgcolor='#E6E6FA'>Dear TestMan,<img src=@cid:{0}\"></body>", imageCid);
//mailitem.Body = body;
mailitem.Display(false);
mailitem.Send();
}
将您的图像转换为base64。 可以使用https://www.base64-image.de/这样的网站/工具,也可以通过编程方式使用http://www.c-sharpcorner.com/blogs/convert-an-image-to-base64-string-and-base64 -字符串到图像
嵌入: <img src="data:image/jpeg;base64,IMAGEDATA" />
编辑数据类型以匹配您的图像类型,然后将“ IMAGEDATA”替换为转换为基本64字符串的图像字节。
作为参考,一个完整的工作示例:
public void SendMail()
{
LinkedResource logo = new LinkedResource(
"images\\image005.png", //Path of file
"image/png"); //Mime type: Important!
logo.ContentId = "logo"; //ID for reference
//Actual HTML content of the body in an 'AlternateView' object.
AlternateView vw = AlternateView.CreateAlternateViewFromString(
"Hello, this is <b>HTML</b> mail with embedded image: <img src=\"cid:logo\" />",
null,
MediaTypeNames.Text.Html); //Mime type: again important!
vw.LinkedResources.Add(logo);
var msg = new MailMessage() { IsBodyHtml = true };
msg.AlternateViews.Add(vw);
msg.From = new MailAddress("sender@domain.com");
msg.To.Add(new MailAddress("reciever@domain.com"));
msg.Subject = "HTML Mail!";
using (var client = new SmtpClient("localhost", 25))
client.Send(msg);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.