【问题标题】:Add a Base64 image to a mail in C#在 C# 中将 Base64 图像添加到邮件中
【发布时间】: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#


【解决方案1】:

首先,您的 alternateView 不存在,因为您没有实例化它,为此您需要在之前添加此行:

AlternateView alternateView = new AlternateView("MyImage");

“MyImage” 是文件的名称。关于 body 错误,您需要添加刚刚创建的交替视图,因此您只需像这样放置 alternateView 而不是“body”: p>

mail.AlternateViews.Add(alternateView);

【讨论】:

  • new AlternativeView("MyImage") 不起作用,因为图像不是保存在某处的文件 - 它是一个代表它的字符串,它来自 SQL,因此没有保存在任何地方。您对这种情况有什么建议吗?
猜你喜欢
  • 2019-02-25
  • 1970-01-01
  • 2014-09-28
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多