In previous article we have seen How to send mail Using C#, here we are using the same concept to send mail but additionally we are attaching the file to the mail. We will be pulling some data from Database, exporting into CSV file, and then the file will be sent as mail. Below is the example:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.IO;
using System.Net.Mail;
using System.Net;
using System.Data;
using System.Data.SqlClient;

namespace RECEIPT_INT_ERROR_LOG
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
             string constring = ConfigurationManager.AppSettings["connectionstring"].ToString();
             string AppLocation = "";
             AppLocation = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
             AppLocation = AppLocation.Replace("file:\\", "");
             string date = DateTime.Now.ToShortDateString();
             date = date.Replace("/", "_");
             string file = AppLocation + "\\ExcelFiles\\" + date + ".csv";
             SqlConnection conn = new SqlConnection(constring);
             conn.Open();
             SqlCommand cmd = new SqlCommand("select Name,Id,Status from logTable ", conn);
             cmd.CommandType = CommandType.Text;
             SqlDataAdapter da = new SqlDataAdapter(cmd);
             DataTable dt = new DataTable();
             da.Fill(dt);
             conn.Close();
             Program obj = new Program();
             obj.CreateCSVFile(dt, file);
             obj.mail(file);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception", e);
                Console.ReadLine();
            }

        }
        public void CreateCSVFile(DataTable dt, string strFilePath)
        {
            StreamWriter sw = new StreamWriter(strFilePath, false);
            int iColCount = dt.Columns.Count;
            int iRowcount = dt.Rows.Count;

            if (iRowcount != 0)
            {

                for (int i = 0; i < iColCount; i++)
                {
                    sw.Write(dt.Columns[i]);
                    if (i < iColCount - 1)
                    {
                        sw.Write(",");
                    }
                }
                sw.Write(sw.NewLine);
                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < iColCount; i++)
                    {
                        if (!Convert.IsDBNull(dr[i]))
                        {
                            sw.Write(dr[i].ToString());
                        }
                        if (i < iColCount - 1)
                        {
                            sw.Write(",");
                        }
                    }
                    sw.Write(sw.NewLine);
                }
            }
            else
            {
                sw.Write("Error Not Found");
            }
            sw.Close();
        }

        public void mail(string file)
        {
            try
            {
             MailMessage mail;
             SmtpClient smtp;
             string[] sendTo;
             mail = new MailMessage();
             sendTo = ConfigurationManager.AppSettings["toMailId"].Split(';');
             for (int i = 0; i < sendTo.Length; i++)
             {
                 mail.To.Add(sendTo[i]);
             }
             smtp = new SmtpClient("141.251.180.70");
             smtp.Timeout = 2147483647;
             mail.IsBodyHtml = true;
             mail.From = new MailAddress(ConfigurationManager.AppSettings["fromAddress"].ToString());
             mail.Subject = ConfigurationManager.AppSettings["mailSubject"].ToString();
             smtp.Credentials= new System.Net.NetworkCredential("fourthbottle@gmail.com", "MailPassword");
             System.Net.Mail.Attachment attachment;
             attachment = new System.Net.Mail.Attachment(file); //Attaching File to Mail 
             if (File.Exists(file))
             {
                 mail.Attachments.Add(attachment);
                 smtp.Send(mail);
             }
            }
            catch (Exception exp)
            {
                Console.WriteLine("Exception", exp);
            }
        }
    }
}