Register | Login
Friday, August 29, 2008

Sections
  
About Us
  
Hosting Provided by Server Intellect
Partners
Downloads
  
 WWWCoder.com Resource Directory

Sending emails with ASP .NET
2/1/2005 10:30:08 PM

In this article, you'll see how sending email with ASP .NET is possible and then we'll go deeper to see how you can use HTML emails or include attachments.

I can't imagine a complete website that hasn't got a function to email someone, either the user when he registers or the administrator when someone contacts him through the website. No doubt, ASP .NET must have a class that can be used to send emails. Actually, there are two: SmtpMail and MailMessage.
In this article, you'll see how sending email with ASP .NET is possible and then we'll go deeper to see how you can use HTML emails or include attachments.

But first you'll need to check if the Microsoft SMTP Service is turned on. To do this either open the Internet Services Manager directly or open Computer Management and Navigate to Internet Information Services -> Default SMTP Virtual Server and checkout if the button with the 'play' icon on it is disabled, that means it is already started.



Microsoft SMTP Service is the one we'll use in this article, but you can as well use something more professional like the Microsoft Exchange Server. The reason why we're using the first mentioned is because it's included in Windows XP Professional and Windows 2000.

Testing Microsoft SMTP Service

It's better to test it before using it in an ASP .NET application so if it doesn't work, at least you can't blame it on the web application. It's incredible how easy it is to test this service.
By default, your folder for IIS files is located somewhere in C:\Inetpub. In addition, the folders that Microsoft SMTP Service uses are located here, more exactly the folder is called mailroot. The SMTP service uses these folders to store email messages. You can see a total of seven folders, the most important one for sending email is Pickup - open this folder. Now start the best editor possible: Notepad. In it paste the following lines:

To: andrei_pociu@geekpedia.com
From: arthur_vandelay@geekpedia.com
Subject: Hello Andrei

I'm testing the Microsoft SMTP Service, didn't meant to bother.

You recognize the typical fields used to send email, to, from and subject and below the content of the email. In the From field you can enter any email address you want, even if it's not yours. Now save this file in the Pickup folder using any name you wish, test.txt for example. The next second it should disappear... that's because it was sent. If you leave the fields unchanged, it will send it to my email address and I'll know that you're reading my article right now.

Now that we settled this out, we can start developing. Fire up Microsoft Visual Studio .NET and start a new ASP .NET Web Application.
To the WebForm add four TextBoxes, the last one should have the property TextMode set to MultiLine (makes it a textarea). Also, add a button to the recipe. The entire layout should look like this:



I recommend setting the ID property of each textbox to txtFrom, txtTo, txtSubject and txtContent and for the button btnSend so that we don't confuse them.

Now we get to my favorite part, coding. Open WebForm1.aspx.cs, the first thing we must do is import the namespace where SmtpMail and MailMessage classes are:

using System.Web.Mail;

Next, create a new instance of the MailMessage class:

protected MailMessage MMsg;

Double click the button on the WebForm to get to the btnSend_Click() event. Inside paste the following code:

MMsg = new MailMessage();
MMsg.From = txtFrom.Text;
MMsg.To = txtTo.Text;
MMsg.Subject = txtSubject.Text;
MMsg.Body = txtContent.Text;
SmtpMail.Send(MMsg);


We create a new instance of MailMessage on the first line and then we set several properties needed to send the message. The last line actually sends the email by using the Send() method of SmtpMail.
Sometimes when you upload your website to a webhost you'll have to change the SMTP server. This can be done by changing the SmtpServer property:

SmtpMail.SmtpServer = "localhost";

localhost is the name of the SMTP server but you could as well enter an IP.

As you can see, sending emails is a very simple task in ASP .NET and can be done just by setting a few properties. The application is now fully functional and you can compile it, run it, fill in the fields and press btnSend.

There are some other properties you can set, like CC (Carbon Copy) or BCC (Blind Carbon Copy) which are both well known in email messaging.
Another property you might be interested in is Priority, which can set the message priority to Low, Normal or High.
Here's an example of how to use it:

MMsg.Priority = MailPriority.High;

We all know that email messages can be either plain text or HTML. By default they are sent as plain text, but you can change this by setting the BodyFormat property to Html:

