Introduction
This article shows how to use VB.NET to implement POP3 and SMTP protocol. There is a DLL file included in the source files, this DLL contains two classes to implement POP3 and SMTP and an extra class for e-mail's codec (base 64 only, not included in the source code because it is being tested now).
Any questions? Please contract me immediately at soldierq@msn.com.
Main functions in these Classes
The most basic functions are the same in POP3
class and the SMTP
class.
Connect to Mail Server
Private Function Connect() As Boolean
Try
sockPOP3.Connect(m_Remote)
If sockPOP3.Connected = True Then
sockPOP3.Receive(bufferReceive)
Return True
Else
Return False
End If
Catch ex As Exception
sockPOP3.Close()
Throw New Exception("Failed to Connect " +
"Host:" & vbCrLf & ex.Message)
End Try
End Function
Send Commands to Server
Private Function SendCommand(ByVal Command As String) As Byte()
Try
bufferSend = Encoding.ASCII.GetBytes(Command & vbCrLf)
sockPOP3.Send(bufferSend)
Array.Clear(bufferReceive, 0, bufferReceive.Length)
sockPOP3.Receive(bufferReceive)
Return bufferReceive
Catch ex As Exception
Throw New Exception("Error In Sending " +
"Command To Server:" & vbCrLf & ex.Message)
End Try
End Function
Check Server Response
Private Function CorrectedResponse(ByVal ReceivedBytes() As Byte, _
Optional ByRef Message As String = "") As Boolean
Dim strText As String = Encoding.ASCII.GetString(ReceivedBytes)
Message = strText
RaiseEvent GotResponse(strText)
If strText.StartsWith("+OK") Then
Return True
Else
Return False
End If
End Function
Private Function CorrectedResponse(ByVal ReceivedBytes() As Byte, _
Optional ByRef Message As String = "") As Boolean
Dim strText As String = Encoding.ASCII.GetString(ReceivedBytes)
Message = strText
RaiseEvent GotResponse(strText)
Select Case strText.Substring(0, 1)
Case 1, 2, 3
Return True
Case 4, 5
Return False
Case Else
Return False
End Select
End Function
Commands in POP3 and SMTP
Here I'll just show you two session samples with a mail server using Microsoft Exchange. The mail
class calls the SendCommand()
method and the CorrectedResponse()
method to send commands to the server and check the command execution results. You can find more information about the POP3 and SMTP protocol standards on the Web.
The bold string indicates it's a command:
==SMTP===
220 Microsoft ESMTP MAIL Service, Version: 5.0.2195.6713 ready at
Fri, 13 Aug 2004 11:12:22 +0800
helo
250 mail.cyberrs2.com Hello [192.168.101.52]
mail from:test@test.com
250 2.1.0 test@test.com ....Sender OK
rcpt to:abc@abc.com
250 2.1.5 abc@abc.com
data
354 Start mail input; end with <CRLF>.<CRLF>
subject:test test smtp & pop3
.
250 2.6.0 <MAILiAXL21xDenYPnDd00022f02> Queued mail for delivery
quit
221 2.0.0 Service closing transmission channel
==POP3==
+OK Microsoft Exchange Server 2003 POP3 6.5.6944.0 (mail.cyberrs2.com)
user test
+OK
pass ******
+OK User successfully logged on.
stat
+OK 1 414
list
+OK 1 414
1 414
.
retr 1
+OK
Received: Microsoft SMTPSVC(5 .0.2195.6713);
Fri, 13 Aug 2004 11:12:45 +0800 subject:test From: test@test.com
Bcc:
Return-Path: test@test.com
Message-ID: <MAILiAXL21xDenYPnDd00022f02>
X-OriginalArrivalTime: 13 Aug 2004 03:13:00.0356 (UTC)
FILETIME=[7051D840:01C480 E3]
Date: 13 Aug 2004 11:13:00 +0800
test smtp & pop3
.
dele 1
+OK
quit
+OK Microsoft Exchange Server 2003 POP3 6.5.6944.0
How to use the QMailClient Class
MailReceiver = New POP3Client
MailReceiver.RemoteServerAddress = "pop3.163.com"
MailReceiver.UserName = "xxx"
MailReceiver.Password = "yyyy"
MailReceiver.IncreaseNetworkCompatible = True
If MailReceiver.Login() = False Then
MessageBox.Show("Login failed", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
If Not arrList Is Nothing Then
arrList.Clear()
arrList = MailReceiver.GetMailList(True)
MailReceiver.Quit()
End Iff
Dim MailReceiver As QMailClient.POP3Client
MailReceiver = New POP3Client
MailReceiver.RemoteServerAddress = "pop3.163.com"
MailReceiver.UserName = "xxx"
MailReceiver.Password = "yyyy"
MailReceiver.IncreaseNetworkCompatible = True
Try
MailReceiver.Login()
Mail = MailReceiver.RetrieveMail(MailIndex)
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
MailReceiver.Quit()
End Try
Private Sub ShowMail()
>> Me.lblMailDate.Text = "DATE: " & Mail.Date
>> Me.lblMailFrom.Text = "FROM: " & Mail.From
>> Me.lblMailSubject.Text = "SUBJECT: " & Mail.Subject
>> Me.lblMailTo.Text = "TO: " & Mail.To
>>
>> If Mail.BodyContentType = EMail.ContentType.MultipartAlternative Then
>> Dim file As New FileStream(FolderTmp & "tmp.html", _
FileMode.Create, FileAccess.Write, FileShare.None)
>> Dim a As Encoding = Encoding.GetEncoding("gb2312")
>>
>> file.Write(a.GetBytes(Mail.BodyHTML), 0, _
a.GetByteCount(Mail.BodyHTML))
>> file.Close()
>> Me.rtxtContent.Text = Mail.Body
>> Me.tbtnHTML.Enabled = True
>> ElseIf Mail.BodyContentType = EMail.ContentType.MultipartRelated Then
>> Dim file As New FileStream(FolderTmp & "tmp.html", _
FileMode.Create, FileAccess.Write, FileShare.None)
>> Dim a As Encoding = Encoding.GetEncoding("gb2312")
>>
>> Dim att As MailAttachment
>> Dim strBody As String = Mail.BodyHTML
>> For Each att In Mail.Attachments
>> If att.ContentID <> "" Then
>> strBody = strBody.Replace("cid:" & att.ContentID, _
att.FileName)
>> att.SaveToFile(FolderTmp & att.FileName)
>> End If
>> Next
>>
>> file.Write(a.GetBytes(strBody), 0, a.GetByteCount(strBody))
>> file.Close()
>> Me.rtxtContent.Text = Mail.Body
>> Me.tbtnHTML.Enabled = True
>> Else
>> Me.rtxtContent.Text = Mail.Body
>> Me.tbtnHTML.Enabled = False
>> End If
>>
>> If Mail.Attachments.Count <> 0 Then
>> Dim mailAttach As MailAttachment
>>
>> For Each mailAttach In Mail.Attachments
>>
>> Dim strExName As String = _
>> FileInformation.GetFileExtendedName(mailAttach.FileName)
>> Dim strmFile As New _
>> FileStream(FolderTmp & "ico." & strExName, _
>> FileMode.Create)
>> strmFile.Close()
>>
>> Dim fsi As System.IO.FileSystemInfo
>> fsi = New FileInfo(FolderTmp & "ico." & strExName)
>> imgFileIcons.Images.Add(IconExtractor.GetSmallIcon(fsi))
>> lstvAttachments.Items.Add(_
SysInfomation.GetFileNameFromFilePath(_
mailAttach.FileName), _
imgFileIcons.Images.Count - 1)
>> Next
>> Me.grpbxAttach.Visible = True
>> End If
>> End Sub
>>>> Dim mailSend As New QMailClient.EMail
>>>> mailSend.To = "abc@bcd.com;dd@dd.com"
>>>> mailSend.Cc = "cc@dd.com"
>>>> mailSend.Subject = "test"
>>>> mailSend.Body = "test1"
>>>> mailSend.From = "abc@abc.com"
>>>>
>>>> Dim mailClient As New SMTPClient
>>>> mailClient.RemoteServerAddress = "pop3.163.com"
>>>>
>>>> mailClient.IncreaseNetworkCompatible = True
>>>>
>>>> If mailClient.Connect = True Then
>>>>
>>>> mailClient.UserName = "user"
>>>> mailClient.Password = "pass"
>>>>
>>>> If mailClient.AuthLogin = False Then
>>>> MessageBox.Show("Authentication failed", _
"Error", MessageBoxButtons.OK, _
MessageBoxIcon.Error)
>>>>
>>>> Exit Sub
>>>> End If
>>>>
>>>>
>>>> mailClient.SendMail(mailSend)
>>>>
>>>> mailClient.Quit()
>>>>
>>>> mailClient = Nothing
>>>> End If