user3746002
user3746002

Reputation: 27

C# add image to email body

This code sends an email with the attachment "Logo.JPG" but does not attach it to the body of the email. I just get the image place holder. How can i add the image to the text of the message?

string emailType = "NewMember";
string sMessage = GetData.emailText(emailType);
string sEmail = GetData.userEmails(userName);
string sSubject = GetData.emailSubject(emailType);
string sImage = System.Web.HttpContext.Current.Server.MapPath("~/images/logo.jpg");
SmtpClient smtpClient = new SmtpClient();
string htmlBody = "<html><body>Dear " + userName + sMessage + "<br/><br/><img src=" + sImage + "></body></html></body></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
   (htmlBody, null, MediaTypeNames.Text.Html);
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(avHtml);
FileStream fileToStream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/images/logo.jpg"), FileMode.Open, FileAccess.Read);
Attachment att = new Attachment(fileToStream, "Logo.jpg", MediaTypeNames.Image.Jpeg);

att.ContentDisposition.Inline = true;
MailAddress sFrom = new MailAddress("[email protected]");
MailAddress sTo = new MailAddress(sEmail);
mail.From = sFrom;
mail.To.Add(sTo);
mail.Subject = sSubject;
mail.Attachments.Add(att);
mail.Body = String.Format(
           htmlBody);
mail.IsBodyHtml = true;
//  mail.Attachments.Add(att);
smtpClient.Send(mail);

Upvotes: 2

Views: 13920

Answers (1)

Hiral Nayak
Hiral Nayak

Reputation: 1082

Html body as

 string htmlBody = "<html><body>Dear " + userName + sMessage + "<br/><br/><img src=cid:sImage /></body></html></body></html>"

Upvotes: 2

Related Questions