asp.net send email

Source: Internet
Author: User
Tags auth base64 count socket versions email account mailmessage net send
asp.net

First, let's take a look at the SMTP classes that are coming with the. NET class library.
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
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 #)
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).


Second, send 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 #)
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 = "Test";


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 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.


Third, use the socket to compose the mail sending program
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 via the Telnet smtp.263.net 25 command in WinXP's command window:
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 .
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 hint" username:= "
BXLHY2NVDW50 "Client Input" myaccount= "BASE64 encoding
334 UGFZC3DVCMQ6 "Server hint" password:= "
bxlwyxnzd29yza== "Client Input" mypassword= "BASE64 encoding
235 Authentication Successful "server-side 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:
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.