【发布时间】:2021-08-16 05:14:41
【问题描述】:
我正在尝试将图片添加到我用 C# 发送的邮件中,我在这里找到了一些代码 - stackoverflow。 (问题:Add Attachment base64 image in MailMessage and read it in html body)。 但是这段代码在 C# 中给了我语法错误我不知道如何正确解决......这是我的代码:
using System.Net.Mail;
using System.Net.Mime;
public static string FixBase64ForImage(string Image)
{
System.Text.StringBuilder sbText = new System.Text.StringBuilder(Image, Image.Length);
sbText.Replace("\r\n", string.Empty); sbText.Replace(" ", string.Empty);
return sbText.ToString();
}
public static bool SendEmail2(string mailToGet, string subject, string message, string image)
{
try
{
Byte[] bitmapData = Convert.FromBase64String(FixBase64ForImage(image));
System.IO.MemoryStream streamBitmap = new System.IO.MemoryStream(bitmapData);
MailMessage mail = new MailMessage();
var imageToInline = new LinkedResource(streamBitmap, MediaTypeNames.Image.Jpeg);
imageToInline.ContentId = "MyImage";
alternateView.LinkedResources.Add(imageToInline);//here there is an error
mail.AlternateViews.Add(body);//here there is an error
//from now on - my code:
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.IsBodyHtml = true;
message+= "<img alt ='' src ='cid: MyImage'/>";
mail.Body = message;
mail.Subject = subject;
mail.To.Add(mailToGet);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myEmailAdress", "myPassword");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
return true;
}catch(Exception e)
{
throw e;
}
}
我有两个错误:一个在alternateView.LinkedResources.Add(imageToInline); 线上,它说:名称'alternateView' 在当前上下文中不存在,另一个在mail.AlternateViews.Add(body); 线上,它给出同样 - 在body上。
我尝试在这里创建这些元素,但这只会给我带来更多麻烦......我什至不知道我是否使用了正确的 usings(顺便说一下,我根据需求放置了这些C# 的一部分,而不是我复制的代码的一部分)。谁能告诉我这段代码的含义以及我错在哪里?如果你知道,我该怎么做才能修复它?
【问题讨论】:
-
为什么不用那个主题的第二个答案,很详细
标签: c#