在电子邮件中将动态生成的图像作为附件发送 C#
Send dynamically generated image as an attachment in email c#
我正在运行时创建图像。
稍后,这将作为附件发送。这是我的代码-
Bitmap qr = CreateCode(false);
MailMessage mail = new MailMessage();
Attachment a = new Attachment(qr); //error
最后一行显示“....无效的论点”。
不想保存到本地
有什么办法吗?
MailMessage
class上的Attachments
属性是Attachment
类型对象的集合。
您只能添加 Attachment
类型的项目。
查看 Attachment
的各种构造函数,看看哪一个最适合您的需要 - 有两个采用 Stream
参数,因此您可能需要 MemoryStream
来自您 Bitmap
并设置适当的内容类型和处置数据。
编辑:您在我写这篇文章时更改了代码示例,但您仍应查看各种 Attachment
构造函数。
将位图制作成流然后使用Attachment stream constructor:
using(var stream = new System.IO.MemoryStream())
{
Bitmap qr = CreateCode(false);
qr.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
MailMessage mail = new MailMessage();
Attachment a = new Attachment(stream,'myBitmap.bmp',MediaTypeNames.Image.Bmp);
}
构造函数参数是:
public Attachment(
Stream contentStream,
string name,
string mediaType
)
如果您想在 HTML 页面上显示二维码图像。
必须在附件中向您发送 QR 码图像,并在 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);
我正在运行时创建图像。
稍后,这将作为附件发送。这是我的代码-
Bitmap qr = CreateCode(false);
MailMessage mail = new MailMessage();
Attachment a = new Attachment(qr); //error
最后一行显示“....无效的论点”。
不想保存到本地
有什么办法吗?
MailMessage
class上的Attachments
属性是Attachment
类型对象的集合。
您只能添加 Attachment
类型的项目。
查看 Attachment
的各种构造函数,看看哪一个最适合您的需要 - 有两个采用 Stream
参数,因此您可能需要 MemoryStream
来自您 Bitmap
并设置适当的内容类型和处置数据。
编辑:您在我写这篇文章时更改了代码示例,但您仍应查看各种 Attachment
构造函数。
将位图制作成流然后使用Attachment stream constructor:
using(var stream = new System.IO.MemoryStream())
{
Bitmap qr = CreateCode(false);
qr.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
MailMessage mail = new MailMessage();
Attachment a = new Attachment(stream,'myBitmap.bmp',MediaTypeNames.Image.Bmp);
}
构造函数参数是:
public Attachment(
Stream contentStream,
string name,
string mediaType
)
如果您想在 HTML 页面上显示二维码图像。 必须在附件中向您发送 QR 码图像,并在 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);