How to send an Email using C# – complete features

This article provides detailed information on how to send Email using C# in a step by step procedure. Although there are many articles on the web providing the same info, many of them left out some interesting concepts untouched. Concepts like Alternate Views, Linked Resources add an additional fragrance to the world of Email in C#.

Out of my experience in the fascinating world of ASP.NET and C#, it’s been observed that many of the new programmers often run into lot of doubtful scenarios while performing an Email assignment. The thought of helping new comers is my prior motivation which made me to write this article.

Step By Step Procedure:

Step 1:

Create a new project in Microsoft Visual Studio 2008 (File -> New -> Project -> Visual C# -> Console Application)

Give an appropriate name (in this case ‘SendEmail’) and also specify the location where to store the project. Leave remaining options untouched.

This step created a console application, where we can create the classes we want and execute them from the command prompt.

Step 2:

Now add a new item to the project we just created (Project -> Add New Item -> Class).

Specify a name to the class (here it is ‘Email’). The code now looks like as follows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SendEmail
{
    class Email
    {
    }
}

This completes the basic setup of the project. Now we will see what are the namespaces required to send an email.

Step 3:

Import the below namespaces – (just type them after ‘using System.Text’)

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

System.Net.Mail – by importing this namespace we can use the inbuilt classes like SmtpClient, MailMessage, MailAddress in our code, which are the important classes required to send email.

System.Net.Mime – by importing this we can send email using Multipurpose Internet Mail Extensions like by specifying attachments like pdf’s, sending images in the body of email etc.

Add the Main thread to the class. So at the end of the section the code should be as follows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net.Mime;

namespace SendEmail
{
    class Email
    {
        public static void Main(string[] args)
        {
        }
    }
}

Step 4:

Now comes the important coding to accomplish email task. For the sake of understanding the process, the complete code is divided into five blocks.

Block 1:

Create objects of MailMessage and SmtpClient –

MailMessage m = new MailMessage();
SmtpClient sc = new SmtpClient();

MailMessage helps us to create the mail and SmtpClient allows us to send mail to the reciepient.

Block 2:

NOTE: the following code is configured to send mails from GMAIL account, later we can configure it as per our requirement.

Add – From, To, CC, BCC, subject, Body – as shown.

m.From = new MailAddress("from@gmail.com", "Display name");
m.To.Add(new MailAddress("to@domain.com", "Display name To"));
m.CC.Add(new MailAddress("CC@yahoo.com", "Display name CC"));
//similarly BCC
m.Subject = "Test";
m.Body = "This is a Test Mail";

MailMessage also provides provision to include options like Priority (sets priority of mail), DeliveryNotificationOptions(instructs SMTP server to send a message to FROM address in case of delay, fail or success mail departure), ReplyTo (email address to which replies will be sent).

Block 3:

Add attachments to the mail using MailMessage.Attachments – To add attachments using file stream, we got to import System.IO namespace.

FileStream fs = new FileStream("E:\\TestFolder\\test.pdf", FileMode.Open, FileAccess.Read);
Attachment a = new Attachment(fs, "test.pdf", MediaTypeNames.Application.Octet);
m.Attachments.Add(a);

We can send multi-media type attachment as shown above or else a simple attachment can be send as follows.

m.Attachments.Add(new Attachment("E:\\windows\\win32.ini"));

Block 4:

This block tells us how to send HTML emails. To send an Html mail we must first make MailMessage.IsBodyHtml to true and to send any images in the mail, we got to use AlternateView and LinkedResource concepts. The code goes as below.

string str = "<html><body><h1>Picture</h1><br/><img src=\"cid:image1\"></body></html>";
AlternateView av = AlternateView.CreateAlternateViewFromString(str,null,MediaTypeNames.Text.Html);
LinkedResource lr = new LinkedResource("E:\\Photos\\hello.jpg", MediaTypeNames.Image.Jpeg);
lr.ContentId = "image1";
av.LinkedResources.Add(lr);
m.AlternateViews.Add(av);

To reference images attached as linked sources from your Html message body, use cid:contentID in the image tag. And then specify the same name for the LinkedResource.ContentID.

Block 5:

Final block comes with the SMTP credentials (credentials of SMTP server which is responsible to send the message to the recipient).

sc.Host = "smtp.gmail.com";
sc.Port = 587;
sc.Credentials = new System.Net.NetworkCredential("from@gmail.com", "password of from");
sc.EnableSsl = true; // runtime encrypt the SMTP communications using SSL
sc.Send(m);

The other way around maintaining SMTP credentials for a web application is to use Web.Config file. Add the following code in the configuration section of Web.Config file.

<system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="from@gmail.com">
        <network defaultCredentials="true" host="smtp.gmail.com" port="587"
                 userName="from@gmail.com" password="passworf of from"/>
      </smtp>
    </mailSettings>
  </system.net>

And now there is no need to define smtp credentials every time and everywhere in the web application. And this completes the email assignment.

Important Point:

1) Always use TRY…CATCH block to catch the exceptions, because dealing with SMTP might results in lot of exceptions. Some of the exceptions are SmtpException (when user is not valid), InvalidOperationException (server hostname not defined), SmtpFailedRecipientException etc.

