C# 在电子邮件c中将动态生成的图像作为附件发送#
我正在运行时创建一个映像 稍后,这将作为附件发送。这是我的密码-C# 在电子邮件c中将动态生成的图像作为附件发送#,c#,winforms,email,email-attachments,C#,Winforms,Email,Email Attachments,我正在运行时创建一个映像 稍后,这将作为附件发送。这是我的密码- Bitmap qr = CreateCode(false); MailMessage mail = new MailMessage(); Attachment a = new Attachment(qr); //error 最后一行显示“…无效参数” 我不想在本地保存它 有什么办法吗?类上的MailMessage属性是Attachment类型对象的集合。 您只能添加附件类型的项目 查看附件的各种构造函数,看看哪一个最适合您的需要
Bitmap qr = CreateCode(false);
MailMessage mail = new MailMessage();
Attachment a = new Attachment(qr); //error
最后一行显示“…无效参数”
我不想在本地保存它
有什么办法吗?类上的
MailMessage
属性是Attachment
类型对象的集合。
您只能添加附件类型的项目
查看附件
的各种构造函数,看看哪一个最适合您的需要-有两个构造函数使用流
参数,因此您可能需要从位图
获取内存流
,并设置适当的内容类型和处置数据
编辑:在我编写本文时,您更改了代码示例,但您仍应查看各种附件构造函数。将位图制作成流,然后使用:
构造函数参数为:
public Attachment(
Stream contentStream,
string name,
string mediaType
)
如果您想在HTML页面上显示二维码图像。
您必须在附件中发送二维码图像,并在HTML正文中使用下面的代码
byte[] image = //an image
List<Attachment> attachments = new List<Attachment>();
Stream stream = new MemoryStream(image);
var qrAttachment = new Attachment(stream, "QrImage.png");
attachments.Add(qrAttachment);
//bottom code is so important
string body = $"<img src=\"cid:{qrAttachment.ContentId}\" />";
MailMessage mailMessage = new MailMessage
{
To = { "test@test.com"},
Body = body,
};
foreach (var attachment in attachments)
{
mailMessage.Attachments.Add(attachment);
}
smtpClient.Send(mailMessage);
byte[]image=//图像
列表附件=新列表();
流=新内存流(图像);
var qrAttachment=新附件(流,“QrImage.png”);
附件。添加(附件);
//底层代码非常重要
字符串体=$“”;
MailMessage=newmailmessage
{
To={”test@test.com"},
身体,
};
foreach(附件中的var附件)
{
mailMessage.Attachments.Add(附件);
}
smtpClient.Send(mailMessage);
我相信这会接受一个流,你可以在Attachments的构造函数中使用它。没有一个附件构造函数只接受流,应该是流和字符串。是的,我修正了这一点,请记住资源处置也很重要,不这样做可能会导致内存泄漏,在流上添加了using语句,并将代码放在块中
byte[] image = //an image
List<Attachment> attachments = new List<Attachment>();
Stream stream = new MemoryStream(image);
var qrAttachment = new Attachment(stream, "QrImage.png");
attachments.Add(qrAttachment);
//bottom code is so important
string body = $"<img src=\"cid:{qrAttachment.ContentId}\" />";
MailMessage mailMessage = new MailMessage
{
To = { "test@test.com"},
Body = body,
};
foreach (var attachment in attachments)
{
mailMessage.Attachments.Add(attachment);
}
smtpClient.Send(mailMessage);