The implementation code for sending mail using SMTP in asp.NET

  • 2020-05-12 02:28:00
  • OfStack

Core code:
 
public class Mail 
{ 
#region  Mail parameters  
static public string accountName = System.Configuration.ConfigurationManager.AppSettings["SmtpAccountName"]; 
static public string password = System.Configuration.ConfigurationManager.AppSettings["SmtpAccountPW"]; 
static public string smtpServer = System.Configuration.ConfigurationManager.AppSettings["SmtpServer"]; 
static public int smtpPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["SmtpPort"]); 
#endregion 

/// <summary> 
///  Mail sending method 1 
/// </summary> 
/// <param name="sendTo"></param> 
/// <param name="subject"></param> 
/// <param name="body"></param> 
static public void SendMail(string sendTo, string subject, string body) 
{ 
//.net smtp 
System.Web.Mail.MailMessage mailmsg = new System.Web.Mail.MailMessage(); 
mailmsg.To = sendTo; 
//mailmsg.Cc = cc; 
mailmsg.Subject = subject; 
mailmsg.Body = body; 
mailmsg.BodyFormat = MailFormat.Html; 


//sender here 
mailmsg.From = Mail.accountName; 
// certify needed 
mailmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");//1 is to certify 
//the user id 
mailmsg.Fields.Add( 
"http://schemas.microsoft.com/cdo/configuration/sendusername", 
Mail.accountName); 
//the password 
mailmsg.Fields.Add( 
"http://schemas.microsoft.com/cdo/configuration/sendpassword", 
Mail.password); 

System.Web.Mail.SmtpMail.SmtpServer = Mail.smtpServer; 

System.Web.Mail.SmtpMail.Send(mailmsg); 

} 
/// <summary> 
///  Mail sending method 2 
/// </summary> 
/// <param name="sendTo"></param> 
/// <param name="subject"></param> 
/// <param name="body"></param> 
static public void SendMail2(string sendTo, string subject, string body) 
{ 
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(accountName, sendTo, subject, body); 
msg.From = new System.Net.Mail.MailAddress(accountName, "Mail"); 
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(smtpServer); 
msg.IsBodyHtml = true; 
client.Credentials = new System.Net.NetworkCredential(accountName, password); 
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; 

client.Send(msg); 
} 
} 


