【问题标题】:Attaching an image to email [duplicate]将图像附加到电子邮件[重复]
【发布时间】:2014-02-07 00:18:43
【问题描述】:

我尝试从本地开发机器发送带有图像的测试电子邮件。图片未作为附件发送。 可能是一个愚蠢的问题,但是在我将其托管在 www 上之前,我有什么办法可以从我在本地机器上运行的网站发送电子邮件用于测试目的。

public static void SendMail(string emailBody, string to, string from, string subject)
{
    MailMessage mailMessage = new MailMessage("to@to.com", "from@test.com");
    mailMessage.Subject = subject;
    mailMessage.Body = emailBody;
    mailMessage.IsBodyHtml = true;
    //mailMessage.Body += "<br /><br /> <asp:Image ID='Image1' runat='server' ImageUrl='~/images/banner.jpg' />";

    string path = System.Web.HttpContext.Current.Server.MapPath(@"~/images/banner.jpg"); 
    AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><br/><img src=cid:companylogo/><br></body></html>" + emailBody, null, MediaTypeNames.Text.Html);LinkedResource logo = new LinkedResource(path);
    av1.LinkedResources.Add(logo);
    mailMessage.AlternateViews.Add(av1);

    string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(cs))
    {
        SqlCommand sc = new SqlCommand("SELECT EmailAdd FROM Volunteers where Country like 'United K%' and Race like 'Pak%' ", con);
        con.Open();
        SqlDataReader reader = sc.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                mailMessage.To.Add(reader[0].ToString());
            }
        }
        reader.Close();
    }

    SmtpClient smtpClient = new SmtpClient();
    smtpClient.Send(mailMessage);
}

【问题讨论】:

  • "is there any way i can send email from my website running on my local machine for test purposes" - 是的,绝对是。运行本地 SMTP 侦听器进行测试:smtp4dev.codeplex.com
  • 你如何区分和不混淆像cssc这样的变量?我会更有意义地命名它们。

标签: c# asp.net email


【解决方案1】:

看起来您可能没有设置正确的图像 CID。这是我在我的一个应用程序中使用的方法:

// Construct the MailMessage object to be relayed to the SMTP server
message = new MailMessage("to@to.com", "from@test.com");

string path = System.Web.HttpContext.Current.Server.MapPath(@"~/images/banner.jpg"); 
byte[] image = LoadImageAsByteArray(path);

// create a stream object from the file contents
var stream = new MemoryStream(image);

// create a mailAttachment object
var mailAttachment = new System.Net.Mail.Attachment(stream, "bannerAttachment.jpg")
                     {
                       // set the content id of the attachment so our email src links are valid
                       ContentId = Guid.NewGuid().ToString("N")
                     };

// set the attachment inline so it does not appear in the mail client as an attachment
mailAttachment.ContentDisposition.Inline = true;

// and then add the newly created mailAttachment object to the Attachments collection
message.Attachments.Add(mailAttachment);

而且...我发现“奇怪”的一件事是您对 AlternateView 的使用 - 这似乎有点多余。我建议像这样创建身体:

// Construct the body 
var body = string.Format("<html><body><br/><img src=cid:{0} /><br />{1}</body></html>", mailAttachment.ContentId, emailBody);

// Subject
message.Subject = "Whatever"

// Ensure this is set to true so images are embedded correctly
message.IsBodyHtml = true;

// finally, add the body
message.Body = body;

// Create an smtp client object to initiate a connection with the server
var client = new SmtpClient(smtpServerAddress, smtpServerPort.Value);

// tell the client that we will be sending via the network (as opposed to using a pickup directory)
client.DeliveryMethod = SmtpDeliveryMethod.Network;

// and finally send the message
client.Send(message);

);

注意:您必须处理自己的身份验证等,因为我没有包括在内。另外,这是我自己的生产代码的摘录,所以请告诉我你的进展情况。我很乐意相应地修改我的答案。

【讨论】:

  • 这个LoadImageAsByteArray函数是从哪里来的,它没有声明不能识别,有没有我需要引用的dll来使用它。
  • 对不起,我认为这是不言自明的。我使用了这里描述的方法:stackoverflow.com/questions/1131116/… 或者,您可以使用这里描述的方法:stackoverflow.com/questions/7350679/…
  • 很高兴知道这对你是否有用?
  • 我还没有尝试过,因为没有附加图像,邮件处理时间太长了。因为我正在向许多收件人发送电子邮件。在我重新访问之前,我将首先在单独的帖子中解决该问题,但会在此处更新状态
【解决方案2】:

这是您的解决方案。

 string ss = "<div style='background:#e0e1e3;width:800px; margin:20px auto;border:1px solid #d8d9db;'>";
                ss = ss + "<div style='background:#ffffff; padding:10px;'>";
                ss = ss + "<img src='http://example.com/images/myimage.jpg'  /></div>";



    MailMessage MailMsg = new MailMessage();
                MailMsg.To.Add("test@test.com");
                MailMsg.From = new MailAddress("Test.co.in");
                MailMsg.Subject = "Your subject";
                MailMsg.BodyEncoding = System.Text.Encoding.UTF8;
                MailMsg.IsBodyHtml = true;
                MailMsg.Priority = MailPriority.High;
                MailMsg.Body = ss;
    SmtpClient tempsmtp = new SmtpClient();
                tempsmtp.Host = "smtp.gmail.com";
                tempsmtp.Port = 587;
                tempsmtp.EnableSsl = true;
                tempsmtp.Credentials = new System.Net.NetworkCredential("test@test.com", "welcome");
tempsmtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            tempsmtp.Send(MailMsg);

【讨论】:

  • 您使用的图像似乎放在网络上,我的图像在我的本地解决方案文件夹中,我想将其与电子邮件一起附加。在将解决方案部署到 Web 服务器之前,我正在测试该功能。
猜你喜欢
  • 2012-02-28
  • 2010-10-06
  • 2016-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
相关资源
最近更新 更多