Click here to Skip to main content
11,482,103 members (66,727 online)
Click here to Skip to main content

Implement POP3 and SMTP in .NET

, 4 Jan 2006 CPOL 396.4K 7.5K 132
Rate this:
Please Sign up or sign in to vote.
Using socket to implement POP3 and SMTP protocol.

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

'POP3
'The pop3 server will return "+OK" when command success, 
'otherwise it will return "-ERR".
    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
'SMTP
'The SMTP server will return a message with a three-bit-digital 
'for each command. The first bit indicates whether the 
'command is successful or failed as show below

    Private Function CorrectedResponse(ByVal ReceivedBytes() As Byte, _
                       Optional ByRef Message As String = "") As Boolean
        'The first digital of the three digitals in 
        'response message indicates as follow:
        '1: command accepted, waiting for confirm
        '2: command executed
        '3: command accepted, waiting for more information
        '4: command refused
        '5: command failed
        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

'Get mail list from serverrDim MailReceiver As QMailClient.POP3Client
MailReceiver = New POP3Client        
MailReceiver.RemoteServerAddress = "pop3.163.com"
MailReceiver.UserName = "xxx"
MailReceiver.Password = "yyyy"
'Optional, please set this TRUE when you are under firewall or 
'using antivirus software which will scan incoming and outgoing mails.
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
'Get a mail from server according to the 
'mail index which can be obtained in mail list
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 Index, it can be obtain from mail list(start from 1)
  Mail = MailReceiver.RetrieveMail(MailIndex)   
Catch ex As Exception
  MessageBox.Show(ex.Message, "Error", _
       MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
  MailReceiver.Quit()


End Try
'NOTES: The Retrievemail() method has two overloads which will return 
'a QMailClient.EMail object or the source code string of the mail,
'The EMail object can decode the mail automatically and 
'support many mail content type such as multipart/mixed,
'multipart/related and multipart/report.
'If you want to use your own mail decoder then just call the overload 
'function which only return mail source code (string).
'Show mail on a form or a web page
'NOTES: The code below is not assured to run because it needs some 
'form controls, here just show an example.
'The Email.body contains the plain text mail content and the 
'Email.bodyHTML contains the source HTML code of the mail 
'content if the mail is formatted in HTML
    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
>>        'Write a temp file to show HTML mail
>>        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
>>                'Create a empty file in order to get icon
>>                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
'Sending a mail
>>>>       Dim mailSend As New QMailClient.EMail
                       'Use ";" to splite multi-receivers
>>>>       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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

TonyTonyQ
Architect
China China
No Biography provided
Follow on   LinkedIn

Comments and Discussions

 
QuestionHow to search in OLD emails or how to retrieve old emails? Pin
Member 456788820-Feb-14 1:00
memberMember 456788820-Feb-14 1:00 
AnswerRe: How to search in OLD emails or how to retrieve old emails? Pin
TonyTonyQ23-Apr-14 0:11
professionalTonyTonyQ23-Apr-14 0:11 
BugCrashes on badly formed from addresses Pin
Member 361026326-Mar-13 23:37
memberMember 361026326-Mar-13 23:37 
QuestionError: Charset not supported: 3Diso-8859-= Pin
KGRBernd21-Oct-11 0:54
memberKGRBernd21-Oct-11 0:54 
QuestionHow to filter POP3 Email from Junk Mail ? Pin
hoi20-Oct-10 17:47
memberhoi20-Oct-10 17:47 
GeneralSending mail: Null reference Pin
devastator78930-Sep-10 11:32
memberdevastator78930-Sep-10 11:32 
GeneralRe: Sending mail: Null reference Pin
devastator78930-Sep-10 11:57
memberdevastator78930-Sep-10 11:57 
QuestionWhere is the DLL file for this project? Pin
Tony Girgenti30-Jun-10 10:25
memberTony Girgenti30-Jun-10 10:25 
AnswerRe: Where is the DLL file for this project? Pin
devastator78930-Sep-10 10:27
memberdevastator78930-Sep-10 10:27 
GeneralRe: Where is the DLL file for this project? Pin
Tony Girgenti30-Sep-10 11:10
memberTony Girgenti30-Sep-10 11:10 
GeneralRe: Where is the DLL file for this project? Pin
devastator78930-Sep-10 11:35
memberdevastator78930-Sep-10 11:35 
GeneralAn established connection was aborted by the software in your host machine Pin
ank6516-Jun-10 18:22
memberank6516-Jun-10 18:22 
QuestionI am confused - please helps peeps Pin
dielan master14-Apr-10 15:25
memberdielan master14-Apr-10 15:25 
GeneralI am confused Pin
dielan master14-Apr-10 15:24
memberdielan master14-Apr-10 15:24 
QuestionUnicode attachment format not support Pin
Praveen Kumar26-Feb-10 23:51
memberPraveen Kumar26-Feb-10 23:51 
Generalgetmaillist Pin
RezTiNpeaCe10-Feb-10 10:17
memberRezTiNpeaCe10-Feb-10 10:17 
Questioncan't use HttpUtility Pin
villamind10-Oct-09 5:17
membervillamind10-Oct-09 5:17 
AnswerRe: can't use HttpUtility Pin
Member 385703511-Jul-10 5:47
memberMember 385703511-Jul-10 5:47 
GeneralAbout getting attachment from MailList Pin
friendprach10-Oct-09 1:27
memberfriendprach10-Oct-09 1:27 
GeneralRe: About getting attachment from MailList Pin
maslopo3-May-10 5:14
membermaslopo3-May-10 5:14 
GeneralAbout UniqueID Pin
friendprach9-Oct-09 20:22
memberfriendprach9-Oct-09 20:22 
GeneralAbout retreiving Gmail Mail using above code Pin
friendprach9-Oct-09 20:03
memberfriendprach9-Oct-09 20:03 
GeneralSaveToStream problem Pin
voellinger11-Sep-09 12:03
membervoellinger11-Sep-09 12:03 
Generalthank you TonyTonyQ Pin
Member 287396824-Aug-09 8:03
memberMember 287396824-Aug-09 8:03 
Questionpop3 massege login failed With email Gmail [modified] Pin
khalidys24-Aug-09 3:13
memberkhalidys24-Aug-09 3:13 
AnswerRe: pop3 massege login failed With email Gmail Pin
RezTiNpeaCe10-Feb-10 15:29
memberRezTiNpeaCe10-Feb-10 15:29 
GeneralThank you, Tony Pin
Domenican16-Jul-09 21:01
memberDomenican16-Jul-09 21:01 
GeneralAttachments Pin
alterjo6-Jul-09 23:07
memberalterjo6-Jul-09 23:07 
GeneralRe: Attachments Pin
Santoshbalid2-Nov-12 3:40
memberSantoshbalid2-Nov-12 3:40 
GeneralBug in POP3Client.SendCommand (Possible Infinite Loop) Pin
dequadin25-Jun-09 3:49
memberdequadin25-Jun-09 3:49 
QuestionAtt.ContentID Pin
Ruandv4-Jun-09 22:49
memberRuandv4-Jun-09 22:49 
Questioncan not retrieve Attachments Pin
Ruandv4-Jun-09 3:35
memberRuandv4-Jun-09 3:35 
AnswerRe: can not retrieve Attachments Pin
TonyTonyQ4-Jun-09 6:26
memberTonyTonyQ4-Jun-09 6:26 
AnswerRe: can not retrieve Attachments Pin
Ruandv4-Jun-09 21:42
memberRuandv4-Jun-09 21:42 
QuestionCannot save attatchemt to my server. It is trying to save to a strange path... Pin
acowbear13-May-09 9:43
memberacowbear13-May-09 9:43 
AnswerRe: Cannot save attatchemt to my server. It is trying to save to a strange path... Pin
TonyTonyQ13-May-09 18:48
memberTonyTonyQ13-May-09 18:48 
GeneralRe: Cannot save attatchemt to my server. It is trying to save to a strange path... Pin
acowbear14-May-09 6:08
memberacowbear14-May-09 6:08 
GeneralRe: Cannot save attatchemt to my server. It is trying to save to a strange path... Pin
acowbear15-May-09 4:14
memberacowbear15-May-09 4:14 
QuestionHow do you use the Reply To Pin
thebigo11-Mar-09 20:20
memberthebigo11-Mar-09 20:20 
GeneralAttachment Pin
Padingt0n3-Mar-09 7:51
memberPadingt0n3-Mar-09 7:51 
GeneralRe: Attachment Pin
TonyTonyQ3-Mar-09 16:01
memberTonyTonyQ3-Mar-09 16:01 
QuestionProblem with Plain-Text special characters encoding [modified] Pin
jerzdna24-Jun-08 0:09
memberjerzdna24-Jun-08 0:09 
AnswerRe: Problem with Plain-Text special characters encoding Pin
Ruuteek2-Oct-08 1:44
memberRuuteek2-Oct-08 1:44 
GeneralRe: Problem with Plain-Text special characters encoding Pin
Ruuteek2-Oct-08 3:22
memberRuuteek2-Oct-08 3:22 
QuestionUnable to Get this working - please help Pin
Tastic19-Apr-08 0:13
memberTastic19-Apr-08 0:13 
QuestionRe: Unable to Get this working - please help Pin
anas010011-Nov-09 5:33
memberanas010011-Nov-09 5:33 
GeneralGreat Job! Pin
zach_hurst11-Mar-08 17:19
memberzach_hurst11-Mar-08 17:19 
Generalpop3 Pin
anilshelar458-Mar-08 0:37
memberanilshelar458-Mar-08 0:37 
QuestionAm getting "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond" error.... Pin
krsk4u6-Mar-08 3:24
memberkrsk4u6-Mar-08 3:24 
AnswerRe: Am getting "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond" error.... Pin
zach_hurst11-Mar-08 17:32
memberzach_hurst11-Mar-08 17:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150520.1 | Last Updated 4 Jan 2006
Article Copyright 2004 by TonyTonyQ
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid