发送正文带有图像的电子邮件



我想发送一封在正文顶部带有徽标的电子邮件。这是我的方法:

public bool SendEmail(string toAddress)
{
SmtpClient smtpServer = new SmtpClient("the server");
try
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<image src=cid:logo  style="height: 50px;"><br>Hello World", null, MediaTypeNames.Text.Html);

LinkedResource imageResource = new LinkedResource(Server.MapPath(@"....imageslogo.png"));
imageResource.ContentId = "logo";
htmlView.LinkedResources.Add(imageResource);
smtpServer.Port = port;
smtpServer.Credentials = new NetworkCredential("user", "pass");
smtpServer.EnableSsl = false;
MailMessage message = new MailMessage();
message.To.Add(toAddress);
message.From = new MailAddress("the address");
message.Subject = "Some subject";
message.AlternateViews.Add(htmlView);
message.IsBodyHtml = true;
smtpServer.Send(message);
smtpServer.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}

方法正在发送电子邮件,但是图像是作为附件发送的。我试过这样做:

LinkedResource imageResource = new LinkedResource(Server.MapPath(@"....imageslogo.png"), MediaTypeNames.Image.Jpeg);

但是当我添加" mediatypames . image . jpeg "在这一行中,发送的电子邮件根本没有图像。

有人能帮我一下吗?提前感谢!

你可以将你的图像转换为base64并在src中添加,或者你可以直接给出图像所在的页面。

您可以尝试使用MailKit库。发送嵌入图像在这个库中工作得很好。

var stream = new MemoryStream();
image.Save(stream, ImageFormat.Png);
stream.Position = 0;
var resource = builder.LinkedResources.Add(contentId, stream);
resource.ContentId = contentId;
// in the email message, there is img with src="cid:contentId"

另一个嵌入图像的例子在这里。

您可以使用:

public bool SendEmail(string toAddress)
{
SmtpClient smtpServer = new SmtpClient("the server");
try
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<image src=cid:logo  style="height: 50px;"><br>Hello World", null, MediaTypeNames.Text.Html);
LinkedResource imageResource = new LinkedResource(Server.MapPath(@"....imageslogo.png"));
imageResource.ContentId = "logo";
htmlView.LinkedResources.Add(imageResource);
smtpServer.Port = 0; //add port here
smtpServer.Credentials = new NetworkCredential("user", "pass");
smtpServer.EnableSsl = false;
MailMessage message = new MailMessage();
message.To.Add(toAddress);
message.From = new MailAddress("the address");
message.Subject = "Some subject";
//add file here
Attachment attachment = new Attachment("c://image");
attachment.ContentDisposition.Inline = true;
message.Attachments.Add(attachment);
message.AlternateViews.Add(htmlView);
message.IsBodyHtml = true;

smtpServer.Send(message);
smtpServer.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}

最新更新