C#将图像添加到电子邮件正文

时间:2014-08-05 12:44:31

标签: c# image html-email

此代码会发送一封附有“Logo.JPG”附件的电子邮件,但不会将其附加到电子邮件正文中。我只是得到了图像占位符。 如何将图像添加到消息文本中?

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("info@inveshub.com");
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);

1 个答案:

答案 0 :(得分:2)

Html正文为

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