MMsg.BodyFormat = MailFormat.Html;
However there's more about HTML email, and that's covered in the next section.

Sending HTML emails

In most cases plain text may do the job, but sometimes you will want to send HTML email, for sending a newsletter perhaps. We saw earlier how you can change from plain text to HTML email just by setting a property but there's more than this as you will see here. First let's send a simple HTML email message by using HTML tags in the body of the email. Be sure the BodyFormat property is set to MailFormat.Html and then set the Body property like in the following example:

MMsg.Body = "<HTML><HEAD><TITLE>Hello Andrei</TITLE></HEAD><BODY><h3>Hello Andrei</h3><p><font face='Verdana' size='2'>Just testing...</font></p></BODY></HTML>";

Here's how the message looks in Outlook 2003:



As expected, the HTML tags to their job and format the message.

Using HTML you can also include graphics and links just like in a webpage. In regard to the graphics and links I should mention that you should use the complete path and not relative URLs. For example instead of img/SomeIcon.gif you would have to use http://www.somedomain.com/img/SomeIcon.gif.
That doesn't represent a problem in short messages that have a link or two or a graphic or two, but when you want to format the entire email message to look like a webpage and you have tens of graphics, using complete paths gets annoying. Microsoft thought of that so there's a solution - the UrlContentLocation property - used like in the following example:

MMsg.UrlContentLocation = @"http://www.somedomain.com/img/";

Now you can simply use SomeIcon.gif as the path of the graphic. The same applies to links to different pages on your website.

Sending emails with attachments

Email attachments are sent just as easy with the help of the MailAttachment class and its two properties.
First, we have to create a new instance of this class:

protected MailAttachment MAtt;

And then in the btnSend_Click() event, just before the SmtpMail.Send() method, paste the following lines:

MAtt = new MailAttachment(@"C:\Document.pdf");
MMsg.Attachments.Add(MAtt);


The path is set when creating the new instance of MailAttachment, and after that the mail attachment object is added to the attachments list of the email message (because you can have multiple attachments simply by using Add() multiple times with different files).

However, normally the visitor will type the path to the file he wants, or even better, he can browse and select the file he want so send as attachment. Open WebForm1.aspx and inside Form1, just above the button that sends the message, add the following line:

<input id="txtFile" type="file" runat="server" size="32">

This control adds a textbox and a button to the webform which you can use to browse to the file you want. Here's an example of a completed form.



Now don't forget to change the path to the attachment to reflect the content of the textbox and also before adding the attachment the application should check to see if the user specified any attachment at all, because if the textbox is empty an exception will occur.

if(txtFile.PostedFile != null)
{
MAtt = new MailAttachment(@txtFile.PostedFile.FileName);
MMsg.Attachments.Add(MAtt);
}


Even if we get a little bit off-topic, you might be interested in limiting the allowed size of the attachment.
To limit the allowed size of the attached file to 1 MB (1024 bytes) you have to retrieve the size of the file, so here's the modified if condition that does exactly this:

if(txtFile.PostedFile != null && txtFile.PostedFile.ContentLength <= 1024)
{
MAtt = new MailAttachment(@txtFile.PostedFile.FileName);
MMsg.Attachments.Add(MAtt);
}


There's not much more to say about the SmtpMail and MailMessage class, the methods and properties listed here are the ones you'll need most of the time.

Andrei Pociu
Geekpedia.com


Page Options:
format for printing  Format for Printer
email article  Email Page
add to your favorites   Add to Favorites
How would you rate the quality of this content?
Poor - - Excellent
Comments?
Overall Rating:
Comments Left:
Left on 5/16/2008 2:23:49 AM by Anonymous
Comments: very nice site, but so boring
No ratings available.
Left on 5/1/2008 10:48:41 AM by Anonymous
Comments: thank you.
Left on 4/24/2008 1:46:50 AM by Anonymous
Comments: fgf
Left on 10/7/2007 12:50:31 AM by Anonymous
Comments: 2525
Left on 4/26/2007 5:25:29 AM by Anonymous
Comments: Its working nice,my doubt is if i send mail by others mailid ,is there any security for that

Left on 4/26/2007 5:23:39 AM by Anonymous
Comments: Its working nice,my doubt is if i send mail by others from address any possibilities to check
Left on 2/21/2007 5:26:19 AM by Anonymous
Comments: i am not able to send the mail.it is stagnent in queue.

