Click here to Skip to main content
Click here to Skip to main content

Sending Mail Using C# via SMTP

By , 19 Dec 2001
 

Introduction

This project shows how to send mail via an SMTP server using C#.

How to Send Mail via SMTP

Based on RFC 821 about Simple Mail Transfer Protocol, it's very easy to send mail via SMTP. Here's the handshaking for sending mail:

 Receiver: 220 server.com Simple Mail Transfer Service Ready
 Sender  : HELO server.com
 Receiver: 250 server.com
 Sender  : MAIL FROM: <agusk@host.com>
 Receiver: 250 OK
 Sender  : RCPT TO: <myhoney@host.com>
 Receiver: 250 OK
 Sender  : DATA
 Receiver: 354 Start mail input: end with <CRLF>.<CRLF>
 Sender  : all data like From, To, Subject, Body etc. 
           ended with <CRLF>.<CRLF>
 Receiver: 250 OK
 Sender  : QUIT
 Receiver: 250 server.com closing transmission channel

Building the Application Using C#

Here's a model of the GUI:

add these code lines for when the use clicks the Send button:

 private void SendBtn_Click(object sender, System.EventArgs e)
{
    // change cursor into wait cursor
    Cursor cr = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;

    // create server SMTP with port 25
    TcpClient SmtpServ = new TcpClient(ServSMTP.Text,25);
    string Data;
    byte[] szData;
    string CRLF = "\r\n";
    LogList.Items.Clear();            

    try
    {
        // initialization
        NetworkStream NetStrm = SmtpServ.GetStream();
        StreamReader  RdStrm= new StreamReader(SmtpServ.GetStream());
        LogList.Items.Add(RdStrm.ReadLine());
            
        // say hello to server and send response into log report
        Data = "HELLO server " + CRLF;                
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        LogList.Items.Add(RdStrm.ReadLine());
        // send sender data
        Data = "MAIL FROM: " + "<" + sFrom.Text + ">" + CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        LogList.Items.Add(RdStrm.ReadLine());

        // send receiver data
        Data = "RCPT TO: " + "<" + sTo.Text + ">" + CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        LogList.Items.Add(RdStrm.ReadLine());

        // send DATA
        Data = "DATA " + CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        LogList.Items.Add(RdStrm.ReadLine());                

        // send content data
        Data = "SUBJECT: " + sSubject.Text + CRLF +
           sMessage.Text + CRLF + "." + CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        LogList.Items.Add(RdStrm.ReadLine());                

        // quit from server SMTP
        Data = "QUIT " + CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        LogList.Items.Add(RdStrm.ReadLine());                

        // close connection
        NetStrm.Close();
        RdStrm.Close();
        LogList.Items.Add("Close connection");
        LogList.Items.Add("Send mail successly..");

        // back to normal cursor
        Cursor.Current = cr;

    }
    catch(InvalidOperationException err)
    {
        LogList.Items.Add("Error: "+ err.ToString());
    }
}

Reference

  • Document RFC 821 and MSDN for .NET Development

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Agus Kurniawan
Founder PE College
Indonesia Indonesia
Member
He gradueted from Sepuluh Nopember Institute of Technology (ITS) in Department of Electrical Engineering, Indonesia. His programming interest is VC++, C#, VB, VB.NET, .NET, VBScript, Delphi, C++ Builder, Assembly,and ASP/ASP.NET. He's founder for PE College(www.pecollege.net), free video tutorial about programming, infrastructure, and computer science. He's currently based in Depok, Indonesia. His blog is http://geeks.netindonesia.net/blogs/agus and http://blog.aguskurniawan.net

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionpasswordmemberAETCoder19 Jun '11 - 10:07 
There is no password?
GeneralMy vote of 3memberudhaya2code31 Jul '10 - 0:28 
gf
Generalmail in C++membermisa_qn23 Sep '08 - 21:47 
hi evey body
i want send file in c++ but i don't know code.if any you have code it.please post in this site and mail for me.mail to misa_qn@yahoo.com.vn
thank you
GeneralRe: mail in C++memberurapola10 Nov '08 - 17:12 
www.example-code.com/vcpp/FileAttachment.asp
Generalsending mail using C#membersobhaniir9 Aug '08 - 0:25 
hi
i want to send mail using C# but i cant
this is my code:
 
MailAddress from = new MailAddress("negin_sarkhosh22@yahoo.com", ":: safir187.com ::");
MailAddress to = new MailAddress("sara_sarakhanom22@yahoo.com", ":: tnz187 ::");
MailMessage message = new MailMessage(from, to);
 
message.Subject = "Safir187.com is updated!";
message.IsBodyHtml = true;
message.Priority = MailPriority.High;
message.Body = "wedqwe";
 
SmtpClient client = new SmtpClient("localhost");
client.Send(message);
please tell me my mistake
thanks
GeneralRe: sending mail using C#memberPedes21 Aug '08 - 1:23 
>> SmtpClient client = new SmtpClient("localhost");
 
Do you have a SMTP service running on your machine? I guess not. Smile | :)
 
You can easily google simple smtp server applications that don't require installation.
GeneralHelp , pleasememberprogramet_nje15 Apr '08 - 6:38 
I need to send a message between two mails in yahoo.com
 
But I don't konw what can I write to textBox of SMTP
 
Help ,Please !
 
programet_nje@hotmail.com
GeneralHelp , pleasememberprogramet_nje15 Apr '08 - 6:37 
I need to send a message between two mails in yahoo.com
 
But I don't konw what can I write to textBox of SMTP
 
Help ,Please !
Questions this sending mail trhough SMTP dependent on any mail cilent??membertika122 Apr '07 - 23:03 
hi,
 
can anyone temme abt the code written in c # for sending mail throgh SMTP s dependent on any mail client????
 
s ter any code for doin the same in C++????
 
kidly help.
 
thanks.
Generalhaving problemmembermohsen.karami5 Nov '06 - 17:48 
hello
ia have problem with this code .
when i want to run this program it throws an unhandeled exception in this line
 
TcpClient SmtpServ = new TcpClient(ServSMTP.Text.Trim(), 25);
it seems that it couldnt make tcp client
please guide me
 
mohsen
QuestionAuthentication problemmemberDannyAdler23 Mar '06 - 14:54 
Hi everyone,
 
I've found this code that can send SMTP commands via sockets (25).
The problem is when I send the command: "rcpt to:whatever@yahoo.com", I get a server response: "503 This mail server requires authentication ...".
Is there a way to create this authentication, to make this happen?
 
Thanks in advance,
Danny
GeneralAttachementsmemberjacek_pl14 Dec '05 - 2:57 
I want to attach file to an e-mail.
How can I do it?
GeneralRe: AttachementsmemberIsta26 Dec '05 - 16:39 
View the RFC 821 specs. It will tell you how to organize it.
 
I'm not an expert yet, but I play one at work. Yeah and here too.
GeneralError in Codememberrob_johnson_200316 Nov '05 - 14:37 
In the code there is line:
 
Data = "HELLO server " + CRLF;
 
1.
It would be nice to point that instead of "server" there should be real server. E.g. it can be 127.0.0.1
 
2.
HELLO should be HELO
 
3.
It is critical that after server name there will be NO SPACES before CRLF
 
The example of correct line is:
 
Data = "HELO 127.0.0.1" + CRLF;
 

-- modified at 20:42 Wednesday 16th November, 2005
QuestionReady for c++?membercemaaiem30 Oct '05 - 4:46 
the code when uusing Send button its reusablwe for vc++, i have to send a mail in a console application to inform people who were late at the morning.
GeneralSend Mailmemberfredo_lefran10 Aug '05 - 6:23 
Hi,
 
I used this sample but the any message isnot arrive.
 
I don't know why.
 
Someone know how to attach a file?
 
I would like to knwo if i can define user in the server SMTP?
 
Tnak you for your help.
GeneralOpenSMTP.NETmemberUnruled Boy5 May '05 - 4:49 
OpenSMTP.NET http://sourceforge.net/projects/opensmtp-net is recommended.
 
Regards,
unruledboy@hotmail.com
GeneralRe: OpenSMTP.NETsussAnonymous14 Jul '05 - 6:59 
Too bad the project doesn't use BSD licensing, it's worthless for commercial work as it stands.
QuestionWindows 98?memberbefore12324 Sep '04 - 0:39 
Wheather it is working in Windows 98
 
123
GeneralSMTP servermemberjmkuznitzki4 Aug '04 - 2:43 
Certainly a stupid question but .....
 
What do we specify in the area of "SMTP server" ?
I suppose a SMTP server, but is a Standard SMTP server running on my system (Windows XP) ? How can I see that ?
 
What is a SMTP server ?
I believed that we have to send a text respecting the SMTP protocol to the port 25.
 
OMG | :OMG:
 
JMK
GeneralSpecifying &quot;from&quot; field while sending the mail!!!!sussAnonymous13 May '04 - 0:32 
hi all,
I have an application sending mails but i am not able to specify my name in the field.the problem is that the recepient sees my whole e-id instead of my name.
 
can there be a property which i can use to resolve this problem.
 
plz help!!!!
AnswerRe: SMTP AUTH Login ?memberLiang Yitao25 Mar '04 - 6:05 
Smile | :) The System.Web.Mail.SmtpMail does not support ESMTP.
If you want to auth login, you need to do so by using
the TCP client. And remember to convert the user name
and password to BASE64 code. Using the code below:
 
Convert.ToBase64String(Encoder.GetBytes(username))
 
can do the task.
GeneralRe: SMTP AUTH Login ?memberpareshgheewala23 Apr '04 - 8:06 
how do you provide login information to TCP client
like how do u pass [login] and [password] to
ESMTP..
how do we write ESMTP program.
 
thanks..
GeneralRe: SMTP AUTH Login ?memberweb-mouse3 May '04 - 20:16 

Havo everybody made ESMTP Mailer? Also an SMTP Mail Service with Auth??
AnswerRe: SMTP AUTH Login ?membermirsaman25 Oct '11 - 7:46 
Hi,
actually I've learned that the message sequence for ESMTP is like below:
< TCP Connection to server >
S: 220 Welcome to (my smtp server).
C: EHLO (my smtp server).
S: List of supported ways
 
{
for example test smtp.gmail.com on port 587 in telnet.
result is:
 
220 mx.google.com ESMTP j9sm28589707bkd.2
EHLO *(you should send it again when you negotiate an ssl/tls connection)
250-mx.google.com at your service, [46.164.103.3]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250 ENHANCEDSTATUSCODES
 
}
 
C: STARTTLS
S: 220 2.0.0 Ready to start TLS
 
< Here a ssl/tls connection should be negotiated. >
 
After negotiation you can do as normal smtp, but the data you send will be encrypted:
 
C: EHLO
S: Introduce yourself
C: AUTH PLAN ABCDEFG== *(Here you should send your password in base64 encoding)
S: 235 Authentication succeed.
C: Mail FROM: MyMail@MyServer.com
S: 250 Sender OK
and so on ...
 
But I have problem in establishing a secure connection to gmail esmpt.
I do not know how to exchange a secret key between my program and gmail!
So if you know the answer (in C# or java) please help me.
 
Hope it will be useful.
 

and after here you can continue with smtp protocol (mail from, rcpt to:, . . . )
GeneralBody messagememberfelipedrumond25 Oct '03 - 9:55 
I'm having a problem:
 
I send the mail, and the server sends to my email the message:
 
Hi. This is the qmail-send program at hm101.locaweb.com.br.
I'm afraid I wasn't able to deliver your message to the following addresses.
This is a permanent error; I've given up. Sorry it didn't work out.
 
:
vdeliver: Message is corrupted. It does not possess body

 
Felipe Drumond - Brazil
GeneralSMTP using C#membersanalsasiraj20 Aug '03 - 1:47 
i would like to know how to run smtp using c#, i compiled it successfully whenever i try to run it using IIS, default server says hello(220) but when i give command (HELO, EHLO) it doesn't accepts and connection closes saying invalid address, wrong command, mail send successfully and connection close. if configuration of IIS is wrong how do i correctly set it,and how do i recieve the mail send through this SMTP mail server.
i will be very thankfull for any valuable information.
GeneralTwo questionmemberMazdak7 May '03 - 6:24 
1.There is no username and password here.So I can send from any email address?
 
2.How can I attach file to my email?
 
Thanks
 
<html>Mazy
 
No sig. available now.
</html>

GeneralHtml Formatmemberaudepoupette28 Apr '03 - 4:44 
Hello,
 
I need to send HTML formatted email,
How can I do with this code? Confused | :confused:
 

 
aude
GeneralUnhandled exception errormemberjulianarevalo21 Feb '03 - 19:21 
hi.
First of all, you wrote a very nice article. Specially very simple for us, beginners.
 
I cannot run the application, because I get a ‘Microsoft development error’:
 
“An unhandled exception of type 'System.Security.SecurityException' occurred in mscorlib.dll
Additional information: Request for the permission of type System.Net.SocketPermission, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed.”
 
I am using Windows XP, which is completely up-to-date.
BTW, I also couldn’t run the EXE that came with the source code…
 
Any idea???????? Confused | :confused:
 
Thanks a lot!
 
Julian
 

GeneralRe: Unhandled exception errormembercscoder31 May '03 - 6:19 
Try this
Control Panel
Net Framework Configuration
Runtime Restrictions (something like that, sorry i work on a german system)
User
Codegroups
All_Code -> right click for propertys
on the 3th Tab ensure you have enabled full thrust to AllCode
 
i hope it helps
 
HarrySmile | :)
QuestionHow to format message as HTML ?susshandsmart17 Dec '02 - 9:14 
Sending as ASCII is nice, but i really need an option for sending HTML formatted email.
 
Anyone ?!
AnswerRe: How to format message as HTML ?memberEd K17 Dec '02 - 9:20 
From below:
 
// create the mail message
MailMessage mail = new MailMessage();
 
// populate the message
mail.From = argumentEmailFrom;
mail.To = toAddress;
mail.Subject = argumentEmailSubject;
mail.BodyFormat = MailFormat.Html;
mail.Body = "<html><body>" + yourMessageHere + "</body></html>";
 

// send it
SmtpMail.SmtpServer = "your.smtpserver.com"
SmtpMail.Send(mail);

 
ed
 
Every time I walk into a singles bar I can hear Mom's wise words: "Don't pick that up, you don't know where it's been!"
GeneralRe: How to format message as HTML ?memberrarerose9 Mar '06 - 13:54 
Note: I pasted the data in message body
 
