Question

Is there any way to attach System.Drawing.Image to email with out saving it, then grabbing it from the saved path.

Right now I'm creating the image and saving it. I then send email with:

MailMessage mail = new MailMessage();
                string _body = "body"

                mail.Body = _body;
                string _attacmentPath;
                if (iP.Contains(":"))
                    _attacmentPath = (@"path1");//, System.Net.Mime.MediaTypeNames.Application.Octet));
                else
                    _attacmentPath = @"path2");
                mail.Attachments.Add(new Attachment(_attacmentPath, System.Net.Mime.MediaTypeNames.Application.Octet));
                mail.To.Add(_imageInfo.VendorEmail);
                mail.Subject = "Rouses' PO # " + _imageInfo.PONumber.Trim();
                mail.From = _imageInfo.VendorNum == 691 ? new MailAddress("email", "") : new MailAddress("email", "");
                SmtpClient server = null;
                mail.IsBodyHtml = true;
                mail.Priority = MailPriority.Normal; 
                server = new SmtpClient("server");
                try
                {

                    server.Send(mail);
                }
                catch
                {

                }

Is there anyway to directly pass the System.Drawing.Image to mail.Attachments.Add()?

Was it helpful?

Solution

You can't pass an Image directly to an attachment, but you can skip the file system by just saving the image to a MemoryStream, and then providing that MemoryStream to the attachment constructor:

var stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;

mail.Attachments.Add(new Attachment(stream, "image/jpg"));

OTHER TIPS

In theory, you can convert the Image to a MemoryStream, and then add the stream as an attachment. It would go like this:

public static Stream ToStream(this Image image, ImageFormat formaw) {
  var stream = new System.IO.MemoryStream();
  image.Save(stream, formaw);
  stream.Position = 0;
  return stream;
}

Then you can use the following

var stream = myImage.ToStream(ImageFormat.Gif);

Now that you have the stream, you can add it as an attachment:

mail.Attachments.Add(new Attachment(stream, "myImage.gif", "image/gif" ));

References:

System.Drawing.Image to stream C#

c# email object to stream to attachment

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top