Left on 1/12/2007 5:44:30 AM by Anonymous
Comments: hello sir
i want ot extract the data fro email attachment.could u help me.
thank you
No ratings available.
Left on 9/19/2006 6:15:48 AM by Anonymous
Comments:
Left on 6/26/2006 7:29:01 AM by Anonymous
Comments: should be able 2 send mail

Left on 6/21/2006 2:51:57 AM by Anonymous
Comments: using System.Web.Mail;


No ratings available.
Left on 5/30/2006 9:32:55 AM by Anonymous
Comments: You may need to authenticate your email. refer to the following article: http://www.wwwcoder.com/main/parentid/435/site/5833/68/default.aspx
Also make sure your mail server allows the web server's ip address to relay email.
No ratings available.
Left on 5/30/2006 8:45:03 AM by Anonymous
Comments: error msg:The server rejected one or more recipient addresses. The server response was: 550 5.7.1 Unable to relay for mail address

No ratings available.
Left on 5/23/2006 3:58:40 AM by Anonymous
Comments: it is ok but need more options for get accurate Result.
No ratings available.
Left on 5/17/2006 3:38:42 AM by Anonymous
Comments: my msg has not sent & it is restored in badmail
No ratings available.
Left on 5/12/2006 2:38:38 AM by Anonymous
Comments: I'm using the same method in my application, but my message is nowhere to be found. The send method doesn't throw any error message but, I'm not sure where the message is?

The message is not there in any of the folders under the mailroot directory, nor is it getting delivered to the intended receipents.

Have you faced anysuch situation? I'm connecting to a relay server to send out mails, and this is working fine for my ASP/ASP.NET1.x applications.

No ratings available.
Left on 5/9/2006 3:19:08 AM by Anonymous
Comments: My message has not been sent but it is restored in Queue folder.
No ratings available.
Left on 4/13/2006 5:39:16 AM by Anonymous
Comments: good
Left on 4/8/2006 11:45:24 PM by Anonymous
Comments: need help on how can i attatch a file... :D this site is a good reference, i'm currently making a project now.
Left on 2/21/2006 10:03:44 PM by Anonymous
Comments: I am sure it is great, but he doesn't address the problem most are having.. Why is mail left in the queue folder?
Left on 1/31/2006 5:02:23 AM by Anonymous
Comments: good,but can have more information.
Left on 8/30/2005 7:52:04 PM by Anonymous
Comments: Good thx
No ratings available.
Left on 8/17/2005 4:03:43 AM by Anonymous
Comments: Good One, Sir
No ratings available.
Left on 8/16/2005 2:20:17 AM by Anonymous
Comments: nice work.....but why the mails are sent to the queue folder instead of the mail server/receipent??? Anyone help??
Left on 8/7/2005 12:22:50 PM by Anonymous
Comments: simple and good explanation
Left on 7/28/2005 4:55:03 AM by Anonymous
Comments: i tried the code u have given above but my system is showing the following error
"Could not access 'CDO.Message' object".
No ratings available.
Left on 7/26/2005 8:56:13 AM by Anonymous
Comments: its a great help but can u tel me y my code is not attaching the txt file
babulal.kr@gmail.com


mm.To=txtTo.Text;
mm.From=txtFrom.Text;
mm.Subject=txtSub.Text;
mm.Body=txtBody.Text;
mm.Priority=MailPriority.High;
MailAttachment mAtt;

if ( txtFile.PostedFile !=null)
{
file =@txtFile.PostedFile.FileName.ToString();
mAtt=new MailAttachment(file);
mm.Attachments.Add(mAtt);
}
No ratings available.
Left on 7/26/2005 7:51:46 AM by Anonymous
Comments: its really helped me a lot ..... nice work.
No ratings available.
Left on 7/16/2005 6:38:31 AM by Anonymous
Comments: Teoretically,Article is nice but not Practically.I checked in Services,SMTP is running but still I cant send mails...magi... magiselvakumar@yahoo.co.in
No ratings available.
Left on 7/14/2005 5:03:35 AM by Anonymous
Comments: Teoretically,Article is nice but not Practically.I checked in Services,SMTP  is running but still I cant send mails...Ram...
No ratings available.
Left on 7/7/2005 5:53:34 AM by Anonymous
Comments: it is not working properly pls check it out and send mail to sreekanth_chakra@yahoo.co.in
No ratings available.
Left on 7/6/2005 11:52:18 AM by Anonymous
Comments: Fantastic!
Left on 6/15/2005 10:20:14 PM by Anonymous
Comments: My mail is always on the queue folder. Could you help? Janine_chen@cardlink.co.nz
Left on 6/12/2005 2:32:09 AM by Anonymous
Comments: Hi, I got error msg as follows:

Unable to deliver this message because the follow error was encountered: "Error is processing file in pickup directory.".

The specific error code was 0xC00402CE.


No ratings available.
Left on 6/3/2005 6:51:47 AM by Anonymous
Comments: my mail is always on the queue folder sent mail to sanuks2004@yahoo.com
No ratings available.
Left on 6/3/2005 6:39:41 AM by Anonymous
Comments: my mail is always on the queue folder
No ratings available.
Left on 5/28/2005 4:29:03 AM by Anonymous
Comments: i have error message say
SmtpMail.Send(MMsg);
to relay Amr_h_g@hotmail.com


Left on 5/28/2005 4:24:45 AM by Anonymous
Comments: very interactive but i have wrror message say (error in send using SmtpMail.Send(MMsg);)
Left on 5/7/2005 10:41:54 PM by Anonymous
Comments: so good

No ratings available.
Left on 5/2/2005 5:34:13 PM by Anonymous
Comments: The server rejected one or more recipient addresses. The server response was: 550 5.7.1 Unable to relay. Could you please help me out? my email:zifa786@hotmail.com
No ratings available.
Left on 4/28/2005 5:32:38 AM by Anonymous
Comments: This article is really great. Well draft, simple and straight.
No ratings available.
Left on 4/28/2005 1:47:06 AM by Anonymous
Comments: The server rejected one or more recipient addresses. The server response was: 550 5.7.1 Unable to relay for jkrajes@rediffmail.com
No ratings available.
Left on 4/27/2005 7:34:40 AM by Anonymous
Comments: Hi, I tried it many times to test the SMPT service as you instructed.The smpt is on but my mails are in Queue folder. Could you please help me out? my email:ar_mukesh@yahoo.co.in
No ratings available.
Left on 4/26/2005 4:01:55 AM by Anonymous
Comments: but, didnt work for me. SMPT is on and I tried the example you posted but, for some reason my mail in Queue folder. I am using SMTP on localhost.email me @ : rashmi.n@tcs.com
No ratings available.
Left on 4/23/2005 3:24:22 AM by Anonymous
Comments: Excellent Article. I found the sent email message in the queue folder of the mailroot folder when I run the code for the first time. But the next time I run the code, I didn't find any email message in that folder. Can any body tell me what is the matter.
For contact : bbeginner@yahoo.co.uk
Left on 4/21/2005 4:25:41 PM by Anonymous
Comments: Hi, I tried three times to test the SMTP service as you instructed. but my mails are in Queue folder. Could you please help me out? my email: tz92612@yahoo.com
No ratings available.
Left on 4/21/2005 2:45:51 AM by Anonymous
Comments: Have a look here:

http://forums.asp.net/830926/ShowPost.aspx
No ratings available.
Left on 4/21/2005 2:32:22 AM by Anonymous
Comments: Hi Andrei Pociu,

I need to write an asp.net application which will connect to exchane server 2000 and retrieve address book and display the same on asp.net web form

can u help me out with is
Left on 4/18/2005 3:26:02 PM by Anonymous
Comments: is there vb code ?
No ratings available.
Left on 4/15/2005 2:26:54 AM by Anonymous
Comments: Hi ,

Thanks a lot for the article .
It works but i am not able to send any attachments that are not present in the root directory of the machine .
Like i can attach files on C:/ but not on the desktop .
How can i do that ?
Please help me !
No ratings available.
Left on 4/11/2005 1:38:28 AM by Anonymous
Comments: but, didnt work for me. SMPT is on and I tried the example you posted but, for some reason my mail in Queue folder
Left on 4/8/2005 5:08:27 PM by Anonymous
Comments: This Article helped me a lot. Thank You.
Left on 4/8/2005 6:34:45 AM by Anonymous
Comments: Hey man it worked once after that i just get some log on the C:\Inetpub\mailroot\Badmail link.. any idea.. what is causing this?
No ratings available.
Left on 4/5/2005 8:37:16 AM by Anonymous
Comments: Comments: error msg: The "SendUsing" configuration value is invalid. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Runtime.InteropServices.COMException: The "SendUsing" configuration value is invalid. Source Error: Line 62: MMsg.Subject = txtSubject.Text; Line 63:
pls  help me out.
my id is subhashinusa@yahoo.com
Left on 4/5/2005 1:48:59 AM by Anonymous
Comments: Good reference
Left on 4/4/2005 6:55:23 AM by Anonymous
Comments: Click
No ratings available.
Left on 3/31/2005 2:33:19 PM by Anonymous
Comments: Worth Reading

Left on 3/30/2005 7:31:27 PM by Anonymous
Comments: Big help, thanks.
Left on 3/30/2005 2:19:41 PM by Anonymous
Comments: but, didnt work for me. SMPT is on and I tried the example you posted but, for some reason my mail in Queue folder. I am using SMTP on localhost. This has something to do with my exchange server.Email me at saunak_it@yahoo.com
Left on 3/24/2005 5:10:07 AM by Anonymous
Comments: was very informative thanks .

I have learned a new concept today along with how things work in the system also
No ratings available.
Left on 3/23/2005 2:39:59 PM by Anonymous
Comments: good i got mails in my inetpup mailroot directory with something.eml how to recognise these and how to route this mails
Left on 3/23/2005 1:26:13 PM by Anonymous
Comments: This works like a charm!but i wanna know how to send messages, like when u recieve mails from somobody in the inbox you see the person's name, not his mail id. In the from field i want to associate a name with the e-mail id. Hope it is making sense!!!
Left on 3/23/2005 9:38:29 AM by Anonymous
Comments: too
Left on 3/23/2005 8:22:16 AM by Anonymous
Comments: how to route the emails
No ratings available.
Left on 3/22/2005 6:17:21 AM by Anonymous
Comments: stav
Left on 3/22/2005 4:01:28 AM by Anonymous
Comments: There was an error message. can u solve it. The error message is as follows:
The server rejected one or more recipient addresses. The server response was: 550 5.7.1 Unable to relay for somone@yahoo.com
Left on 3/21/2005 4:59:05 PM by Anonymous
Comments: error msg:
The "SendUsing" configuration value is invalid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime.InteropServices.COMException: The "SendUsing" configuration value is invalid.

Source Error:


Line 62: MMsg.Subject = txtSubject.Text;
Line 63: MMsg.Body = txtContent.Text;
Line 64: SmtpMail.Send(MMsg);
Line 65:
Line 66:

Source File: c:\inetpub\wwwroot\emailing\webform1.aspx.cs    Line: 64

No ratings available.
Left on 3/21/2005 12:56:19 PM by Anonymous
Comments: Excellent article!!! Exactly what I needed. Clearly explained. Thanks, Andrei.
No ratings available.
Left on 3/20/2005 8:38:35 AM by Anonymous
Comments: This is A good email site
Thank you for putting this
website on And Can you put micorsoft on This compurtre. And put msn as a Free email website.
    Thank You
No ratings available.
Left on 3/18/2005 8:02:47 PM by Anonymous
Comments: can you add a link to the source code?
No ratings available.
Left on 3/18/2005 5:21:23 AM by Anonymous
Comments: i tried to put a test.txt file in mailroot/pickup, it disappear but it went in queuw folder and venevr delivered, Also when i am sending email from my ASP.net system.web.mail using the same method you described, it goes to queue flder and never delivered. What may be the cause and what is its solution ?

