Implementing code for sending mail using SMTP in asp.net-practical tips

Source: Internet
Author: User
Tags auth base64 network function email account mailmessage smtpclient microsoft outlook
Core code:
 code as follows:

public class Mail
{
#region Message 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>
How to send a message
</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 Send method Two
</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);
}
}


Summary
This article briefly describes the SMTP protocol (RFC2554) process of sending mail, and discusses the three different scenarios, the problems they may encounter, and their solutions to using SMTP to send mail in. NET.
Directory
? . NET SMTP class
? Sending mail using CDO components
? Compose a mail dispatcher using the socket
Summarize
Brief introduction
Mail delivery is often a lot. NET application, especially in the application with network function, one of the indispensable modules, this article introduces the use. NET SMTP class library and two other ways to send mail via CDO (collaboration Data Objects) and sockets.
. NET SMTP class
First, let's introduce. NET class library, with its own SMTP class. Under the System.Web.Mail namespace in. NET, there is a class that specifically uses the SMTP protocol to send messages: SmtpMail, which meets the most common requirements for sending mail. This class has only one own public function--send () and a public property-smtpserver, as shown in the following figure:
You must specify the name (or IP address) of the server that sent the message by using the SmtpServer property, and then call the
The Send () function to send the message.
The code example is as follows:
(in C #)
 code as follows:

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 the message's related properties, such as precedence, attachments, and so on, in the parameter MailMessage object of the Send function. In addition to the MailMessage object as a parameter (such as the preceding code), the Send function can also be simply invoked directly as a string parameter with 4 main messages (From,to,subject,messagetext).
Sending mail using CDO components
CDO is the acronym for Collaboration Data objects, a collection of high-level COM objects, and has undergone several versions of evolution, The CDO2.0 versions are now used in both Windows2000 and Exchange2000 (Cdosys.dll and Cdoex.dll, respectively). CDOSYS is built on top of the SMTP protocol and NNTP protocol, and as a component of Windows2000 server is installed, you can find it in the System32 subdirectory of the system directory (such as C:\Winnt or C:\Windows) (Cdosys.dll )。
The CDO component is richer than the SmtpMail object described earlier and provides functionality not provided by the SmtpMail classes, such as sending mail through an SMTP server that requires authentication.
The following code shows how to use the CDO component to send mail through an SMTP server that requires authentication:
(in C #)
 code as follows:

public void Cdosendmail ()
{
Try
{
Cdos. Message omsg = new CDO. Message ();

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

Omsg.htmlbody = "Cdos. 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 represents anonymous Authentication mode (no validation required)
The value=1 represents the Basic authentication method (using Basic (Clear-text) authentication.
The configuration Sendusername/sendpassword or Postusername/postpassword fields are used to specify.)
VALUE=2 represents NTLM authentication Mode (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: Due to the Exchange2000 CDO component Cdoex.dll will update the original Windows2000 CDO component Cdosys.dll, So if you want to continue using Cdosys.dll, you must first uninstall the Cdoex.dll by Regsrv32.exe.
Compose a mail dispatcher using the socket
Of course, if you feel that SmtpMail does not meet your needs, the CDO is not straightforward enough, then you have to do it yourself; in fact, if you are familiar with the socket programming, it is not difficult to write your own e-mail program, the following is an example.
First, let's briefly explain how the authenticated SMTP server uses the AUTH primitive for authentication, and its detailed definition can refer to RFC2554.
Specifically as follows:
1 First, you need to use EHLO instead of the original helo.
2 EHLO successful, the client needs to send the Auth primitive language, and the server on the authentication of the user name and password of the way to negotiate.
3 If the negotiation succeeds, the server will return a result code beginning with 3, which can pass the username and password to the server.
4 Finally, if the verification is successful, you can start the letter.
The following is a practical example where the client connects to 263 of the SMTP server in the command window of WinXP via the telnet smtp.263.net 25 = commands:
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
8BITMIME
AUTH LOGIN
334 Vxnlcm5hbwu6
Bxlhy2nvdw50
334 Ugfzc3dvcmq6
bxlwyxnzd29yza==
235 Authentication Successful
MAIL from:myaccount@263.net
Ok
RCPT to:myaccount@263.net
Ok
Data
354 End data with <CR><LF>.<CR><LF>
This is a testing email.
haha.
.
Ok:queued as Ac5291d6406c4
QUIT
221 Bye
The above content is the whole process of the letter. Where authentication is primarily related to lines nineth through 14th:
AUTH LOGIN '; '; '; '; Client input
334 vxnlcm5hbwu6 '; '; Server Prompts "username:="
Bxlhy2nvdw50 '; '; '; '; BASE64 encoding for client input "myaccount="
334 ugfzc3dvcmq6 '; '; Server Prompts "password:="
bxlwyxnzd29yza== '; '; '; '; BASE64 encoding for client input "mypassword="
235 authentication successful '; '; Server-side Pass validation
As can be seen from the above analysis, in this authentication process, the server and the client directly through the socket pass through the standard BASE64 encoded plain text. This process can be easily implemented in C #, or added directly to the original source code.
In addition, some ESMTP servers do not support Auth login mode authentication, only support auth CRAM-MD5 mode authentication. But the difference between the two is that the text is encoded in a different way.
The source code that implements this feature can be found on the sourceforge.net http://sourceforge.NET/projects/opensmtp-net/download. A simple pseudo code is given below:
code as follows:

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;
}

Summarize
This article describes the. NET three different ways to send mail using the SMTP protocol, where the first (using the SmtpMail Class) scenario meets most of the basic messaging functionality requirements, The second (using CDO components) and the third (compose SMTP class with socket) scenario provides a more free and complete customization method, such as the ability to send mail through a certified SMTP server that the first scenario does not.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.