How to send an Email using C# and ASP .net – complete features

Original Post: [Me] and http://www.intstrings.com/ramivemula/articles/how-to-send-an-email-using-c-net-with-complete-features/

Methods – 1:  clsMail.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using ug_admission;

namespace ug_admission
{
public class clsMail
{
public clsMail()
{
//
// TODO: Add constructor logic here
//
}

public static bool sendEmail(string strSubject, string strFrom,
string strTo, string strBody, string strCc,
string strBcc, string displayName)
{
System.Net.Mail.SmtpClient Mail = new System.Net.Mail.SmtpClient();
Mail.Host = clsMail.value(“SMTPServer”).ToString();

string username = null;
string Password = null;
if (clsMail.value(“UseDefaultCredentials”) + “” == “false”)
{
Mail.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
username = clsMail.value(“MailUserName”);
Password = clsMail.value(“MailPassword”);
System.Net.NetworkCredential basicAuthenticationInfo =
new System.Net.NetworkCredential(username, Password);
//if ((clsMail.value(“MailPort”) != null) && (IsNumeric(clsMail.value(“MailPort”))))
if ((clsMail.value(“MailPort”) != null))
{
Mail.Port = Convert.ToInt16(clsMail.value(“MailPort”));
}
Mail.UseDefaultCredentials = false;
Mail.Credentials = basicAuthenticationInfo;
if (clsMail.value(“EnableSsl”) == “True”)
Mail.EnableSsl = true;
}

System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage();
myMail.Subject = strSubject;

myMail.From = new System.Net.Mail.MailAddress(strFrom, displayName);
myMail.To.Add(new System.Net.Mail.MailAddress(strTo));
if (!string.IsNullOrEmpty(strCc))
{
myMail.CC.Add(new System.Net.Mail.MailAddress(strCc));
}
if (!string.IsNullOrEmpty(strBcc))
{
myMail.Bcc.Add(new System.Net.Mail.MailAddress(strBcc));
}

if (clsMail.value(“sendBccTest”) == “True”)
myMail.Bcc.Add(new System.Net.Mail.MailAddress(
clsMail.value(“sendBccTestEmailAddress”)));

myMail.IsBodyHtml = true;
myMail.Body = strBody;
try
{
Mail.Send(myMail);

return true;
}
catch (Exception ex)
{
ex.Message.ToString();
return false;

}
}

public static string value(string key)
{
if ((ConfigurationManager.AppSettings[key] != null))
{
return ConfigurationManager.AppSettings[key];
}
return ConfigurationManager.AppSettings[“SiteUrl”];
}

//public static System.Boolean IsNumeric(System.Object Expression)
//{
//    if(Expression == null || Expression is DateTime)
//        return false;

//    if(Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
//        return true;

//    try
//    {
//        if(Expression is string)
//            Double.Parse(Expression as string);
//        else
//            Double.Parse(Expression.ToString());
//            return true;
//        } catch {} // just dismiss errors but return false
//        return false;
//    }
//}
}
}

Web.config

<configuration>
<appSettings>
<add key=”SMTPServer” value=”smtp.gmail.com”/>
<add key=”UseDefaultCredentials” value=”false”/>
<add key=”MailUserName” value=”from@gmail.com”/>
<add key=”MailPassword” value=”password”/>
<add key=”MailPort” value=”587″/>
<add key=”EnableSsl” value=”True”/>
<add key=”sendBccTest” value=”False” />
<add key=”SiteUrl” value=”http://www.website.com”/&gt;
</appSettings>
</configuration>

Calling: clsMail.sendEmail(“Test Subject”, “from@gmail.com”, “to@gmail.com”, “Body”, “cc@gmail.com”, “bcc@gmail.com”, “From Display Name: System Admin”);

Methods – 2: Original post: http://www.intstrings.com/ramivemula/articles/how-to-send-an-email-using-c-net-with-complete-features/

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s