Vb. NET verify the legality of the email address to implement code _ practical skills

Source: Internet
Author: User
Tags rfc mail account mail exchange mx record nslookup nslookup command
First, ask questions
Now, for the email address that the user gives on the Web page or on the phone, we are increasingly not sure if it really works. In today's era of spam, there is every reason to be reluctant to disclose the email address easily.
  
On the other hand, when we use it for legitimate purposes, we often worry about whether the email address is valid or not, and the user may intentionally or unintentionally write the wrong address, or it may cause the mailbox to fail because of the long time not accessing the email address. For a small number of email addresses, it may be possible to validate their legality by hand, such as sending test emails, but when the number of e-mail addresses reaches tens of thousands of or more, manual validation is not possible and must be performed automatically by a dedicated tool or by writing your own program.
  
The general authentication method only judges the legality of the email address, for example, check if it contains "@" and "." Symbol. Obviously, this kind of inspection is not sufficient, the email address format is correct does not prove that it must be valid. For this reason, some websites have taken the email password, special resources URL, etc., or ask the user to reply to email, to ensure the validity of the email address. However, these methods are not always effective, for example, you may not collect user emails from your own website, but get them through a third party.
  
Considering these reasons, the most fundamental way to verify the legality of an email address is to query the mail server. This article will give you a complete vb.net code to complete this task.
  
   second, the legality of the mail server
The first step in determining the legality of any email address is, of course, to see if it is in the correct format, such as whether it contains "@" and "." Symbols, a lot of this information, there are even ready-made controls, so this article will not repeat. Our task begins by determining whether the domain of the email address is valid, for example, for abc@sina.com.cn, to first determine whether the sina.com.cn mail server is active.
  
Each domain has an MX record, the mail exchange exchanger record, that points to the server that handles the email in that domain, and we only need to query the DNS server to get that information. The nslookup command that Windows itself brings is ideal for completing this task, for example, to find a sina.com.cn mail server, just perform nslookup-type=mx sina.com.cn, where-type=mx indicates that you want to find an MX record. The output is as shown in figure one. The Windows nslookup command is available only after you install the TCP/IP protocol, and you can see Windows Help for more information.
    
The following Getmailserver function encapsulates an operation that invokes the Windows nslookup command, returning the mail server based on the domain name specified in the parameter.
  
Private Function getmailserver (ByVal Sdomain As String) as String
Dim info as New ProcessStartInfo ()
Dim NS as Process
' Call the Windows nslookup command to find the mail server
Info. UseShellExecute = False
Info. Redirectstandardinput = True
Info. Redirectstandardoutput = True
Info. FileName = "Nslookup"
Info. CreateNoWindow = True
' Lookup type is MX. For a detailed description of Nslookup, see
' Windows Help
Info. Arguments = "-type=mx" + SDomain.ToUpper.Trim
' Start a nslookup command to execute Windows ()
NS = Process.Start (info)
Dim Sout as StreamReader
Sout = ns. StandardOutput
' Use regular expressions to find mail server information in nslookup command output results
Dim reg as Regex = New Regex ("Mail exchanger = (? [^\\\s]+)]
Dim MailServer as String
Dim response as String = ""
Do while (sout). Peek () >-1)
Response = Sout. ReadLine ()
Dim Amatch as Match = Reg. Match (response)
If (Amatch. Success) Then
MailServer = Amatch. Groups ("Server"). Value
Exit do
End If
Loop
Return mailserver
End Function
  
   third, the legality of the email address
As long as the domain specified in the email address is legal, we can connect to the mail server and try to send an email. If the mail server responds that the user is illegal or does not exist, the mail address is invalid. The main actions in this step include creating a socket to connect to the mail server, and then communicating with the server as required by the SMTP mail Transfer Protocol to complete the mail delivery operation. For a detailed description of the SMTP protocol, interested readers can see the SMTP specification (RFC 821): Http://www.ietf.org/rfc/rfc821.txt.
  
The input parameter of the Checkemail function below is a mail address, and the return value of the function indicates whether the address is legitimate. The function has two values that can be adjusted at will: in the process of sending a message, we have to provide a legal domain name to each other's mail server to indicate our identity. The choice here is sina.com.cn, depending on how busy the network and the other mail servers are, the response time varies, and the wait time is 3 seconds. When the network or the other server is very busy, reducing the wait time increases the likelihood that the test will fail.
  
