Sending E-mails with attachments using .NET

Email notification is a common part of most applications. The System.Web.Mail namespace can be used to send HTML mails and even add attachments to it.

We will create a console-based application to demonstrate the same.

Here is the code for the console application (HTMLMail.cs)

using System;
using System.Web.Mail;

class HTMLMail
{
    public static void Main()
    {
        Console.WriteLine("Sending Mail");
        try
        {
            MailMessage oMail = new MailMessage(); 
            Console.WriteLine("Mail Created"); 
            oMail.To = "[email protected]";
            oMail.Cc = "[email protected]"; 
            oMail.From = "[email protected]";
            oMail.Subject = "Hi Yateen";
            oMail.BodyFormat = MailFormat.Html;
            string strBody = "Hello Yateen" +
                                   " This is from .NET";
            oMail.Body = strBody;
            // Your SMTP Server name.
            // By Default , it is localhost if not specified
            SmtpMail.SmtpServer = “Smtp Server Name”
            SmtpMail.Send(oMail);
            Console.WriteLine("Mail Sent"); 
        }
        catch(Exception ex)
       {
           Console.WriteLine("Error : " + ex.Message);
        }
     }
}

We create a Mail object and set the appropriate mail properties like To, From, CC, Subject, and Body and then set the BodyFormat property of the mail object to HTML.

Let's see how do we add an attachment to the above mail. Add the command given below just before we send the mail with the statement Smtp.Send .

oMail.Attachments.Add(new MailAttachment("c:\\aishwarya1.jpg"));


Compile the above code using the following command

csc /r:System.Web.dll HTMLMail.cs

You can run the console.exe from command prompt to send the mail. Happy Coding !!!!

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish