返回首页

简介
本文介绍如何使用VB.NET实现POP3和SMTP协议。在源文件中包含有一个DLL文件,该DLL包含两个类来实现POP3和SMTP和电子邮件的编解码器的一个额外的类(基数为64只,不包含在源代码,因为它是现在正在测​​试)。
有问题吗?请合同{A}我立刻。这些类的主要功能
最基本的功能是相同的类的POP3和SMTP类。连接到邮件服务器

   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
发送命令到服务器{C}检查服务器的响应
'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
POP3和SMTP的命令
在这里,我将只显示您使用Microsoft Exchange邮件服务器的两个会议。邮件类调用的SendCommand()方法和CorrectedResponse()方法,将命令发送到服务器并检查命令的执行结果。你可以找到更多关于POP3和SMTP协议标准的信息在网络上。
大胆的字符串表示这是一个命令:
==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
如何使用QMailCli​​ent类
'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

回答

评论会员:KGRBernd 时间:2011/12/03
检索电子邮件时,我得到上面的错误信息EMail.vb模块,功能DecodeTextContent(创建)命令行:
请帮帮忙!

贝恩德
评论会员:海 时间:2011/12/03
您好TonyTonyQ

是有什么办法来过滤所有垃圾邮件从POP3电子邮件?
因为POP3电子邮件客户端阅读包括垃圾邮件从收件箱中的所有电子邮件。
可以指导我如何从POP3电子邮件过滤所有垃圾邮件的电子邮件状态?

预先感谢,


评论会员:devastator789 时间:2011/12/03
使用示例代码:
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"

 

'Add two attachments

mailSend.Attachments.Add(New QMailClient.MailAttachment("C:\sample.jpg"))

mailSend.Attachments.Add(New QMailClient.MailAttachment("C:\test.doc"))

 

Dim mailClient As New QMailClient.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 


改变了服务器的地址,等..它连接的罚款,但调试时得到mailCli​​ent.SendMail(mailSend),并引发一个System.NullReferenceException
评论会员:devastator789 时间:2011/12/03
这是已经在这里找到答案:

现在工作正常
评论会员:。托尼Girgenti 时间:2011/12/03
您好
我下载了这个项目的源文件,但无法找到引言本文所示的DLL文件。
有谁知道如何得到它?


托尼
评论会员:devastator789 时间:2011/12/03
我有完全相同的问题。它说,只是使用的DLL文件,但有没有DLL文件,那么我们怎样才能
评论会员:?托尼Girgenti 时间:2011/12/03
您好devastator

我从未收到这个问题的答案。这是这么久,我忘了我是试图做

对不起,我不能帮你。

托尼
评论会员:游客 时间:2011/12/03
devastator789:源出现编译为一个DLL用VB.net2010Express确定,但它清楚地说,包括使用该DLL。唯一的问题是,我认为这是很容易位:P|ank65
??请帮我
评论会员:dielan主 时间:2011/12/03
我不知道如何使用,当我用你得到的邮件功能它说,一些值不声明,有人请帮我... ... {S0}
评论会员:dielan主 时间:2011/12/03
我不知道如何使用,当我用您的邮件功能,它说,一些值不声明有人请帮助我... ... {S0}
评论会员:Praveen库马尔 时间:2011/12/03
当我收到邮件使用Unicode TXT文件在attachement得到attachement,附件格式成为distruct
任何一个能帮助我

文件的内容,如
/>
评论会员:RezTiNpeaCe 时间:2011/12/03
Try

            MailReceiver.Login()

            MsgBox("succes")

            arr.Clear()

            arr = MailReceiver.GetMailList(True)

            MsgBox("succes" & arr.Count)

            Mail = MailReceiver.RetrieveMail(CType(arr.Item(0), QMailClient.EMail).UniqueID)

            MsgBox("succes Receive")

        Catch ex As Exception

            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        Finally

            MailReceiver.Quit()

        End Try
当我运行此代码
它只是显示"演替"
之后,我得到了长加载
永不落幕的
请纠正我的代码
THX
我用谷歌POP3
SSL端口995
很多THX
评论会员:villamind 时间:2011/12/03
当我试图源,确有错误"HttpUtility不会宣布"

它不能使用的System.Web(进口的System.Web),任何人都可以帮助我对这个问题吗?

我用框架的Visual Studio 2005。NET 2.0。和操作系统Vista的

谢谢的
评论会员:会员3857035 时间:2011/12/03
添加到"System.Web.dll中"的参考。选择的解决方案中的项目
资源管理器,右击它,选择"添加引用..."从上下文菜单中,
选择"。NET"选项卡"System.Web.dll中"
评论会员:。friendprach 时间:2011/12/03
您好,
我从我使用下面的代码应用程序的附件一起发送邮件: -

尝试

DIM ClientPC作为新Net.Mail.SmtpClient(域,港口)
作为新Net.NetworkCredential DIM myAuthentication(MailFrom,密码)
昏暗的发送者邮件地址(MailFrom)
昏暗的接收器作为新的邮件地址及()
ClientPC.UseDefaultCredentials = FALSE
  ; ClientPC.Credentials = myAuthentication
  ; 如果MailFrom.Contains("Gmail的")
ClientPC.EnableSsl = TRUE
最终如果

"sEmail = gvMailContacts.GetRowCellDisplayText(rowno"的ContactID")
&# 160; 作为新MailMessage DIM斯迈尔(发送者,接收者)

sMail.IsBodyHtml = TRUE
sMail.Subject主题=
sMail.Body = MailBody
sMail.ReplyTo =发件人

如果AttachmentPath"
&# 160; 昏暗的重视作为新System.Net.Mail.Attachment(AttachmentPath)
sMail.Attachments.Add(附加)
最终如果

ClientPC.Send(斯迈尔)

返回True
赶上Net.Mail.SmtpException
前 返回False
&# 160; 赶上前为例外
返回False
END TRY
当我retreive我不使用你上面的代码的邮件附件。
附件计数为0时,已发送的邮件,即使邮件attachment.Why是如此有什么改变我sendmail代码
评论会员:??maslopo 时间:2011/12/03
我有同样的问题,你解决了吗?
评论会员:?friendprach 时间:2011/12/03
您好,

我的应用程序发送邮件到users.If用户回复邮件发送我想要得到的邮件的答复。 我的应用程序可以给一个用户发送多个邮件。我已保存通过我的应用程序在我的database.But发送邮件,我怎么能识别用户的邮件发送答复?我可以使用上面的代码中提供的唯一ID?后立即发送邮件,我可以得到的UniqueID这个唯一的ID是相同的,当我们发送邮件时,我们retreive邮件使用上面的代码
评论会员:??friendprach 时间:2011/12/03
您好,
我试图设置我的Gmail ID
但它不能连接到Gmail
我已经给主机名smtp.gmail.com
但仍然斜面连接
如何从Gmail中检索邮件
评论会员:?voellinger 时间:2011/12/03
您好,

我有一个问题SaveToStream方法。
如果我recive邮件是没有问题的邮件保存为流。
当我将派遣一个新的邮件和发送前SaveToStream的方法,我会成为一个错误启动。该方法会错过一些设置??
这里是我的代码:

newMail.To = TextBox_An.Text
newMail.Cc = TextBox_Cc.Text
newMail.Subject = TextBox_Betreff.Text
newMail.Body ="测试"
newMail.From = MAILUSER
 0; newMail.ReplyTo = MAILUSER
newMail.InReplyTo = MAILUSER
newMail.ReturnPath = MAILUSER
newMail.Priority = EMail.MailPriority.Normal
newMail.Header ="

newMail.Bcc ="
......{ BR}
& #160; 昏暗的SM的MemoryStream =新的MemoryStream()

SM = newMail.SaveToStream(FALSE)
DIM bytBLOBData为字节(sm.Length - 1)
sm.Position = 0
sm.Read(0 bytBLOBData,sm.Length)
作为新SQLiteParameter昏暗的PRM("@ BLOBData",bytBLOBData)
 60; cmd.Parameters.Add(PRM)

我战术核武器的邮件保存在数据库befor发送。
有人可以帮助我。
关于
马可波罗
评论会员:会员2873968 时间:2011/12/03
。正是我在寻找

THX
评论会员:khalidys 时间:2011/12/03
我使用的Gmail帐户更改端口995和configration我的帐户,但它GEV我massege登录失败

plz帮助我

上周一,2009年8月24日,日上午08:24
修改
评论会员:RezTiNpeaCe 时间:2011/12/03
不支持SSL
评论会员:Domenican 时间:2011/12/03
主旨!尼斯的工作))

我在您的代码中的一些modificates:

1。受保护的朋友共享功能GetEncodedValueString
有时这个功能删除的电子邮件地址字符串的结束。解决方案:

.....{ BR}如果strValue.IndexOf ("=?") -1
如果SplitBySemicolon = True,则
如果((键="从:")或(键=":"))SourceString.Contains ("<")然后
  ; strReturn = ConvertStringEncodingFromBase64(strValue)";"strValue.Substring(strValue.IndexOf ("<"), strValue.Length - strValue.IndexOf ("<")){ BR} & #160; ELSE
  ; strReturn = ConvertStringEncodingFromBase64(strValue)","
 0; 最终如果
ELSE
如果((键="从:")或(键=":"))SourceString.Contains ("<")然后
 0; strReturn = ConvertStringEncodingFromBase64(strValue)"strValue.Substring(strValue.IndexOf ("<"), strValue.Length - strValue.IndexOf ("<")){ BR}   ;ELSE
 60;strReturn = ConvertStringEncodingFromBase64(strValue)
 0; 最终如果
最终如果
ELSE
strReturn = strValue
最终如果
.....{ BR} Atttachments文件的长文件名不正确提取。 (例如:BLA BLA - bla.15.47382097025 this_file_is long.31.12.2008.doc),因为它的名字保存在源邮件2字符串。解决方案:

1。
保护作为字符串的朋友m_CustomHeader
字串
受保护的朋友m_ReplyTo字串
受保护的朋友m_InReplyTo保护朋友SecondFileNamePart字符串<-----------{ BR}.....{ BR}
(2)
受保护的朋友分SplitBody ....{ BR}.....{ BR}'====解码内容===={ BR}...
如果CT = MailContentType.MessageRFC822然后
attach.m_FileName ="消息"id.Next(1000,9999)。"EML"
ELSE
&# 160;SecondFileNamePart ="
attach.m_FileName = ConvertStringEncodingFromBase64(GetValueString(strContent,"文件",TRUE))
如果SecondFileNamePart""然后attach.m_FileName = attach.m_FileName ConvertStringEncodingFromBase64(SecondFileNamePart)
最终如果
......{ BR}
(3)
受保护的友元函数GetValueString ....{ BR}....{ BR}J = Key.Length"J indecates键字符串的结束索引
如果重点="文件名="
  ; strReturn = SourceString.Substring(J,strSource.IndexOf(vbCrLf,J) - J)。TrimStart.TrimEnd"之前的字符串键和符号的字符串
SecondFileNamePart = SourceString.Substring(j strReturn.Length,strSource.IndexOf("内容传输编码",J strReturn.Length) - J - strReturn.Length)。TrimStart.TrimEnd"之前的字符串键和符号的字符串
ELSE
strReturn = SourceString.Substring(J,strSource.IndexOf(vbCrLf,J) - J)。TrimStart.TrimEnd"之前的字符串键和符号的字符串
最终如果
PS。 cyrilic邮件支持 - 在所有项目上Encoding.Default的变化Encoding.ASCII

PSS / Sory不好英语((
评论会员:alterjo 时间:2011/12/03
。我已接收附件的问题,我收到Outlook中的附件,而不是在VB网(在相同的邮件)

我的代码是这样的:

DIM MailReceiver新POP3Client
DIM arrList作为新的ArrayList
MailReceiver =新POP3Client(CorreoElectronico.ServidorPOP3,CorreoElectronico.Usuario,CorreoElectronico.Contraseña,CorreoElectronico.PuertoPOP3)
MailReceiver.IncreaseNetworkCompatible = TRUE
作为电子邮件DIM MensajesRecibidos()
DIM我为整数

CorreoElectronico.EjecutandoInstrucciones = TRUE

尝试
&# 160; 如果MailReceiver.Login()= false,那么
CorreoElectronico.ComunicacionCorrecta = FALSE
  ; CorreoElectronico.EjecutandoInstrucciones = FALSE
 0;退出小组
最终如果

arrList.Clear()
  ; arrList = MailReceiver.GetMailList()
如果arrList.Count GT; 0
使用ReDim MensajesRecibidos(arrList.Count - 1)
 0; 对于i = 0到arrList.Count - 1
MensajesRecibidos = MailReceiver.RetrieveAndDeleteMail(arrList(I)(I)的UniqueID)
&# 160; "MailReceiver.DeleteMail(arrList(I)的UniqueID)
  ; 接下来,我
&# 160; 最终如果
赶上前为例外
CorreoElectronico.ComunicacionCorrecta = FALSE
 60;最后
MailReceiver.Quit()
END TRY
  ;如果MailReceiver.Statue L​​T,GT; ConnectionState.Closed然后
MailReceiver.CloseForcedly()
最终如果

如果不MensajesRecibidos为Nothing
对于i = 0 MensajesRecibidos.GetLength(0) - 1
如果没有MensajesRecibidos(我)是什么,然后
 60; 对于每个ad​​junto在MensajesRecibidos(I)。附件
& #160; adjunto.SaveToFile(将Application.StartupPath放大器;"/"放大器; adjunto.FileName)
 0; 下一步
& #160; 最终如果

& #160; 接下来,我
最终如果
感谢
评论会员:。 时间:2011/12/03