Search code examples
c#winformsemailemail-attachments

Send dynamically generated image as an attachment in email c#


I'm creating an image in runtime.

Later on, this will be sent as an attachment. Here is my code-

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

Last line shows ".... invalid arguements".

I don't want to save it locally.

Is there any way to do it?


Solution

  • Make the bitmap into a stream and then use the 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);
    }
    

    the constructor params are:

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