c# - 在 C# 中将 Base64 图像添加到邮件中
问题描述
我正在尝试将图片添加到我用 C# 发送的邮件中,我在这里找到了一些代码 - stackoverflow。(问题:在 MailMessage 中添加附件 base64 图像并在 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);
,它给出了相同的 - 在身体上。我尝试在这里创建这些元素,但这只会让我陷入更多麻烦......我什至不知道我是否使用了正确的using s (顺便说一下,我把这些放在 C# 的需求中,而不是作为我复制的代码)。谁能告诉我这段代码的含义以及我错在哪里?如果你知道,我该怎么做才能修复它?
解决方案
首先,您的 alternateView 不存在,因为您没有实例化它,为此您需要在之前添加此行:
AlternateView alternateView = new AlternateView("MyImage");
其中“MyImage”是文件的名称。关于正文错误,您需要添加刚刚创建的交替视图,因此您只需像这样放置“正文”而不是“正文”:
mail.AlternateViews.Add(alternateView);
推荐阅读
- python - 熊猫丢弃重复忽略 NaN
- python - Jupyter ModuleError pyaudio
- node.js - 我收到错误“{ 错误:无效登录:535-5.7.8 用户名和密码不被接受。” 当我尝试使用 Node JS 中的模块 nodemailer 发送邮件时
- mysql - 在 MariaDB 中添加外键
- python - Django REST Swagger 给出 400 错误
- xpath - 如何在这个 `tr` 中选择下一个 `td`?
- mysql - 在 WordPress 中列出与当前帖子具有相同标签的帖子
- html - 通过 URL 将登录信息传递给具有更改属性名称的表单
- terminal - 终端命令在 PhpStorm 中不起作用
- c# - 发出 http 请求时的 Windows 服务计时