Categories
C# / .NET Program Tutorial

C# (ASP.NET) Program for Sending a Email with Attachment (with explanation)

Read my  previous post “sending email in C#” to understand the basic of STMP. Now, we are going to send a email with attachment. The attachment may be any format.

Snippet for creating Attachment object is

Attachment attach = new Attachment(string filepath);

Access this attachment in MailMessage Object

mailMsg.Attachments.Add(attach);

Full Program:

using System;
using System.Net;
using System.Net.Mail;

namespace MailProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            string name, email, sub, msg;

            //inputs
            name = "aravind";
            email = "test@gmail.com";
            sub = "this is subject  ";
            msg = "this is body ";

            //creating object for StmpClient
            SmtpClient mailSender = new SmtpClient("smtp.google.com", 587);
            mailSender.Credentials = new NetworkCredential("username@gmail.com", "password");
            mailSender.EnableSsl = true;

            //Attached file.
            Attachment attach = new Attachment(@"C:\Users\Varun\Desktop\vhrc.txt");

            //creating object for MailMessage
            MailMessage mailMsg = new MailMessage("cs@webepix.com", email, sub, msg);
            mailMsg.Attachments.Add(attach);
            mailMsg.Priority = MailPriority.High;
            mailMsg.IsBodyHtml = true;
            mailMsg.SubjectEncoding = System.Text.Encoding.UTF8;

            //Sending Mail
            try
            {
                mailSender.Send(mailMsg);
                Console.WriteLine("Successfully Submitted!");
                Console.ReadKey();
            }

            //catching the exception
            catch (Exception err)
            {
                Console.WriteLine(err.Message.ToString());
                Console.ReadKey();
            }

        }
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *