在C#中将图像附加到邮件正文中

如何在正文内容中附加图像。 我写了下面的代码

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); string UserName = "xyz@someorg.com"; string Password = "my password"; message.To.Add(new System.Net.Mail.MailAddress("toaddress@toadddress.com")); message.From = new System.Net.Mail.MailAddress("fromaddress@fromaddress.com"); message.Subject = "test subject"; message.Body = ""; message.IsBodyHtml = true; System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); smtpClient.Host = "hostname"; smtpClient.Port = 25; smtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password); smtpClient.Send(message); 

代码很好,因为我也收到了消息,但图像在身体内部[X]而不是图像。 怎么解决这个? 路径是正确的?

  string attachmentPath = Environment.CurrentDirectory + @"\test.png"; Attachment inline = new Attachment(attachmentPath); inline.ContentDisposition.Inline = true; inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline; inline.ContentId = contentID; inline.ContentType.MediaType = "image/png"; inline.ContentType.Name = Path.GetFileName(attachmentPath); message.Attachments.Add(inline); 

参考: 使用内联附件在C#中发送电子邮件

使用所谓的LinkedResource 。 在这里你可以找到操作方法。 做得那么成功。

如果教程没有帮助,请不要害羞并要求澄清。 🙂

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net; using System.IO; using System.Net.Mime; using System.Net.Mail; namespace ItsTrulyFree { public partial class demo_mail : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { enter code here } protected void btnSubmit_Click(object sender, EventArgs e) { MailMessage Msg = new MailMessage(); // Sender e-mail address. Msg.From = new MailAddress(txtUsername.Text); // Recipient e-mail address. Msg.To.Add(txtTo.Text); Msg.Subject = txtSubject.Text; // File Upload path String FileName = fileUpload1.PostedFile.FileName; string mailbody = txtBody.Text + "
"; //LinkedResource LinkedImage = new LinkedResource(FileName); //HttpContext.Current.Server.MapPath("/UploadedFiles"); LinkedResource LinkedImage = new LinkedResource(Server.MapPath("~//" + FileName), "image/jpg"); LinkedImage.ContentId = "MyPic"; //Added the patch for Thunderbird as suggested by Jorge LinkedImage.ContentType = new ContentType(MediaTypeNames.Image.Jpeg); AlternateView htmlView = AlternateView.CreateAlternateViewFromString(mailbody+ " ", null, "text/html"); htmlView.LinkedResources.Add(LinkedImage); Msg.AlternateViews.Add(htmlView); SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.Credentials = new System.Net.NetworkCredential(txtUsername.Text, txtpwd.Text); smtp.EnableSsl = true; smtp.Send(Msg); Msg = null; Page.RegisterStartupScript("UserMsg", ""); } //catch (Exception ex) //{ // Console.WriteLine("{0} Exception caught.", ex); //} } }