CODEDIGEST
Home Articles CodeDigest Tutorials InstallShield FAQs
Skip Navigation LinksHome » Article » ASP.Net Article » Sending Email using C# and ASP.Net 2.0  Submit Articles and Win Geeky Prizes!!   You are not logged in.
Search
 

Sponsors
InstallShield
 

Product Spotlight
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Sending Email using C# and ASP.Net 2.0
Free Trial: InstallShield 2010 for Windows Installers Is InstallShield right for you? InstallShield handles your most complex installation requirements in minutes. Try it now.

By Satheesh babu
Posted On Jul 11,2008
Article Rating: (Login)
Average Rating: 5
No of Ratings: 1
No of Comments: 30
Category: ASP.Net
Print this article.

Subscribe to our feed!

Sending Email using C# and ASP.Net 2.0

 

Most often, we will have requirements to send email from our asp.net applications. This article will help us understand some of the available techniques we can use to send email from asp.net applications. With the introduction of .Netframework 2.0, the classes for sending email are packed in System.Net.Mail namespace as opposed to System.Web.Mail namespace in 1.x framework. Moving forward we will see,

InstallShield

Ø       Sending a Simple Mail

Ø       Sending Mail with Attachment

Ø       Sending Mail with HTML body

Ø       Sending Email with Embedded Image in the Message Body

Ø       Sending Email with Gmail SMTP Server from ASP.Net

 

Sending a Simple Mail

MailMessage mail = new MailMessage();

mail.To.Add("to@gmail.com");

mail.From = new MailAddress("from@gmail.com");

mail.Subject = "Test Email";

string Body = "Welcome to CodeDigest.Com!!";

mail.Body = Body;

SmtpClient smtp = new SmtpClient();

smtp.Host = ConfigurationManager.AppSettings["SMTP"];

smtp.Send(mail);

 

The above code can be used to send a simple email.

 

Sending Mail with Attachment

We can also send email with attachments. The below code will help you to achieve it.

 

MailMessage mail = new MailMessage();

mail.To.Add("to@gmail.com");

mail.From = new MailAddress("From@gmail.com");

mail.Subject = "Test Email";

string Body = "Welcome to CodeDigest.Com!!";

mail.Body = Body;

mail.Attachments.Add(new Attachment(@"F:\Articles\Email in ASP.Net 2.0\SendEmail\mail.png"));

SmtpClient smtp = new SmtpClient();

smtp.Host = ConfigurationManager.AppSettings["SMTP"];

smtp.Send(mail);

 

Sending Mail with HTML Body

Sometimes, we will have requirements to send email as a HTML body. The below code will help you to achieve the same.

MailMessage mail = new MailMessage();

mail.To.Add("to@gmail.com");

mail.From = new MailAddress("From@gmail.com");

mail.Subject = "Test Email";

string Body = "Welcome to CodeDigest.Com!!";

mail.Body = Body;

mail.IsBodyHtml = true;

SmtpClient smtp = new SmtpClient();

smtp.Host = ConfigurationManager.AppSettings["SMTP"];

smtp.Send(mail);

 

We may also have requirements to send email with an embedded image in the message body. This was made easy with ASP.Net 2.0 with the help 2 new classes that are packed in .Netframework 2.0. Next section will help us understand the same.

 

Sending Email with Embedded Image in the Message Body

We can embed image in the email body using LinkedResource class and AlternateView class that is packed with System.Net.Mail namespace and by making the message body as HTML.

 

How to achieve this?

 We have to include a <IMG> with a contentid specified in src attribute of <IMG> tag in the message body, i.e. the HTML body should contain <img src="cid:imageId" />.

Example will be,

<b>View my Pic</b><br>

<img src="cid:Anyid" />

 

We need to give the same contentid to the ContentId attribute of LinkedResource object for the code to work.

 

Implementation

try

        {

            MailMessage mail = new MailMessage();

            mail.To.Add("to@gmail.com");

            mail.From = new MailAddress("from@gmail.com");

            mail.Subject = "Test with Image";

            string Body = <b>Welcome to codedigest.com!!</b><br><BR>Online resource for .net articles.<BR><img alt=\"\" hspace=0 src=\"cid:imageId\" align=baseline border=0 >";

 

            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body, null, "text/html");

            LinkedResource imagelink = new LinkedResource(Server.MapPath(".") + @"\codedigest.png", "image/png");

            imagelink.ContentId = "imageId";

            imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;

            htmlView.LinkedResources.Add(imagelink);

            mail.AlternateViews.Add(htmlView);

            SmtpClient smtp = new SmtpClient();

            smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;

            smtp.Send(mail);

        }

        catch (Exception ex)

        {

            Response.Write(ex.Message);

        }

Sponsors

Useful Books For Developers
Learning jQuery 1.3 More books..

Similar Articles

OUTPUT

 

Sending Email with Gmail SMTP Server from ASP.Net

To send email using gmail SMTP server you will require a valid gmail userid and password. If you didn’t specify a valid gmail userid and password then you will get the following error.

 

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

 

The below code can be used to send email using gmail SMTP server, smtp.gmail.com.

 

MailMessage mail = new MailMessage();

mail.To.Add("to@gmail.com");

mail.From = new MailAddress("from@gmail.com");

mail.Subject = "Test Email";

string Body = "<b>Welcome to CodeDigest.Com!!</b>";

mail.Body = Body;

mail.IsBodyHtml = true;

SmtpClient smtp = new SmtpClient();

smtp.Host = ConfigurationManager.AppSettings["SMTP"];

smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["FROMEMAIL"], ConfigurationManager.AppSettings["FROMPWD"]);

smtp.EnableSsl = true;   

smtp.Send(mail);

 

Web.Config

<appSettings>

    <add key="SMTP" value="smtp.gmail.com"/>

    <add key="FROMEMAIL" value="mail@gmail.com"/>

    <add key="FROMPWD" value="password"/>

  </appSettings>

 

Conclusion

Thus, we have understood some of the common ways we can use to send email from our asp.net applications. Sending Email with Embedded image in the message body is a very useful feature that ASP.Net 2.0 provides us to send email.

Happy Coding!!

 

You can contribute to CodeDigest.Com:
Donate to CodeDigest.com
Article Feedback
Title  
Submitted By  
Comment  
Enter the verification number
 
Comments
dsfsd
sdfgsd
Very Good Article
This is really very simple, good and well-explanatory code to understand.
Best tutorial online
I've been struggling to find a tutorial online as straight forward as yours... but even better on the actually WORK

KUDOS TO YOU!
What to do
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. k29sm8803835fkk.51
Thanks
I have an image stored on the server itself. When i am using LinkedResource imagelink = new LinkedResource(Server.MapPath(".") + "@\\App_Themes\\White\\Images\\StationeryLogo.gif", "image/gif");
it is using my local path. How to take the image from the server itself.
thanks
Really nice article.. Thanks a ton
A new solution
here's something about that
http://www.stjhimy.com/2009/12/13/how-to-send-an-email-using-c/
Web 2.0 Application Generator Generate database and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download
This article is really useful.
All the methods to send an email in ASP.Net are given.
Its really good.
Thanks
How to send a link embedded
I want to send a couple of embedded links together with an inline image. But when I send the links in plain html, the link is taken as <a rel="no follow">. I just use something like this in the code.

<a href="www.google.com"></a>

Do you know the reason for this?
How to send a link embedded
I want to send a couple of embedded links together with an inline image. But when I send the links in plain html, the link is taken as <a rel="no follow">. I just use something like this in the code.

<a href="www.google.com"></a>

Do you know the reason for this?
SMTP Mailer
Your code was very straight forward. Thank You. I also found a pre-build static class with source code here to for those who need extra help. http://easykb.com/default.aspx?id=43
send email
how to send email in asp.net 2.0 with C# 2.0 for more users account

each user have email how to send all users .

ad_tach@yahoo.com
it says " No connection could be made because the target machine actively refused it "
i implemented a s u said but it is saying " No connection could be made because the target machine actively refused it " what to do..???
Excellent tutorial buddy
This tutorial has full example for sending email and it is very helpful. Thank a lot
QUERY,PLS REPLY
I got an error while running this code.Error is "transport failed to connect to server".my smtp server is localhost.what is the solution,Pls reply
query
how can i use the web cam and microphone of my computer for voice calling and vedio conferencing in asp.net using c# and socket
VEry Helpful Code
This code snippet is very helpful.
Exelent Eork
same as my requriment.
exelent turtorial, thans alot.
best regards;
sohail
karachi pakistan
Thanx
Great tutorial. Just what I needed to know. Code worked like a charm.
RE:please
Hi John,
Thanks for the feedback...If you are really confused where to place the code, then it depends on your need..It can be on a button click event or in a class methid etc..The above code will work fine if you import System.Net.Mail namespace..
please
Please if you want to help be more explicative and clear in your tutorial, it is a bit confusion. where to place what and so on can be very usefull.

thanks
sending email in html format in c#
Some little bit error in this code. i m not satisfy
my feedback
very nice
Clarification Needed
Your code is very useful.
I am doing website for our company. In "Contact Us" page, I am getting user's email and I am trying to send mail to
our company's contact id. Since we are using SMTP , I am not getting that user's email id in our mail. Can you tell me
how to solve this problem.
Thanks.
thanks
your code is very good for using mail mesage on every system.
using SMTP port
look at http://testedcode.blogspot.com/2008/08/sending-email-in-aspnet-20-using.html
sending email with gmail
great article,keep up the good work
Error Message
I've got error message in sending email.Error message about in stmp. What can i do? Please reply to my email.. fretplaystyle@yahoo.com thanks!
Good Job
A good job, I olny had problem obtaining the server path but it works good
Thank You for your help
Your work is wonderful to help people that realy need your help.