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

13

我该如何在正文内容中添加一张图片?我已经编写了以下代码:

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 = "<img src=@'C:\\Sunset.jpg'/>";                
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],而不是图片。怎么解决?路径正确吗?


谢谢,我解决了 message.Body = "<img src='C:\\Sunset.jpg'/>"; - priyanka.bangalore
6
你并没有这样做。接收者在根目录下存储该文件的概率为零。 - Hans Passant
1
@HansPassant:除非电子邮件只发送给OP!;-) - Jon Egerton
3个回答

26
    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#中使用内嵌附件发送电子邮件


哦...这种方法似乎更好。 - Arnis Lapsa
5
以后查看此解决方案的任何人,要使其工作,我必须在我的代码中添加以下图像标签(我的ContendId为“ Screenshot”):message.Body = "<img src=\"cid:Screenshot\" alt=\"\" />"; - Grungondola
cid链接在Android上的Outlook似乎无法工作,但在Windows上的Outlook和三星电子邮件中可以工作。通过使用AlternateViewLinkedResource进行修复,请参考此答案。不确定其中的区别是什么。 - Christian Gollhardt

1

使用所谓的LinkedResource这里可以找到如何操作。我已经成功完成了。

如果教程没有帮助,请不要害羞,提出澄清问题。 :)


0
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 + "<br/><img src=cid:companylogo>";

            //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+
                  " <img src=cid:MyPic>",
                  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", "<script>alert('Mail sent thank you...');if(alert){ window.location='SendMail.aspx';}</script>");
            }
            //catch (Exception ex)
            //{
            //    Console.WriteLine("{0} Exception caught.", ex);
            //}
        }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接