The Send method does all the work in our class. Once you've set the subject, body, from and recipient data members, you simply call the Send method and the SMTP communication is initiated. I won't explain the details of the SMTP protocol here, but rather encourage the user to step through the code, read the SMTP RFC and read my previous articles on SMTP.
public void Send()
{
string message;
string response;
Connect( server, 25);
response = Response();
if (response.Substring( 0, 3) != "220")
{
throw new SmtpException( response);
};
message = "HELO me\r\n";
Write( message);
response = Response();
if (response.Substring( 0, 3) != "250")
{
throw new SmtpException( response);
}
message = "MAIL FROM:<" + from + ">\r\n";
Write( message);
response = Response();
if (response.Substring( 0, 3) != "250")
{
throw new SmtpException( response);
}
foreach ( string address in to )
{
try
{
message = "RCPT TO:<" + address
+ ">\r\n";
Write( message);
response = Response();
if (response.Substring( 0, 3) != "250")
{
throw new SmtpException(
response);
}
}
catch( SmtpException e)
{
System.Console.WriteLine("{ 0}",
e.What());
}
}
foreach ( string address in cc )
{
try
{
message = "RCPT TO:<" + address
+ ">\r\n";
Write( message);
response = Response();
if (response.Substring( 0, 3) != "250")
{
throw new SmtpException(
response);
}
}
catch( SmtpException e)
{
System.Console.WriteLine("{ 0}",
e.What());
}
}
foreach ( string address in bcc )
{
try
{
message = "RCPT TO:<" + address
+ ">\r\n";
Write( message);
response = Response();
if (response.Substring( 0, 3) != "250")
{
throw new SmtpException(
response);
}
}
catch( SmtpException e)
{
System.Console.WriteLine("{ 0}",
e.What());
}
}
message = "DATA\r\n";
Write( message);
response = Response();
if (response.Substring( 0, 3) != "354")
{
throw new SmtpException( response);
}
message = "Subject: " + subject + "\r\n";
foreach ( string address in to )
{
message += "To: " + address + "\r\n";
}
foreach ( string address in cc )
{
message += "Cc: " + address + "\r\n";
}
message += "From: " + from + "\r\n";
if (bodyHtml.Length > 0)
{
message += "MIME-Version: 1.0\r\n"
+" Content-Type: text/ html;\r\n"
+" charset=\" iso-8859-1\"\r\n";
message += "\r\n" + bodyHtml;
}
else
{
message += "\r\n" + bodyText;
};
message += "\r\n.\r\n";
Write( message);
response = Response();
if (response.Substring( 0, 3) != "250")
{
throw new SmtpException( response);
}
message = "QUIT\r\n";
Write( message);
response = Response();
if (response.IndexOf(" 221") == -1)
{
throw new SmtpException( response);
}
}
The Send method uses three methods, the Connect
, Write
and Response
methods.
The Connect
method is inherited from the TcpClient
class
and establishes a TCP connection between our client and a TCP server.
Comments