How to send an Email using C# – complete features

March 14, 2013 |

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.

0 comments:

Post a Comment