2) The complete example dealt with smtp.gmail.com credentials, in case to send email from different domain use corresponding domain credentials.

Final Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;

namespace SendEmail
{
    class Email
    {
        public static void Main(string[] args)
        {
                   MailMessage m = new MailMessage();
                   SmtpClient sc = new SmtpClient();         
            try
            {
                m.From = new MailAddress("from@gmail.com", "Display name");
                m.To.Add(new MailAddress("to@domain.com", "Display name To"));
                m.CC.Add(new MailAddress("CC@yahoo.com", "Display name CC"));
                //similarly BCC
                m.Subject = "Test1";    m.IsBodyHtml = true;    m.Body = " This is a Test Mail";

                FileStream fs = new FileStream("E:\\TestFolder\\test.pdf", 
                                   FileMode.Open, FileAccess.Read);
                Attachment a = new Attachment(fs, "test.pdf", 
                                   MediaTypeNames.Application.Octet);
                m.Attachments.Add(a);


                string str = "<html><body><h1>Picture</h1><br/><img 
                                 src=\"cid:image1\"></body></html>";
                AlternateView av = 
                             AlternateView.CreateAlternateViewFromString(str, 
                             null,MediaTypeNames.Text.Html);
                LinkedResource lr = new LinkedResource("E:\\Photos\\hello.jpg", 
                             MediaTypeNames.Image.Jpeg);
                lr.ContentId = "image1";
                av.LinkedResources.Add(lr);
                m.AlternateViews.Add(av);

                              
                sc.Host = "smtp.gmail.com";
                sc.Port = 587;
                sc.Credentials = new
                  System.Net.NetworkCredential(“from@gmail.com","Password");
                sc.EnableSsl = true;
                sc.Send(m);

                Console.ReadLine();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
    }
}

Conclusion:

Concepts behind – “How to send email using C#” are discussed thoroughly and successfully implemented. Sending and Html email with Alternate Views and Linked Resources is discussed. Configuring SMTP server credentials is shown in code.

You may also like...

4 Pingbacks/Trackbacks

  • RamiVemula

    @Renu – I am not able to understand what do you mean by Feedback, so you mean Replies to the email sent. In that case you need to use Pop3 or IMAP to get those. In case you need to allow any domain email to send emails, then you need to have all those SMTP Settings in your code or atleast in your config file and dynamically determine them. Password is simply for your code to get connected to your SMTP Server. There is no need to ask password from user.

  • Jules Bartow

    How is this complete? Where is the Asynchronous send?

  • RamiVemula

    @Jules – Please read disclaimer, but I appreciate your point. For that please read my article on Sending Automated emails using windows Services, even in that I used IAsyncResult, but not SendAsync(). I will write about SendAsync() in a new article and will link it to the existing one.

  • Vibs

    Thanks… Very well explained. Specially the display name part.

  • Vince Deegan

    Thanks Rami. Well explained.
    Have a question though:
    When I implemented your example, I used my own mail provider, Yahoo. But, was only getting either a timeout error or a Failed to send Mail error.
    For the “From” info, I put my email address, and for the “To” info, I gave the same address since I was sending it to myself. For the Host name, I used smtp.yahoo.com, and for the Port, I used 465. For the credential info., I put my user name (email address) and my password.
    Thanks for any suggestions.
    P.S. I also tried using another Try/Catch and the InnerException function, directly around the Send command just to check for more details. And the main thrust of the error info was that the host failed to respond from port 465. Don’t know what other port to use.

  • RamiVemula

    @Vince – Probably you might need to comment out EnableSSl code – take this reference – http://stackoverflow.com/questions/8007510/failed-to-send-email-from-yahoo-server-in-gmail-is-working
    Thanks,

  • maxamillion

    Hi Rami,
    Thanks for this post, I have spent hours today looking for this kind of information. A Lot of pages that I have visited showed promise but alas fell down in the end.

    After reading through our page I was able to modify my code and start sending emails within about 5 minutes.

  • Ron

    Dear Rami,

    When i use your code, I get the execption “Fout bij het verzenden van e-mail”
    Dutch for ‘Failing to send the email’. Can it be that i should use different Gmail SMTP credentials?

    I live in the Netherlands

    Ron

  • RamiVemula

    @Ron – Probably port number issue.

  • Vipin Viswanath

    Dear RamiVemula , great article. I could easily put this in to effective use.

  • Sajith

    it is nice article ….but i have one doubt .
    how to add abuse email id when mail sending.. could u please send it

  • RamiVemula

    @Sajith – if you want to add report abuse functionality, what I wold suggest is to have a anchor tag in html email, which points to a specific report abuse page in your application. Have proper querystring params in the url and then upon click on this url, you can grab the querystirng params and process report abuse case on backend.

  • Vivien

    fantastic publiѕh, very informative. I ponder whу
    the other specialists of this sector do not гealizе this.

    Yοu must contіnuе yοur writing.
    I am confidеnt, you’ve a huge readers’ base
    alreаdy!

  • swetha

    nice , article

  • Jung

    Hey there would you mind letting me know which webhost you’re working with? I’ve loaded your blog in
    3 completely different web browsers and I must say this blog loads a lot faster then most.

    Can you recommend a good web hosting provider at a fair price?
    Cheers, I appreciate it!

  • RamiVemula

    @Jung – Creadit goes to Niraj – http://www.anirajkumar.com/

  • Nirav Savla

    Hiii My question is , in case of the wrong email address when email get bounced back how to handle this email or find the email and log them .

  • RamiVemula

    @Nirav – You need some POP3 or IMAP components to receive bounce back emails.

  • khayati

    i have a quick contact form in my website when user fill the form all the content of the form is send to my server email id in which my site is host

  • RamiVemula
  • Vagai

    I got an error message.
    The remote certificate is invalid according to the validation procedure.

  • RamiVemula

    @Vagai – Check out this solution – http://forums.asp.net/t/1808054.aspx/1

  • Lelala

    Problem with that code is, it will wait until the receiver’s sever will pick up the mail when your server is calling – since this may take 2 – 3 seconds your app seems to hang, if its a desktop app; if its a webapp, your page rendering/loading will seem to hang.
    Only solution is to make this an asynchron task:
    Either by sending the mail in a background thread (by encapsulating the smtp-mail-setup stuff in a class), or use some of the fancy MVC features to accomplish it.
    Regards,
    Lelala

  • Amanda

    Great code! Im a beginner in c#, i came across this error message:

    A first chance exception of type ‘System.Net.Mail.SmtpException’ occurred in System.dll
    Failure sending mail.

    Please help!

  • RamiVemula

    @Amanda – There can be many reasons for that exception. Do some online research and you have to provide more details to resolve this error.

  • Lokesh

    It shows sending mail failure at the line sc.Send(m);

  • Lokesh
  • dhaval savaliya

    how to run program

  • RamiVemula

    @dhaval – using F5.

  • Pingback: Sending email request | DiMo()

  • Mayaa

    Nice post !! thanks.. was really helpful.

  • THILLAI

    Nice,,thanks

  • Anoop

    Is there any way to append a image in base64 string in a mail and send. When I tried, it works fine with yahoomail. It doesn’t work with other email applications

  • noman

    i want to make a website whicj user sen email to me with the help of my website (form) any help me i am new in .net please hep me

  • nathan

    You can use CDO for sending mail instead of SMTP…C# CDO Email

    Nathan

  • Pingback: Sending mail on web App C# asp.net | Asp Forum()

  • Pingback: [RESOLVED]Send mails to users | Asp Forum()

  • Pingback: [RESOLVED]how to send mail from aspx contact form page in hosting | Asp Forum()

  • http://freelancersgigs.com Linda

    Great, if you have time, then check out my website as well!