我需要在c#中附加邮件中的html附件

时间:2018-01-09 13:35:08

标签: c# excel stored-procedures email-attachments

我在Excel中有一个电子邮件ID列表,每个电子邮件ID都有一个要附加的图像,其url将写入excel的下一行。请帮我附上每张图片及其相应的图片。我写了发送邮件的程序。这会在路径必须附加文件的位置显示错误非法字符。 提前谢谢。

请帮助我。

{

        DataTable dtValues = SQLHelper.ExecuteDataset("Stored Procedure").Tables[2];
        if (dtValues.Rows.Count > 0)
            System.Console.Clear();
        foreach (DataRow row in dtValues.Rows)
        {
            string mailname = Convert.ToString(row["row1"]);
            string mailemail = Convert.ToString(row["row2"]);
            string Code = Convert.ToString(row["row3"]);
            string Code_new = Code.Replace("\t", "");
            string Id = Convert.ToString(row["row4"]);
            string str = AppDomain.CurrentDomain.BaseDirectory;
            string image = str + "Codes\\" + Code_new + ".jpg";
            //string path = Microsoft.SqlServer.Server.MapPath("/HTMLPage.html");
            //string strPath = HttpContext.Current.Server.MapPath("~/HTML");

            //string body = string.Empty;
            StreamReader reader = new StreamReader("HTMLPage1.html");
            string readfile = reader.ReadToEnd();
            string body = "";
            body = readfile;
            body = body.Replace("{USERNAME}", mailname);
            body = body.Replace("{EMAILID}", mailemail);
            body = body.Replace("{CODE}", QRCode);
            body = body.Replace("{IMAGE}", image);

            MailMessage Msg = new MailMessage();
            Msg.From = new MailAddress("xxx@gmail.com"); // Sender e-mail address.
            Msg.To.Add(mailemail);
            Console.WriteLine(Id + " : " + mailemail);

            Msg.Subject = "QR Code";
            Msg.Body = "Hi";
            Attachment attachFile = new Attachment(body);
            Msg.Attachments.Add(attachFile);
            Msg.IsBodyHtml = true;
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
            SmtpServer.Port = 587;
            SmtpServer.EnableSsl = true;
            SmtpServer.UseDefaultCredentials = false;
            SmtpServer.Credentials = new System.Net.NetworkCredential("xxx2694@gmail.com", "984621232312");
            SmtpServer.Send(Msg);

        }
 }

1 个答案:

答案 0 :(得分:3)

应添加附件:

// Create file attachment
Attachment ImageAttachment = new Attachment(Server.MapPath(Convert.ToString(row["FilePath"])));

// Set the ContentId of the attachment, used in body HTML
ImageAttachment.ContentId = Convert.ToString(row["FileName"]);

// Add an image as file attachment
Msg.Attachments.Add(ImageAttachment);