将动态生成的图像作为附件发送到电子邮件c#

时间:2015-04-27 14:23:21

标签: c# winforms email email-attachments

我在运行时创建图像。

稍后,这将作为附件发送。这是我的代码 -

Bitmap qr = CreateCode(false);
MailMessage mail = new MailMessage();
Attachment a = new Attachment(qr); //error

最后一行显示" ....无效的争论"。

我不想在本地保存。

有什么办法吗?

3 个答案:

答案 0 :(得分:2)

将位图制作成流,然后使用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);
}

构造函数params是:

public Attachment(
    Stream contentStream,
    string name,
    string mediaType
)

答案 1 :(得分:0)

Attachments类的MailMessage属性是Attachment类型对象的集合。 您只能添加Attachment类型的项目。

看一下Attachment的各种构造函数,看看哪一个最适合您的需求 - 有两个需要Stream参数,所以您可能需要MemoryStream来自您Bitmap并设置适当的内容类型和处置数据。

编辑:您在编写此代码时更改了代码示例,但您仍应查看各种Attachment构造函数。

答案 2 :(得分:0)

如果您想在 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);