C # How to test whether the smtpclient client successfully connects to the smtpserver?

Source: Internet
Author: User
Tags smtpclient

Refer to my blog post for a souvenir, especially the hash code-use SMTP to send emails in. net.

Reference and sort out chinafcl

In smtpclient, only the email address, password, and SMTP server address are provided. How can I test whether the email address and password are correct? (Similar to the test connection function of the mail client)

Private bool checksmtp (string smtpserver, int port, string username, string password)
{
Tcpclient = new tcpclient (smtpserver, Port );
Networkstream stream = tcpclient. getstream ();

If (! Waitefor (stream, "220") return false;

Sendcommand (stream, "HELO 211.152.50.xxx \ r \ n ");
If (! Waitefor (stream, "250") return false;

Sendcommand (stream, "auth login \ r \ n ");
If (! Waitefor (stream, "334") return false;

Sendcommand (stream, base64encode (username) + "\ r \ n ");
If (! Waitefor (stream, "334") return false;

Sendcommand (stream, base64encode (password) + "\ r \ n ");
If (! Waitefor (stream, "235") return false;

Return true;

}

Private bool waitefor (networkstream stream, string strcode)
{
Int streamsize;
Byte [] readbuffer = new byte [1024];
Streamsize = stream. Read (readbuffer, 0, readbuffer. Length );
String returnvalue = encoding. Default. getstring (readbuffer). substring (0, streamsize );

Console. writeline (returnvalue );

Return returnvalue. substring (0, 3). Equals (strcode );
}
Private void sendcommand (networkstream stream, string strcmd)
{
Byte [] writebuffer;

Writebuffer = encoding. Default. getbytes (strcmd );

Stream. Write (writebuffer, 0, writebuffer. Length );

}

Private string base64encode (string Str)
{
Byte [] barray;
Barray = encoding. Default. getbytes (STR );
Return convert. tobase64string (barray );
}

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.