未找到图像路径

时间:2014-08-05 10:09:13

标签: c# image email email-attachments

如何将图像添加到C#

中从Web服务器发送的电子邮件中

这是我正在使用的代码:

        string emailType = "NewMember";
        string sMessage = GetData.emailText(emailType);
        string sEmail = GetData.userEmails(userName);
        string sSubject = GetData.emailSubject(emailType);
        SmtpClient smtpClient = new SmtpClient();
        string htmlBody = "<html><body>Dear " + userName + sMessage + "<br/><br/><img src=\"cid:filename\"></body></html>";
        AlternateView avHtml = AlternateView.CreateAlternateViewFromString
           (htmlBody, null, MediaTypeNames.Text.Html);

        LinkedResource inline = new LinkedResource("~/Resources/images/logo.jpg", MediaTypeNames.Image.Jpeg);
        inline.ContentId = Guid.NewGuid().ToString();
        avHtml.LinkedResources.Add(inline);

        MailMessage mail = new MailMessage();
        mail.AlternateViews.Add(avHtml);

        Attachment att = new Attachment("~/Resources/images/logo.jpg");
        att.ContentDisposition.Inline = true;
        MailAddress sFrom = new MailAddress("info@website.com");
        MailAddress sTo = new MailAddress(sEmail);
        mail.From = sFrom;
        mail.To.Add(sTo);
        mail.Subject = sSubject;
        mail.Body = String.Format(
                   htmlBody +
                   @"<img src=""cid:{0}"" />", inline.ContentId);

        mail.IsBodyHtml = true;
        mail.Attachments.Add(att);
        smtpClient.Send(mail);

` 这是我得到的错误消息: 找不到路径'C:\ Windows \ SysWOW64 \ inetsrv \〜\ Resources \ images \ logo.jpg

的一部分

1 个答案:

答案 0 :(得分:1)

尝试 -

Attachment att = new Attachment(Server.MapPath("~/Resources/images/logo.jpg"));
LinkedResource inline = new LinkedResource(Server.MapPath("~/Resources/images/logo.jpg"), MediaTypeNames.Image.Jpeg);

而不是 -

Attachment att = new Attachment("~/Resources/images/logo.jpg");
LinkedResource inline = new LinkedResource("~/Resources/images/logo.jpg", MediaTypeNames.Image.Jpeg);

因为您需要网站文件夹内的资源路径。因此,您必须使用Server.MapPath映射路径。更多细节 -

Server.MapPath Method