Search code examples
c#excelstored-proceduresemail-attachments

I need to attach html attachments in mail in c#


I have a list of email id in a excel and each email id have a image to be attched whose url will be written in the next row of the excel. Please help me to attach each image with its corresponding image. I have written program to send mail. This shows error Illegal characters in path at the point where it has to attach file. Thanks in advance.

Please help me with this.

{

        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);

        }
 }

Solution

  • It should add an attachment:

    // 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);