I changed to mutiline property to yes
Still My message body is coming in a single line. Frown | :(
QuestionSMTP AUTH Login ?sussAnonymous29 Oct '02 - 22:05 
How to do smtp auth login in c #
GeneralGetting POP3 Mail AttachmentsmemberAnonymous29 Aug '02 - 3:02 
I really appreciate the article at http://www.codeproject.com/csharp/POPApp.asp, but can anyone tell me how to read/get/decode attachments such as word documents / excel spreadsheets / image files from a POP3 server mail account ?
 
Assistance will be appreciated as time is of the essence!
 
Thanks!
Generalusing System.Web.Mail;memberPhilip Fitzsimons15 Aug '02 - 3:42 
why do you not use the mail class? WTF | :WTF:
 
using System.Web.Mail;
.
.
.
 
// create the mail message
MailMessage mail = new MailMessage();
 
// populate the message
mail.From = argumentEmailFrom;
mail.To = toAddress;
mail.Subject = argumentEmailSubject;
mail.BodyFormat = MailFormat.Html;
mail.Body = htmlMessage;
 

// send it
SmtpMail.SmtpServer = "your.smtpserver.com"
SmtpMail.Send(mail);
 



"When the only tool you have is a hammer, a sore thumb you will have."

GeneralRe: using System.Web.Mail;sussAnonymous23 Aug '02 - 6:13 
I know how to SEND Mail, but I am trying to get messages from the SMTP Server.
 
I want to use the example at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnproasp2/html/usingcdofornts.asp in C-Sharp though.
 
Thanks!
 
OMG | :OMG:
GeneralRe: using System.Web.Mail;membersmallguy7819 Jun '03 - 13:14 
you don't 'get' messages from an smtp server you muppet. that's what pop3 is for
GeneralRe: using System.Web.Mail;memberTim_Wilde12 Sep '05 - 7:41 
OK, I just fell off my chair laughing! Laugh | :laugh: Poke tongue | ;-P
 
Tim W.
---------------------- Done ----------------------
 
Build: x succeeded, 0 failed, 0 skipped, 1 warm-fuzzy feeling
GeneralRe: using System.Web.Mail;memberBarista Bill17 Nov '04 - 10:33 
You can't use System.Web.Mail on 2003 servers.
 
See the KB article here[^]
GeneralRe: using System.Web.Mail;memberPhilip Fitzsimons17 Nov '04 - 23:49 
er my post was dated 9:42 15 Aug '02
there was no 2003 server then Smile | :)
 



"When the only tool you have is a hammer, a sore thumb you will have."

GeneralRe: using System.Web.Mail;sussAnonymous4 Mar '05 - 11:55 
The article you link to explicitly tells you to use System.Web.Mail on 2003 servers!
GeneralGet MAIL from SMTP Using C#sussAnonymous14 Aug '02 - 9:57 
Hi,
 
Is there anything out there in C# of the following:
<%
Set objSession = Server.CreateObject("CDONTS.Session")
objSession.LogonSMTP "Service", "service@mysmtp.com"
Set objFolder = objSession.inbox
set objMessages = objFolder.messages
Response.Write "Number of Messages: " & objMessages.count
%>
 
I am going from VBScript to C# and cannot find anything out there with a sample Frown | :( br /> 
Any assistance will be greatly appreciated!
GeneralRe: Get MAIL from SMTP Using C#memberMadShad200417 Jan '05 - 20:57 
It is sometimes hard to believe that some people out there actually think they could ever possibly write a program on thier own? I mean, why do you think that you've had to configure smtp AND pop in every single email client you've ever owned....for a laugh?
GeneralSMTPsussAnonymous7 Aug '02 - 20:55 
How to send User Name and Password to SMTP Server???
GeneralErrorsussAnonymous11 Jul '02 - 6:20 
It has something wrong
When I type my SMTP server and I send another message it only sends messages to E-mails on this server only
I mean when I send E-mail form My e-mail to another different E-mail it tells me in the log screen
Relay Access DeniedConfused | :confused:
GeneralRe: ErrormemberDoug Brower26 Sep '02 - 2:35 
Take a look at the relay restrictions set for your SMTP server. If you're using IIS, open the IIS control panel applet, right-click on the SMTP server, and select properties. Click the Access tab, then click the Relay... button. On my system, I have the "All except the list below" radio button selected, the list is empty, and the "Allow all computers which successfully authenticate..." checkbox is unchecked.
 
HTH!Smile | :)
GeneralAttachmentmemberAnonymous4 Jul '02 - 11:57 
Nice article!
But how I can send e-mail with attachments?
GeneralRe: AttachmentmemberAnonymous4 Jul '02 - 21:12 
Sending mail with attachment using System.Web
http://www.c-sharpcorner.com/Internet/MailingAppMG.asp

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 20 Dec 2001
Article Copyright 2001 by Agus Kurniawan
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid