在 vb.net 中使用 pop3 从 gmail 服务器检索电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21548893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve email from gmail server using pop3 in vb.net
提问by user3153806
Public Class Pop3
Inherits Sockets.TcpClient
Dim Stream As Sockets.NetworkStream
Dim UsesSSL As Boolean = False
Dim SslStream As Security.SslStream
Dim SslStreamDisposed As Boolean = False
Public LastLineRead As String = vbNullString
Public Overloads Sub Connect(ByVal server As String, _
ByVal username As String, _
ByVal password As String, _
Optional ByVal inport As Integer = 110, _
Optional ByVal usessl As Boolean = False)
If Connected Then disconnect()
UsesSSL = usessl
MyBase.Connect(server, inport)
Stream = MyBase.GetStream()
If UsesSSL Then
SslStream = New Security.SslStream(Stream)
SslStream.AuthenticateAsClient(server)
End If
If Not checkresponse() Then Exit Sub
If CBool(Len(username)) Then
Me.Submit("user" & username & vbCrLf)
If Not checkresponse() Then Exit Sub
End If
If CBool(Len(password)) Then
Me.Submit("pass" & password & vbCrLf)
If Not checkresponse() Then Exit Sub
End If
End Sub
Public Function checkresponse() As Boolean
If Not IsConnected() Then Return False
LastLineRead = Me.Response
If (Left(LastLineRead, 3) <> "+ok") Then
Throw New POP3Exception(LastLineRead)
Return False
End If
Return True
End Function
Public Function IsConnected() As Boolean
If Not Connected Then
Throw New POP3Exception("Not Connected to an Pop3 Server")
Return False
End If
Return True
End Function
Public Function Response(Optional ByVal datasize As Integer = 1) As String
Dim enc As New ASCIIEncoding
Dim serverbufr() As Byte
Dim index As Integer = 0
If datasize > 1 Then
ReDim serverbufr(datasize - 1)
Dim dtsz As Integer = datasize
Dim sz As Integer
Do While index < datasize
If UsesSSL Then
sz = SslStream.Read(serverbufr, index, dtsz)
Else
sz = Stream.Read(serverbufr, index, dtsz)
End If
If sz = 0 Then Return vbNullString
index += sz
dtsz -= sz
Loop
Else
ReDim serverbufr(255)
Do
If UsesSSL Then
serverbufr(index) = CByte(SslStream.ReadByte)
Else
serverbufr(index) = CByte(Stream.ReadByte)
End If
If serverbufr(index) = -1 Then Exit Do
index += 1
If serverbufr(index - 1) = 10 Then Exit Do
If index > UBound(serverbufr) Then
ReDim Preserve serverbufr(index + 256)
End If
Loop
End If
Return enc.GetString(serverbufr, 0, index)
End Function
Public Sub Submit(ByVal message As String)
Dim enc As New ASCIIEncoding
Dim WriteBuffer() As Byte = enc.GetBytes(message)
If UsesSSL Then
SslStream.Write(WriteBuffer, 0, WriteBuffer.Length)
Else
Stream.Write(WriteBuffer, 0, WriteBuffer.Length)
End If
End Sub
Public Sub disconnect()
Me.Submit("QUIT" & vbCrLf)
checkresponse()
If UsesSSL Then
SslStream.Dispose()
SslStreamDisposed = True
End If
End Sub
Public Function statistics() As Integer()
If Not IsConnected() Then Return Nothing
Me.Submit("STAT" & vbCrLf)
LastLineRead = Me.Response
If (Left(LastLineRead, 3) <> "+OK") Then
Throw New POP3Exception(LastLineRead)
Return Nothing
End If
Dim msgInfo() As String = Split(LastLineRead, " "c)
Dim result(1) As Integer
result(0) = Integer.Parse(msgInfo(1))
result(1) = Integer.Parse(msgInfo(2))
Return result
End Function
Public Function List() As ArrayList
If Not IsConnected() Then Return Nothing
Me.Submit("LIST" & vbCrLf)
If Not checkresponse() Then Return Nothing
Dim retval As New ArrayList
Do
Dim response As String = Me.Response
If (response = "." & vbCrLf) Then
Exit Do
End If
Dim msg As New Pop3Message
Dim msgInfo() As String = Split(response, " "c)
msg.number = Integer.Parse(msgInfo(0))
msg.bytes = Integer.Parse(msgInfo(1))
msg.Retrieved = False
retval.Add(msg)
Loop
Return retval
End Function
Public Function GetHeader(ByRef msg As Pop3Message, Optional ByVal BodyLines As Integer = 0) As Pop3Message
If Not IsConnected() Then Return Nothing
Me.Submit("TOP " & msg.number.ToString & " " & BodyLines.ToString & vbCrLf)
If Not checkresponse() Then Return Nothing
msg.Message = vbNullString
Do
Dim response As String = Me.Response
If response = "." & vbCrLf Then
Exit Do
End If
msg.Message &= response
Loop
Return msg
End Function
Public Function Retrieve(ByRef msg As Pop3Message) As Pop3Message
If Not IsConnected() Then Return Nothing
Me.Submit("RETR " & msg.number.ToString & vbCrLf)
If Not checkresponse() Then Return Nothing
msg.Message = Me.Response(msg.bytes)
Do
Dim S As String = Response()
If S = "." & vbCrLf Then
Exit Do
End If
msg.Message &= S
Loop
msg.bytes = Len(msg.Message)
Return msg
End Function
Public Sub Delete(ByVal msgHdr As Pop3Message)
If Not IsConnected() Then Exit Sub
Me.Submit("DELE " & msgHdr.number.ToString & vbCrLf)
checkresponse()
End Sub
Public Sub reset()
If Not IsConnected() Then Exit Sub
Me.Submit("RSET" & vbCrLf)
checkresponse()
End Sub
Public Function noop() As Boolean
If Not IsConnected() Then Return False
Me.Submit("NOOP")
Return checkresponse()
End Function
Protected Overrides Sub Finalize()
If SslStream IsNot Nothing AndAlso Not SslStreamDisposed Then
SslStream.Dispose()
End If
MyBase.Finalize()
End Sub
Public Function ReadPop3(ByVal Server As String, _
ByVal username As String, _
ByVal password As String, _
Optional ByVal Inport As Integer = 110, _
Optional ByVal usessl As Boolean = False) As ArrayList
Try
Dim inmail As New Pop3
inmail.Connect(Server, username, password, Inport, usessl)
Dim stats() As Integer = inmail.statistics()
If stats(0) = 0 Then
Return Nothing
End If
Dim locallist As New ArrayList
For Each msg As Pop3Message In inmail.List
locallist.Add(inmail.Retrieve(msg))
Next
inmail.disconnect()
Return locallist
Catch ex As POP3Exception
MsgBox(ex.Message, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error Encounted")
Catch e As Exception
MsgBox(e.Message, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error Encounted")
End Try
Return Nothing
End Function
End Class
Public Class Pop3Message
Public MailID As Integer = 0
Public ByteCount As Integer = 0
Public number As Integer = 0
Public bytes As Integer = 0
Public Retrieved As Boolean = False
Public Message As String = vbNullString
Public Overrides Function ToString() As String
Return Message
End Function
End Class
Public Class POP3Exception
Inherits ApplicationException
Public Sub New(ByVal str As String)
MyBase.New(str)
End Sub
End Class
.................................................
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Button1.Enabled = False
Dim emailbag As ArrayList = getmail.ReadPop3("Pop.gmail.com", "[email protected]", "shan1986", 995, True)
If emailbag IsNot Nothing AndAlso emailbag.Count <> 0 Then
For Each msg As Pop3Message In emailbag
Me.TextBox1.Text = msg.Message
MsgBox(msg.Message, MsgBoxStyle.OkOnly, "message #" & msg.MailID.ToString & " of " & emailbag.Count.ToString)
Next
Else
MsgBox("no Email found on server ", MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "No email")
End If
Me.Button1.Enabled = True
End Sub
her i want to get mail from gmail server using pop3 if mail found then display each email stuff in textbox and display each message in messagebox but while debugging no errors there was exception ---exception of type 'test application' pop3 exception was thrown.Myproblem is i have many emails in my gmailaccount but not able to retrieve those emails and click event will process else condition and it show an message box that no emails found on server.
如果找到邮件,我想使用 pop3 从 gmail 服务器获取邮件,然后在文本框中显示每个电子邮件内容并在消息框中显示每条消息,但是在调试没有错误时出现异常 --- 抛出了“测试应用程序”类型的异常 pop3 异常。我的问题是我的 gmailaccount 中有很多电子邮件,但无法检索这些电子邮件,单击事件将处理其他条件,并显示一个消息框,在服务器上找不到电子邮件。
somebody help on this issue .thanks in advance
有人帮助解决这个问题。提前致谢
回答by Tino Fourie
First off, if you bothered to read David Ross Goben's PDF document, since the code you have posted is 100% his (apart from the comments you have removed), you would have noticed that providers like GMail, Yahoo and Hotmail all require SSL.
首先,如果您费心阅读 David Ross Goben 的 PDF 文档,因为您发布的代码 100% 是他的(除了您已删除的评论),您会注意到 GMail、Yahoo 和 Hotmail 等提供商都需要 SSL。
Secondly, you can always send a message to David R Goben on his Gmail address (as listed in the PDF document you got with his .NetEMail classes), I am sure he will be happy to know about your problem and how you go about posting his code without crediting him.
其次,您可以随时通过他的 Gmail 地址向 David R Goben 发送消息(如您在他的 .NetEMail 类中获得的 PDF 文档中所列),我相信他会很高兴知道您的问题以及您如何发帖他的代码没有归功于他。
Lastly, if you left in the code comments (as David R Goben had it originally) other members could understand the code better without thinking about it.
最后,如果您留在代码注释中(正如 David R Goben 最初所说的那样),其他成员无需考虑就可以更好地理解代码。
Getting back to your problem.
回到你的问题。
There is a chance that the messages on the GMail server is already flagged as "Read" which could mean that these messages will not show up when you do a POP3.list.
GMail 服务器上的邮件可能已被标记为“已读”,这可能意味着在您执行 POP3.list 时这些邮件不会显示。
Best is to use the POP3.Statistics to see if there are in fact messages to be downloaded.
最好是使用 POP3.Statistics 来查看是否有实际的邮件要下载。
In the event that the POP3.List returns a list of messages, you can fetch messages based on the values in the list since the List holds the UID of each message.
如果 POP3.List 返回一个消息列表,您可以根据列表中的值获取消息,因为 List 保存着每条消息的 UID。
Another option is to stop reading your mail and allow your program to do either a POP3.Statistics and / or POP3.List to determine if there are any messages on the server.
另一种选择是停止阅读您的邮件并允许您的程序执行 POP3.Statistics 和/或 POP3.List 以确定服务器上是否有任何邮件。
**Next time credit people for the time and effort they have put into providing you with code that you can use to your own benefit.
** 下次感谢人们为您提供的代码所付出的时间和精力,您可以利用这些代码为自己谋取利益。