Public Function Checkemail (ByVal semail as String) as Long
  
Dim Ostream as NetworkStream
Dim sfrom as String ' sender
Dim STo as String ' recipient
Dim sresponse as String ' mail server answer
Dim remote_addr as String ' sender's domain name
Dim mserver as String ' mail server
Dim Stext as String ()
  
STo = "<" + Semail + ">"
' Separate the account name and domain name from the mail address
Stext = Semail.split (CType ("@", Char))
' Find the mail server for this domain
Mserver = Getmailserver (stext (1))
' Mserver is a null value indicates that the lookup mail server failed
If mserver = "" Then
Return 4
Exit Function
End If
' The domain name of the sender's address must be legal
REMOTE_ADDR = "sina.com.cn"
Sfrom = " ' Delay the creation of objects as much as possible
Dim oconnection as New tcpclient ()
Try
' Timeout time
Oconnection.sendtimeout = 3000
' Connect SMTP port
Oconnection.connect (Mserver, 25)
' Collect answer information for mail server
Ostream = Oconnection.getstream ()
Sresponse = GetData (ostream)
Sresponse = SendData (ostream, "HELO" & Remote_addr & VbCrLf)
Sresponse = SendData (Ostream, "MAIL from:" & Sfrom & VbCrLf)
' If there is a positive response to the mail from Directive,
' At least indicates the correct name of the email address
If validresponse (sresponse) Then
Sresponse = SendData (Ostream, "RCPT to:" & STo & VbCrLf)
' If there is a positive response to the RCPT TO command
' Indicates that the mail server has approved the address
If validresponse (sresponse) Then
Return 1 ' Email address valid
Else
Return 2 ' Only domain name is valid
End If
End If
' End the session with the mail server
SendData (Ostream, "QUIT" & VbCrLf)
Oconnection.close ()
Ostream = Nothing
Catch
Return 3 ' Wrong!
End Try
End Function
  
' Get the server answer data and convert it to string
Private Function GetData (ByRef ostream as NetworkStream) as String
  
Dim Bresponse (1024) as Byte
Dim Sresponse as String
  
Dim Lenstream as Integer = Ostream.read (bresponse, 0, 1024)
If lenstream > 0 Then
Sresponse = Encoding.ASCII.GetString (bresponse, 0, 1024)
End If
Return Sresponse
End Function
' Send data to the mail server
Private Function SendData (ByRef ostream as NetworkStream, ByVal Stosend As String) as String
Dim Sresponse as String
' Converts a string into a byte array
Dim Barray () as Byte = Encoding.ASCII.GetBytes (Stosend.tochararray)
' Send data
Ostream.write (Barray, 0, Barray.length ())
Sresponse = GetData (ostream)
' Return answer
Return Sresponse
End Function
  
' Does the server return a positive answer? '
Private Function validresponse (ByVal Sresult as String) as Boolean
Dim Bresult as Boolean
Dim Ifirst as Integer
If sresult.length > 1 Then
Ifirst = CType (sresult.substring (0, 1), Integer)
' If the server returns the first character of the answer is less than ' 3 '
' We think the server has approved the operation just now
If Ifirst < 3 Then bresult = True
End If
Return Bresult
End Function
  
The return value of the Checkemail function indicates the test result: 1 indicates that the mail address is valid, 2 indicates that only the domain name is correct (the user's mail account may be invalid), 3 indicates an error, and 4 indicates that the mail server cannot be found.
  
   Four, user interface
We have completed the core functions of testing the legality of email addresses, which can be used in various forms of applications, including Web services, Windows applications, controls, and so on, with a maximum of one change in the declaration mode. To facilitate testing of these functions, let's do a simple user interface in the form of Windows applications.
  
Start Vs.net, select New Visual Basic project, Windows application, figure two, enter project name Checkmail and save location, click "OK" button, VS. NET to create a new project.
    
Drag a text label, an input box, and a button from the Toolbox onto a form that vs.net automatically creates. Change the form's Text property to "email address test," Change the text label to "mail address", change the button's Text property to "check!", and adjust the position of each control so that it looks neat and beautiful, as shown in Figure three.
    
Double-click the button and enter the BUTTON1_CLI to perform when you click the button

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.