Code for verifying the validity of email addresses using VB. NET

Source: Internet
Author: User
Tags email account mx record nslookup nslookup command

I. Ask questions
At present, we are increasingly not sure whether the Email address provided by the user on the Web page or on the phone is actually valid. In today's age of spam flooding, people have no reason to give up their Email addresses easily.
  
On the other hand, when we use an email address obtained through a regular channel for legal purposes, it is often necessary to worry about whether the email address is valid, the user may intentionally or unintentionally write the wrong address, or the mailbox may be invalid because the user does not access the email for a long time. For a small number of mail addresses, you may be able to manually verify their legitimacy, such as sending test emails. However, when the number of mail addresses reaches tens of thousands or more, manual verification is impossible, you must use a dedicated tool or write your own program to automatically perform verification.
  
The regular verification method only checks validity of the email address format, for example, checks whether it contains the "@" and "." symbols. Obviously, this check is inadequate, and the correct email address format does not prove to be valid. For this reason, some websites adopt methods such as sending passwords by email and URLs of special resources, or require users to reply to emails 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 website, but get them through a third party.
  
For these reasons, the most fundamental way to verify the legitimacy of the email address is to query the email server. This article provides the complete VB. NET code to complete this task.
  
  Ii. Legitimacy of email server
The first step to determine the validity of any email address is to check whether its format is correct, for example, whether it contains "@" and ". "symbol, there is a lot of information in this regard, and there are even ready-made controls, so this article will not go into details. Our task starts from determining whether the domain of the mail address is valid, for example, for the abc@sina.com.cn address, first determining whether the mail server of sina.com.cn is valid.
  
Each domain has an MX record, that is, the Mail Exchanger record, which points to the server that processes the email in the domain. We only need to query the DNS server to obtain this information. The nslookup Command provided by Windows is very suitable for this task. For example, to search for the sina.com.cn mail server, you only need to execute nslookup-type = mx sina.com.cn, -type = MX indicates the MX record to be searched. output result 1 is displayed. The nslookup command for Windows is available only after the TCP/IP protocol is installed. For details, see Windows Help.
  

 
The following GetMailServer function encapsulates the operation to call the Windows nslookup command, and returns the email server according to 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
'The search type is MX. For more information about nslookup, see
'Windows help
Info. Arguments = "-type = MX" + sDomain. ToUpper. Trim
'Start an nslookup command for running Windows ()
Ns = Process. Start (info)
Dim sout As StreamReader
Sout = ns. StandardOutput
'Use the regular expression to find the mail server information in the output result of the nslookup command.
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
  
   Iii. Legitimacy of email addresses
As long as the domain specified in the email address is valid, we can connect to the email server and try to send an email. If the email server replies that the user is illegal or does not exist, the email address is invalid. The main operations in this step include creating a Socket to connect to the mail server, and then communicating with the server according to the requirements of the SMTP mail Transmission Protocol to complete the mail sending operation. For more information about the SMTP protocol, see SMTP specifications (RFC 821): http://www.ietf.org/rfc/rfc821.txt.
  
The input parameter of the following CheckEmail function is an email address. The return value of the function indicates whether the address is valid. This function has two values that can be adjusted at will: when sending an email, we need to provide a valid domain name to the recipient's email server to indicate our identity. Here we choose sina.com.cn; the response time varies depending on the amount of free time on the network and the recipient's email server. Here, the waiting time is 3 seconds. When the network or the other server is very busy, reducing the wait time will increase the possibility of test failure.
  
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 'response from the email server
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 email address
SText = sEmail. Split (CType ("@", Char ))
'Find the email server in this domain
Mserver = GetMailServer (sText (1 ))
'Mserver is null, indicating an error occurred while searching for the email server.
If mserver = "" Then
Return 4
Exit Function
End If
'The sender address domain name must be legal
Remote_Addr = "sina.com.cn"
SFrom =" 'Try to delay the object Creation Time
Dim oConnection As New TcpClient ()
Try
'Timeout
OConnection. SendTimeout = 3000
'Connect to the SMTP port
OConnection. Connect (mserver, 25)
'Collect the response information of the email server
OStream = oConnection. GetStream ()
SResponse = GetData (oStream)
SResponse = SendData (oStream, "HELO" & Remote_Addr & vbCrLf)
SResponse = SendData (oStream, "mail from:" & sFrom & vbCrLf)
'If you have a positive response to the mail from instruction,
'At least indicates that the email address's domain name is correct
If ValidResponse (sResponse) Then
SResponse = SendData (oStream, "rcpt to:" & sTo & vbCrLf)
'If you have a positive response TO the rcpt to command
'Indicates that the email server has accepted the address
If ValidResponse (sResponse) Then
Return 1 'email address is valid
Else
Return 2 'only valid for domain names
End If
End If
'End the session with the email server
SendData (oStream, "QUIT" & vbCrLf)
OConnection. Close ()
OStream = Nothing
Catch
Return 3' error!
End Try
End Function
  
'Get Server Response 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 email server
Private Function SendData (ByRef oStream As NetworkStream, ByVal sToSend As String) As String
Dim sResponse As String
'Convert String to Byte array
Dim bArray () As Byte = Encoding. ASCII. GetBytes (sToSend. ToCharArray)
'Send data
OStream. Write (bArray, 0, bArray. Length ())
SResponse = GetData (oStream)
'Return response
Return sResponse
End Function
  
'The server returns a positive response?
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 first character returned by the server is less than '3'
'We think the server has accepted 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 email address is valid, 2 indicates that only the domain name is correct (the user's email account may be invalid), and 3 indicates that an error has occurred, 4 indicates that the email server cannot be found.
  
   Iv. User Interface
We have tested whether the email address is a valid core function. These functions can be used in various forms of applications, including Web Services, Windows applications, controls, etc, you only need to modify the declaration method at most. To facilitate the test of these functions, we will create a simple user interface in the form of a Windows application.
  
Start VS. NET, select create Visual Basic project and Windows application, and enter the project name CheckMail and save location. Click "OK" to create a new project.
    
Drag a text tag, an input box, and a button from the toolbox to a form automatically created by VS. NET. Change the TEXT attribute of the form to "Email address test", the TEXT attribute of the TEXT tag to "Email address", and the TEXT attribute of the button to "Check !", Adjust the position of each control to make it look neat and beautiful.
    
Double-click the button and enter the buttondeskcli

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.