Abstract
This article briefly introduces the process of SMTP protocol (RFC2554) to send mail, and discusses three different schemes, problems and solutions to send mail by using SMTP in.NET.
directory
? NET SMTP class
? Send mail using the CDO component
? Write the email sending program using Socket
conclusion
Introduction to the
This article describes the use of NET's SMTP class library and two other ways of using CDO(Collaboration Data Objects) and Socket to realize the mail sending function.
NET SMTP class
First, let's introduce the SMTP class that comes with the NET library. Under the System.Web.Mail namespace in.NET, there is a class that USES the SMTP protocol to send mail: SmtpMail, which already meets the most common need to send mail. This class has only one public function of its own --Send() and one public property -- SmtpServer, as shown below:
You must specify the name (or IP address) of the server that sent the message via the SmtpServer property before calling
The Send() function sends the message.
The code example is as follows:
(in C & # 35)
 
using System.Web.Mail; 
public void sendMail() 
{ 
try 
{ 
System.Web.Mail.MailMessage myMail=new MailMessage(); 
myMail.From = "myaccount@test.com"; 
myMail.To = "myaccount@test.com"; 
myMail.Subject = "MailTest"; 
myMail.Priority = MailPriority.Low; 
myMail.BodyFormat = MailFormat.Text; 
myMail.Body = "Test"; 
SmtpMail.SmtpServer="smarthost"; //your smtp server here 
SmtpMail.Send(myMail); 
} 
catch(Exception e) 
{ 
throw e; 
} 
} 

You can set properties related to the message, such as priority, attachments, and so on, in the MailMessage object as a parameter to the Send function. In addition to taking the MailMessage object as an argument (such as the code above), the Send function can also be called simply with the four main messages of the message (from, to, subject, messageText) as a string argument.
Send mail using the CDO component
CDO, short for Collaboration Data Objects, is a high-level collection of COM objects that has evolved over several versions and is now used in Windows2000 and Exchange2000 as CDO2.0 (cdosys.dll and cdoex.dll, respectively). CDOSYS is built on top of the SMTP protocol and NNTP protocol, and is installed as a component of Windows2000 Server, which you can find in the system32 subdirectory of the system directory (c:\winnt or c:\windows) (cdosys.dll).
The CDO component has more functionality than the SmtpMail object described earlier, and provides some functionality that the SmtpMail class does not, such as sending mail through the SMTP server that requires authentication.
The following code shows how to use the CDO component to send mail through the SMTP server that requires authentication:
(in C & # 35)
 
public void CDOsendMail() 
{ 
try 
{ 
CDO.Message oMsg = new CDO.Message(); 

oMsg.From = "myaccount@test.com"; 
oMsg.To = "myaccount@test.com"; 
oMsg.Subject = "MailTest"; 

oMsg.HTMLBody = "<html><body>Test</body></html>"; 
CDO.IConfiguration iConfg = oMsg.Configuration; 
ADODB.Fields oFields = iConfg.Fields; 

oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value=2; 
oFields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value="myaccount@test.com"; //sender mail oFields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value="myaccount@test.com"; //email account oFields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value="username"; oFields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value="password"; oFields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value=1; 
//value=0  On behalf of Anonymous Validation (no validation required)  
//value=1  On behalf of Basic Verification method (use basic (clear-text) authentication. 
//The configuration sendusername/sendpassword or postusername/postpassword fields are used to specify credentials. )  
//Value=2  On behalf of NTLM Verification method ( Secure Password Authentication in Microsoft Outlook Express )  
oFields["http://schemas.microsoft.com/cdo/configuration/languagecode"].Value=0x0804; 
oFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value="smtp.21cn.com"; 
oFields.Update(); 
oMsg.BodyPart.Charset="gb2312"; 
oMsg.HTMLBodyPart.Charset="gb2312"; 
oMsg.Send(); 
oMsg = null; 
} 
catch (Exception e) 
{ 
throw e; 
} 
} 

Note: if you wish to continue using cdosys.dll, you must uninstall cdoex.dll via regsrv32.exe, because cdoex.dll of Exchange2000 updates cdosys.dll of Windows2000, cdosys.dll.
Write the email sending program using Socket
Of course, if you feel that SmtpMail doesn't meet your needs, and CDO isn't straightforward enough, you'll have to do it yourself. In fact, if you are familiar with Socket programming, it is not difficult to write a mail sending program yourself. Here is an example.
First, let's briefly explain how the SMTP server with authentication can use the AUTH primitive for authentication. For a detailed definition, please refer to RFC2554.
The details are as follows:
1) first, you need to use EHLO instead of the original HELO.
2) after the success of EHLO, the client needs to send the AUTH primitive to negotiate with the server about the way the user name and password should be passed during authentication.
3) if the negotiation is successful, the server will return a result code starting with 3, which can then pass the user name and password to the server.
4) finally, if the verification is successful, you can start sending the letter.
Here is a practical example of a client sending a message from the WinXP Command window via the command "telnet smtp.263.NET 25=" to the smtp server of 263:
220 Welcome to coremail System(With Anti-Spam) 2.1
EHLO 263.NET
250-192.168.30.29
250-PIPELINING
250-SIZE 10240000
250-ETRN
250-AUTH LOGIN
250 8BITMIME
AUTH LOGIN
334 VXNlcm5hbWU6
bXlhY2NvdW50
334 UGFzc3dvcmQ6
bXlwYXNzd29yZA==
235 Authentication successful
MAIL FROM:myaccount@263.NET
250 Ok
RCPT TO:myaccount@263.NET
250 Ok
Data
354 End data with < CR > < LF > . < CR > < LF >
This is a testing email.
haha.
.
250 Ok: queued as AC5291D6406C4
QUIT
221 Bye
The above is the whole process of sending the letter. The main ones related to authentication are lines 9 through 104:
AUTH LOGIN '; '; '; '; Client input
334 VXNlcm5hbWU6 '; '; '; '; The server prompts "Username:="
bXlhY2NvdW50 '; '; '; '; The client enters the Base64 code of "myaccount="
334 UGFzc3dvcmQ6 '; '; '; '; The server prompts "Password:="
bXlwYXNzd29yZA = = '; '; '; '; The client enters the code Base64 for "mypassword="
235 Authentication successful '; '; '; '; The server side passes validation
As you can see from the analysis above, both the server and the client pass plain text encoded by the standard Base64 directly through Socket during this authentication process. This process can be conveniently used. Implementation, or directly added to the original source code.
In addition, some ESMTP servers do not support AUTH LOGIN authentication, only AUTH CRAM-MD5 authentication. But the only difference between the two is how the text is encoded.
Can realize the function of the source code in SourceForge. NET http: / / sourceforge NET/projects/opensmtp - found on net/download. A simple pseudo-code is given below:
 
