A step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.
A C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.
This tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.
Creating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.
Sending emails with ASP .NETIn 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. |
On Friday, June 10th 2005 at 09:53 AM By Andrew Pociu (View Profile) ![]() ![]() ![]() ![]() (Rated 4.5 with 31 votes) |
|||||||||||||||
|
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 ServiceIt'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. Also 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:
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:
Next, create a new instance of the MailMessage class:
Double click the button on the WebForm to get to the btnSend_Click() event. Inside paste the following code:
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:
localhost is the name of the SMTP server but you could as well enter an IP. If your SMTP server requires authentication, before using the Send() method, supply the required information as shown below:
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:
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:
However there's more about HTML email, and that's covered in the next section. Sending HTML emailsIn 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:
Here's how the message looks in Outlook 2003: ![]() As expected, the HTML tags do 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:
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 attachmentsEmail 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:
And then in the btnSend_Click() event, just before the SmtpMail.Send() method, paste the following lines:
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:
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.
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:
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. |
||||||||||||||||
Digg It!
Del.icio.us
Reddit
StumbleIt
Newsvine
Furl
BlinkList
|
||||||||||||||||
|
||||||||||||||||
Current CommentsHi
I have an ASP .NET app doing basically exactly the code you have here, except using VB iso C#, and it works great... except: my app has to have 2 attachments, which is no problem, but when the sum of the size of the 2 attachments exceeds about 105Kb, then I get a "Unspecified error", and the mail doesn't work. If I decrease the size to about 100Kb, it works??? Any ideas here?
Hi,
First I would check the limit message size in IIS.
Therefore open IIS, navigate to <b>Default SMTP Virtual Server</b>, right click and select Properties. In the Messages tab you have the limit sizes specified in KB.
By default the limit is set to 2MB.
Hi
I already checked these, and they are set to 2MB, and the session size to 10Mb.
100Kb is such an "odd" number... what can this be??
Are you sure the problem is the size, or is it multiple attachments?
Also, this error is normally caused by a missing attachments, so make sure both paths are correct.
Yes, I know the paths are correct and the 2 attachments are fine, because if I reduce the attachments' size to just below 100Kb, it works 100%. If I increase the size again to over 100Kb, I get the error. So I can simulate the error by playing with the total file size.
Strange.
I see <a href="http://www.codecomments.com/archive289-2004-12-298459.html" target="_blank">someone else</a> has the same problem, and I also saw your reply on another forum.
If you find a solution, please let others know.
Hi! How can i to send message using pickup?
thank u Mr- Andrei Pociu for ur Article which shows ur experience in ASP.NET but i would like to tell u about my self that i am dummy about ASP.NET so i think u understand that so could u plz write for us about each code where to write exactly becuz i am still confusing..........
hi,
this is working great.... but what happened is ... I can send only 1 mail at a time. next if I click on 'send' button, it's giving error at
SmtpMail.Send(MMsg);
so, I have to close the application and open it again and then run.
is there anything wrong or something I have to set..to overcome this problem???
What type of error are you getting?
Thank you for ur fast reply...I'm giving you the error as it is. sothat , you can trace the error easily.
Server Error in '/myip2' Application.
--------------------------------------------------------------------------------
The server rejected one or more recipient addresses. The server response was: 550 5.7.1 Unable to relay for vedamul@yahoo.com
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 server rejected one or more recipient addresses. The server response was: 550 5.7.1 Unable to relay for vedamul@yahoo.com
Source Error:
Line 69: mmsg.Body = TextBox6.Text
Line 70:
Line 71: SmtpMail.Send(mmsg)
Line 72: mmsg.BodyFormat = MailFormat.Html
Line 73: SmtpMail.SmtpServer = "localhost"
This is a common error and I'm afraid it's caused by the way your SMTP server is configured. Please see the following page: http://www.systemwebmail.com/faq/4.3.11.aspx
Thank you it's working... ThankQ very much..... ASP.NET is very nice
and how about mobile messaging???
how to send a message/email to a mobile does it need the permission from concern companys which are providing connection.
plzzz suggest.
with this, I created a mail client with :::: user authentication , sessions & attachments.
it's rellay a fun to program in .NET than JAVA.
Sending emails to mobile phones is being done the same way, there's nothing different since you're actually sending the email to a server, and then the client (the mobile phone) connects to the server and retrieves the message. Of course, the mobile phone should have an email client embedded; for example a Smart Phone can receive and open the emails very similarly to when you open them in Outlook on your desktop PC.
If you're planning to send SMS messages (Short Message Service), you'll have to take a different approach and sign-up with a service that can send lots of messages for a small fee. The only advantage of SMS over email is that pretty much every mobile phone supports SMS, unlike the relatively new ones that also have internet connectivity and email clients.
Another difference between the two is that it is free for you to send emails since the mobile phone user will be the one paying to read it, unlike SMS where you pay for the message and the mobile phone user receives it for free.
Hi ,
This is Satya again. My proj of sending SMS from my application was stopped in the middle...coz, I have to pay money/fee to send SMS. I jumped into another application..where I need to put a ".gif" image on the VB.net form and make it animate... I tried a lot but in vain. I belive that you can help me in this matter. [ VB.NET 2003 , placing an animating .gif image on the form when a button is pressed].
Hi, I went through your tutorial and followed the steps for testing my SMtp server by sending it from pickup folder. As soon as I hit save, it disappears and there is nothing in the Pickup folder, but I did not receive the email. I went to IIS and configred my SMTP server.
Following is the code, in ASP.Net That I wrote. I am not getting any error, but the message is not being sent. Please help.
private void SendEmail(string Password, string Email)
{
MailMessage Message = new MailMessage();
Message.To = Email;
Message.Body = "Password is " + Password;
Message.From = "DeepaVeerappan@hotmail.com";
Message.Subject = "Your password";
//SmtpMail.SmtpServer.Insert(0, "127.0.0.1");
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send(Message);
Response.Flush();
}
How do you access the dropfolder to view incoming email via iis smtp
lskdjsldj lhsd shd ldhsklds
my messages get transferred to mailroot/queue folder and never send at all. I need help.
my messages get transferred to mailroot/queue folder and never send at all.plz help.
asd
hi thanks for code i tried the same code in my asp application but the problem is the mail is sittin inside the queuee i tried capyin and pastin it in pickup folder inside ailroot folder in inettub but i tried several time plz help me to over come this probelm
i tried copyin the mail in queue to pick up folder in mail root
but it did not work
wtas the probelm and wats the solution for this problem ?
<a href="http://airtraveltips.blogspot.com>
rgtreth
i hav to send wallpaper to a mobile i hav a credits 4 that ..and i m succes in sending sms to a mobile but wht about wallpaper ? it is same as sms...i m bulding my application in asp.net 2003 using vb.net code...thnks in advance
Plz tell me how to add multiple attachments.
i have more than one file control in my page.If user attachs more than one file,how to send the attached file to the id.(To id is same.)
thanks in advance
regds,
Ramya
Hi, I am trying to send an email text comment and subject to the mobile phone using send( )method of SmtpMail object but unable to get the message.
Is there any specific code for sending the text or the same as we do for sending email on internet? I am using ASP.Net C#
Please help.
Thanks,
Naveen
Hi Im shereef i'm working with a project Web Portal Using Assemblies(Simply a mail server) can u help how to receive mails to my application? i'm using SQL Server 2000 as my back end
The article is cool!
hi
i realy thankful to u and all to help email programming..
Hi am Suji
I tried the above code. Its working successfully.
Thanks to author.
But i need to send sms to mobile.
Hi girish u told that i already know how to send sms.
please provide the code.. Its little urgent... Please help meee...
Thanks in advance.
Hai Andrei Pociu,
I worked with this code, there is no error but the mail is not reaching to particular id. whr to do. Wht mistake is that??
hi any one can help me how to receive emails and stored in to my application just like a ms outlook express
Hi sir..
Here the following exception is occur in send mail.Plz reply me.. what mistake i do that?..
Unable to deliver this message because the follow error was encountered: "Error is processing file in pickup directory.".
by GunaSunadari.
Hi,
This article information is more usefulful to visitors great job
<a href="http://www.infrascape.com/">Network Monitoring</a>
how to set the cursor focus on content textbox of outlook express 6 using C#ASP.net 2003 and while initializing outlook express 6 the cursor should focus on the content textbox?
plz send the code
a62136061@yahoo.com.hk
Related Tutorials
Related Source Code
ASP.NET Job Search