No ratings available.
Left on 3/18/2005 1:40:25 AM by Anonymous
Comments:
The "SendUsing" configuration value is invalid.
Left on 3/17/2005 3:17:13 PM by Anonymous
Comments: but, didnt work for me. SMPT is on and I tried the example you posted but, for some reason my mail in Queue folder. I am using SMTP on localhost. This has something to do with my exchange server. email me at bpatel@360inc.com
Left on 3/17/2005 11:26:37 AM by Anonymous
Comments: Nice article.  Any way of handling MPA formatted messages (HTML/TEXT)?
No ratings available.
Left on 3/16/2005 10:02:13 AM by Anonymous
Comments: pitifull
Left on 3/16/2005 7:12:34 AM by Anonymous
Comments: Excellent, Please can your send me the source code....KC
No ratings available.
Left on 3/16/2005 5:07:28 AM by Anonymous
Comments: This Article is ok, in practical I could not able to send mails with the given statements to an external email id from my file like from abc@one.com to roysoft2@rediffmail.com please let me know how to do this

Left on 3/16/2005 12:09:48 AM by Anonymous
Comments: hai
Left on 3/16/2005 12:05:51 AM by Anonymous
Comments: eqwreqg
Left on 3/15/2005 3:35:46 PM by Anonymous
Comments: exactly what i needed to know, clearly explained
Left on 3/15/2005 12:05:38 PM by Anonymous
Comments: Thanks, man!  Blew my mind how easy this all can be.

John Nagy
Left on 3/14/2005 10:06:47 PM by Anonymous
Comments: I have had issues using .net mail because it doesn't queue up the messages when email is down like the CDONTS did. 
No ratings available.
Left on 3/14/2005 9:03:18 AM by Anonymous
Comments: Good article, but is it possible to send HTML and text using this method? Also, what about graphics as attachments in the message.
Left on 3/14/2005 8:12:36 AM by Anonymous
Comments: ghdfhdfh
No ratings available.
Left on 3/13/2005 8:52:56 AM by Anonymous
Comments: If I'm not mistaken your attachments example does not exactly work.  This will only work when sending attachments from the same computer as the web server.  The PostedFile.FileName is the client computer's fileName, and hence if you are on a server other than the client computer the file will not be found.  You would need to save the file to a temporary place first and then use that fileName to send the attachment.
Left on 3/13/2005 8:20:50 AM by Anonymous
Comments: Is therer vb code for download?
Left on 3/13/2005 7:26:03 AM by Anonymous
Comments: Very good, but how to configure SMTP service in Windows Server 2003. It seems it is not in the IIS. Thanx
Left on 3/12/2005 11:32:48 PM by Anonymous
Comments: I don't understand where the WebForm1.aspx.cs came from and if I need to make a c# document or this is premade.
Left on 3/8/2005 3:23:37 AM by Anonymous
Comments: not excellent but good for starting
Left on 3/2/2005 2:29:54 AM by Anonymous
Comments: a very excellent article. i was searching 4 this piece of information, and this is the first article i found about sending emails with attachments in asp.net
Left on 2/28/2005 6:04:37 PM by Anonymous
Comments: Now how would you do it with Frameworks 2.0 to include HTML?
No ratings available.
Left on 2/28/2005 2:13:11 AM by Anonymous
Comments: This is great, and I got the source, I have one last question… How easy would it be to incorporate a third party text/html editor in place of the body field as in your example. I want ed to see if I could give the user content formatting options, and know I can do it If I use something like freetextbox etc. to do it.
No ratings available.
Left on 2/27/2005 5:08:25 PM by Anonymous
Comments: I just reviewed my article and please excuse the mistake at the end of it where I say "1 MB (1024 bytes)", I meant "1 MB (1024 kilobytes)" :)
No ratings available.
Left on 2/27/2005 4:59:57 PM by Anonymous
Comments: Thank you for emailing me. Yes, I have the source code and I just sent it to your email address.
No ratings available.
Left on 2/27/2005 2:15:03 PM by Anonymous
Comments: This is great, do you have the source code available for download.
Left on 2/12/2005 4:27:01 AM by Anonymous
Comments: well done
Left on 2/8/2005 8:32:33 AM by Anonymous
Comments: Nice article - Jaisabari [Professional copier]
No ratings available.
Left on 2/2/2005 9:16:05 AM by Anonymous
Comments: Very very complete and nice

No ratings available.
  

 Latest Articles
  

 Latest News
  

 

Spotlight
Syndication

 


 


Digg This
 


DotNetNuke Platinum Benefactor

  
 

 Terms Of Use | Privacy Statement
 Copyright 2008 - Santry Technology Solutions, Box 172, Girard, PA 16417, (814) 774-0970