public void SendMail(MailMessage msg) 
{ 
NetworkStream nwstream = GetConnection(); 
WriteToStream(ref nwstream, "EHLO " + smtpHost + "\r\n"); 
string welcomeMsg = ReadFromStream(ref nwstream); 
// implement HELO command if EHLO is unrecognized. 
if (IsUnknownCommand(welcomeMsg)) 
{ 
WriteToStream(ref nwstream, "HELO " + smtpHost + "\r\n"); 
} 
CheckForError(welcomeMsg, ReplyConstants.OK); 
// Authentication is used if the u/p are supplied 
AuthLogin(ref nwstream); 
WriteToStream(ref nwstream, "MAIL FROM: <" + msg.From.Address + ">\r\n"); 
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.OK); 
SendRecipientList(ref nwstream, msg.To); 
SendRecipientList(ref nwstream, msg.CC); 
SendRecipientList(ref nwstream, msg.BCC); 
WriteToStream(ref nwstream, "DATA\r\n"); 
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.START_INPUT); 
if (msg.ReplyTo.Name != null && msg.ReplyTo.Name.Length != 0) 
{ WriteToStream(ref nwstream, "Reply-To: \"" + msg.ReplyTo.Name + "\" <" + 
msg.ReplyTo.Address + ">\r\n"); } 
else 
{ WriteToStream(ref nwstream, "Reply-To: <" + msg.ReplyTo.Address + ">\r\n"); } 

if (msg.From.Name != null && msg.From.Name.Length != 0) 
{ WriteToStream(ref nwstream, "From: \"" + msg.From.Name + "\" <" + 
msg.From.Address + ">\r\n"); } 
else 
{ WriteToStream(ref nwstream, "From: <" + msg.From.Address + ">\r\n"); } 

WriteToStream(ref nwstream, "To: " + CreateAddressList(msg.To) + "\r\n"); 

if (msg.CC.Count != 0) 
{ WriteToStream(ref nwstream, "CC: " + CreateAddressList(msg.CC) + "\r\n"); } 
WriteToStream(ref nwstream, "Subject: " + msg.Subject + "\r\n"); 
if (msg.Priority != null) 
{ WriteToStream(ref nwstream, "X-Priority: " + msg.Priority + "\r\n"); } 
if (msg.Headers.Count > 0) 
{ 
SendHeaders(ref nwstream, msg); 
} 

if (msg.Attachments.Count > 0 || msg.HtmlBody != null) 
{ 
SendMessageBody(ref nwstream, msg); 
} 
else 
{ 
WriteToStream(ref nwstream, msg.Body + "\r\n"); 
} 

WriteToStream(ref nwstream, "\r\n.\r\n"); 
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.OK); 

WriteToStream(ref nwstream, "QUIT\r\n"); 
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.QUIT); 
CloseConnection(); 
} 
private bool AuthLogin(ref NetworkStream nwstream) 
{ 
if (username != null && username.Length > 0 && password != null && password.Length > 0) 
{ 
WriteToStream(ref nwstream, "AUTH LOGIN\r\n"); 
if (AuthImplemented(ReadFromStream(ref nwstream))) 
{ 
WriteToStream(ref nwstream, Convert.ToBase64String( 
Encoding.ASCII.GetBytes(this.username.ToCharArray())) + "\r\n"); 
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.SERVER_CHALLENGE); 
WriteToStream(ref nwstream, Convert.ToBase64String(Encoding.ASCII.GetBytes( 
this.password.ToCharArray())) + "\r\n"); 
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.AUTH_SUCCESSFUL); 
return true; 
} 
} 
return false; 
} 

conclusion
Were introduced in this paper. NET in three different ways to use SMTP agreement send mail, among them 1 (using SmtpMail class) scheme can meet the demand of the function of the most basic email, and the second (use CDO components) and third (using Socket himself wrote SMTP class) programme provides more freedom and full customization methods, such as they can implement scheme cannot do 1 through certification SMTP email server functionality.

Related articles: