steven85791
steven85791

Reputation: 129

Problem Sending an Email with inline Image

I'm trying to send an inline image in my email and it displays fine but instead of just displaying the image I also receive the same image as an attachment. How do I get it to just have the email inline and not have a separate attachment.

Here is my code:

 public async static Task SendMail(string emailAccount, string sendTo, string message, string subject, string imgpath)
        {
            try
            {
                string internalEmail = emailAccount;
                string emailPassword = ConfigurationManager.AppSettings["EmailPassword"];
                string displayName = "Church Musician Team";
                MailMessage myMessage = new MailMessage();
                myMessage.To.Add(sendTo);
                myMessage.From = new MailAddress(internalEmail, displayName);
                myMessage.Subject = subject;
                string attachmentPath = imgpath;
                Attachment inline = new Attachment(attachmentPath);
                inline.ContentDisposition.Inline = true;
                inline.ContentId = "id1";
                inline.ContentType.MediaType = "image/png";
                myMessage.Attachments.Add(inline);
                myMessage.Body = message;
                myMessage.IsBodyHtml = true;
               



                using (SmtpClient smtp = new SmtpClient())
                {
                    smtp.EnableSsl = false;
                    smtp.Host = ConfigurationManager.AppSettings["EmailHost"];
                    smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["EmailPort"]);
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials = new NetworkCredential(internalEmail, emailPassword);
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtp.SendCompleted += (s, e) => { smtp.Dispose(); };
                    await smtp.SendMailAsync(myMessage);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            
        }

Upvotes: 0

Views: 313

Answers (1)

tdinpsp
tdinpsp

Reputation: 202

You can embed the bitmap data right into the body using:

public static string BmpToUrl(Bitmap source)
{
    return $"data:image/png;base64,{Convert.ToBase64String((byte[]) (new ImageConverter()).ConvertTo(source, typeof(byte[])))}";
}

Then wherever you want to actually place it in the body use:

...
body += $"<img src='{BmpToUrl(myBitmap)} />"
...

This way you don't need to have a separate attachment.

Admittedly I've never actually done this in an email but I believe that it should work.

Upvotes: 2

Related Questions