Sending e-mails with attachment in C#

In previous post we saw how to send e-mails using C# in few simple steps. Here we will see how to add attachments to our messages.

Know it:

System.Net.Mail.Attachment : Used to attach any file to our MailMessage.

GUI form:

Sending mails with attachments in C#.

Implement it:

using System;
using System.ComponentModel;
using System.Net.Mail;
using System.Windows.Forms;

namespace MailMe
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            mailProviderList.SelectedIndex = 0;
        }

        private void sendButton_Click(object sender, EventArgs e)
        {
            //Fetch all message details from the form.
            string To = this.toTextbox.Text;
            string BCC = this.bccTextbox.Text;
            string CC = this.ccTextbox.Text;
            string Subject = this.subjectTextbox.Text;
            string Body = this.bodyTextbox.Text;

            //Fetch all attachment file paths from Attachment list.
            string[] Attachments = new string[this.attachmentListbox.Items.Count];
            this.attachmentListbox.Items.CopyTo(Attachments, 0);

            //Fetch the smtp server details
            string SelectedMailProvider = (string)this.mailProviderList.SelectedItem;
            string SmtpHost = "";
            int PORT = 587;
            switch (SelectedMailProvider)
            {
                case "Gmail": SmtpHost = SmtpServer.Gmail;
                    PORT = (int)SmtpServer.PORT.Gmail;
                    break;
                case "Hotmail": SmtpHost = SmtpServer.Hotmail;
                    PORT = (int)SmtpServer.PORT.Hotmail;
                    break;
                case "Outlook": SmtpHost = SmtpServer.Outlook;
                    PORT = (int)SmtpServer.PORT.Outlook;
                    break;
                case "Office365": SmtpHost = SmtpServer.Office365;
                    PORT = (int)SmtpServer.PORT.Office365;
                    break;
                case "Yahoo Mail": SmtpHost = SmtpServer.YahooMail;
                    PORT = (int)SmtpServer.PORT.YahooMail;
                    break;
                case "Yahoo Mail Plus": SmtpHost = SmtpServer.YahooMailPlus;
                    PORT = (int)SmtpServer.PORT.YahooMailPlus;
                    break;
                case "Verizon": SmtpHost = SmtpServer.Verizon;
                    PORT = (int)SmtpServer.PORT.Verizon;
                    break;
            }

            //Fetch Authentication details
            string UserID = this.userIdTextbox.Text;
            string Password = this.passwordTextbox.Text;

            try
            {
                //Initializes a new SmtpClient.
                SmtpClient client = new SmtpClient(SmtpHost, PORT);
                client.EnableSsl = true;
                client.Credentials = new System.Net.NetworkCredential(UserID, Password);

                //client_SendCompleted method will be called after the email has been sent successfully.
                client.SendCompleted += client_SendCompleted;

                //Initializes new MailMessage.
                MailMessage msg = new MailMessage(UserID, To);

                //Add BCC list of the message.
                if (!string.IsNullOrEmpty(BCC))
                {
                    string[] BccList = BCC.Split(',');
                    foreach (string bcc in BccList)
                    {
                        msg.Bcc.Add(bcc);
                    }
                }

                //Add cc list of the message.
                if (!string.IsNullOrEmpty(CC))
                {
                    string[] ccList = CC.Split(',');
                    foreach (string cc in ccList)
                    {
                        msg.CC.Add(cc);
                    }
                }

                //Add subject of the message.
                msg.Subject = Subject;

                //Add Body of the message.
                msg.Body = Body;

                //Add attachments to the message.
                foreach (string filePaths in Attachments)
                {
                    msg.Attachments.Add(new Attachment(filePaths));
                }

                //Sends the message in backgound.
                client.SendAsync(msg, null);

                MessageBox.Show("Please wait while sending...");
            }
            catch (Exception er)
            {
                MessageBox.Show("Unable to send mail.\nError:" + er.Message, "Error");
            }
        }

        void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Unable to send email.\nError:" + e.Error.Message, "Error");
            }
            else
            {
                MessageBox.Show("Mail sent successfully.");
            }
        }

        private void closeButton_Click(object sender, EventArgs e)
        {
            //Closes the form.
            Environment.Exit(0);
        }

        private void addAttachmentButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog FileChooser = new OpenFileDialog();
            FileChooser.Multiselect = true;
            FileChooser.Title = "Insert Attachments";
            DialogResult res = FileChooser.ShowDialog();

            if (res != System.Windows.Forms.DialogResult.Cancel)
            {
                foreach (string filePath in FileChooser.FileNames)
                {
                    this.attachmentListbox.Items.Add(filePath);
                }
            }
        }

        private void removeMenu_Click(object sender, EventArgs e)
        {
            //Gets the selected index from attachment listbox and remove the element from the list.
            int SelectedIndex = this.attachmentListbox.SelectedIndex;

            if (SelectedIndex >= 0)
                this.attachmentListbox.Items.RemoveAt(SelectedIndex);
        }

        private void removeAllMenu_Click(object sender, EventArgs e)
        {
            //Clears all elements present in Attachment listbox
            this.attachmentListbox.Items.Clear();
        }
    }

    /// 
    /// A list of popular smtp server with their port.
    /// 
    public class SmtpServer
    {
        public const string Gmail = "smtp.gmail.com";
        public const string Hotmail = "smtp.live.com";
        public const string Outlook = "smtp.live.com";
        public const string Office365 = "smtp.office365.com";
        public const string Verizon = "outgoing.yahoo.verizon.net";
        public const string YahooMail = "smtp.mail.yahoo.com";
        public const string YahooMailPlus = "plus.smtp.mail.yahoo.com";

        //Smtp servers PORT.
        public enum PORT
        {
            Gmail = 587,
            Outlook = 587,
            Office365 = 587,
            Hotmail = 465,
            YahooMail = 465,
            YahooMailPlus = 465,
            Verizon = 587
        }
    }
}

Output:

Sending e mails with attachment in C#.

Download Exe
Download Full C# Project

Happy coding ;)

Labels: , , , ,