在VB.Net中使用IMAP从MS Exchange Server检索邮件 [英] Using IMAP in VB.Net to retrieve Mails from MS Exchange Server

查看:70
本文介绍了在VB.Net中使用IMAP从MS Exchange Server检索邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我指的是过去某处的前一篇文章(请参阅超链接).我无法添加任何评论,也没有考虑写答复,因为我的问题略有不同.请原谅,如果我在错误的部分发帖,或者在这个主题上打开新话题,我仍然是这个论坛的新手.

I am referring to a previous post somewhere in the past (cf. Hyperlink). I could not add any comments, nor did I consider writing a reply since my Problem differs slightly. Please excuse if I posted in the wrong section or for opening a new thread on this topic, I am still new to this Forum.

请让我说明以下问题:与此

Please let me illustrate the following issue: Similar to this post, I would like to access and retrieve emails and attachments from a MS Exchange Server. I mainly used the code provided by in the Hyperlink above, but I could not connect to the mail Server (I used port 587). In my opinion there was a successful Connection, but the code stops when reaching the following line

Dim Read_Stream2 = New StreamReader(Sstream)

说无法读取数据流.

我也有关于此特定行的问题,因为我无法弄清楚为什么需要将NetworkStream转换为SslStream,然后转换为StreamReader对象.有人可以解释一下这种必要性吗?

I also have a question about this particular line, since I am unable to figure out why there is need to convert the NetworkStream into an SslStream and then into a StreamReader Object. Could somebody please explain this necessity?

关于剩下的问题,请考虑下面的代码.如果使用IMAP可能太麻烦,我也欢迎您提供有关如何使用POP3实现此目标的提示.预先感谢您提供的任何帮助.

As for the remaining Problem, please consider my code so far below. If it might be too cumbersome using IMAP, I would also welcome hints about how to achieve this goal using POP3. Thanks a mil in advance for any help provided.

Imports System.Net.Sockets
Imports System.IO
Imports System.Text
Imports System.Net.Security

Public Class emailDownloader

Dim ServerNm As String
Dim UsrNm As String
Dim PassStr As String
Dim _IntPort As Integer
Dim ImapClient As New Net.Sockets.TcpClient
Dim NetworkS_stream As NetworkStream
Dim m_sslStream As SslStream
Dim Read_Stream As StreamReader
Dim StatResp As String
Dim m_buffer() As Byte

Function Login(ByVal Sstream As SslStream, ByVal Server_Command As String)
    ImapClient = New TcpClient(ServerNm, _IntPort)
    NetworkS_stream = ImapClient.GetStream 'Read the stream

    Sstream = New SslStream(NetworkS_stream)

    Dim Read_Stream2 = New StreamReader(Sstream)
    Server_Command = Server_Command ' + vbCrLf
    m_buffer = System.Text.Encoding.ASCII.GetBytes(Server_Command.ToCharArray())
    Sstream.Write(m_buffer, 0, m_buffer.Length)
    Dim Server_Reponse As String
    Server_Reponse = Read_Stream2.ReadLine()
    Return Server_Reponse

End Function

Private Sub btnStart_Click(sender As System.Object, e As System.EventArgs) Handles btnStart.Click
    lbMailsRetrieved.Items.Clear()
    ServerNm = tbServerName.Text
    _IntPort = tbPortName.Text
    UsrNm = tbUserName.Text
    PassStr = tbPasswort.Text
    StatResp = Login(m_sslStream, "LOGIN " + UsrNm + " " + PassStr + " ") & vbCrLf
    lbMailsRetrieved.Items.Add(StatResp)
End Sub

结束班级

有一个最初使用C#编程的解决方案,可以在

There was a solution initially programmed in C#, which can be found here. I modified the code a bit and it is working for exchange (and only that).

Imports Microsoft.Exchange.WebServices.Data
Imports System.Collections.Generic
Imports System.ComponentModel  
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows.Forms


Namespace ReadMailFromExchangeServer

Public Class Form1
    Inherits Form
    Private exchange As ExchangeService

    Public Sub New()
        InitializeComponent()
        lstMsg.Clear()
        lstMsg.View = View.Details
        lstMsg.Columns.Add("Date", 150)
        lstMsg.Columns.Add("From", 250)
        lstMsg.Columns.Add("Subject", 400)
        lstMsg.Columns.Add("Has Attachment", 50)
        lstMsg.Columns.Add("Id", 100)

        lstMsg.FullRowSelect = True
    End Sub

    Private Sub btnRead_Click(sender As Object, e As EventArgs) Handles btnRead.Click
        ConnectToExchangeServer()
        'Dim ts As New TimeSpan(0, -1, 0, 0)
        'Dim [date] As DateTime = DateTime.Now.Add(ts)
        'Dim filter As New SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, [date])

        If exchange IsNot Nothing Then
            Dim findResults As FindItemsResults(Of Item) = exchange.FindItems(WellKnownFolderName.Inbox, New ItemView(50))
            'Original
            'Dim findResults As FindItemsResults(Of Item) = exchange.FindItems(WellKnownFolderName.Inbox, filter, New ItemView(50))
            For Each item As Item In findResults

                Dim message As EmailMessage = EmailMessage.Bind(exchange, item.Id)
                Dim listItem As New ListViewItem({message.DateTimeReceived.ToString(), _
                                         message.From.Name.ToString() + _
                                         "(" + message.From.Address.ToString() + ")", _
                                         message.Subject, (If((message.HasAttachments), "Yes", "No")), _
                                         message.Id.ToString()})
                lstMsg.Items.Add(listItem)
            Next
            If findResults.Items.Count <= 0 Then

                lstMsg.Items.Add("No Messages found!!")
            End If
        End If

    End Sub

    Public Sub ConnectToExchangeServer()

        lblMsg.Text = "Connecting to Exchange Server.."
        lblMsg.Refresh()
        Try
            exchange = New ExchangeService(ExchangeVersion.Exchange2007_SP1)
            exchange.Credentials = New WebCredentials("abc", "xyz")
            exchange.AutodiscoverUrl("efg")

            lblMsg.Text = "Connected to Exchange Server : " + exchange.Url.Host

            lblMsg.Refresh()
        Catch ex As Exception
            lblMsg.Text = "Error Connecting to Exchange Server!!" + ex.Message
            lblMsg.Refresh()
        End Try

    End Sub

    Private Sub btnLoadAttachment_Click(sender As Object, e As EventArgs) Handles btnLoadAttachment.Click
        If exchange IsNot Nothing Then
            If lstMsg.Items.Count > 0 Then
                Dim item As ListViewItem = lstMsg.SelectedItems(0)

                If item IsNot Nothing Then
                    Dim msgid As String = item.SubItems(4).Text.ToString()
                    Dim message As EmailMessage = EmailMessage.Bind(exchange, New ItemId(msgid))
                    If message.HasAttachments AndAlso TypeOf message.Attachments(0) Is FileAttachment Then
                        Dim fileAttachment As FileAttachment = TryCast(message.Attachments(0), FileAttachment)
                        'Change the below Path    
                        fileAttachment.Load("C:[my_path]" + fileAttachment.Name)
                        lblAttach.Text = "Attachment Downloaded : " + fileAttachment.Name
                    Else
                        MessageBox.Show("No Attachments found!!")
                    End If
                Else
                    MessageBox.Show("Please select a Message!!")
                End If
            Else
                MessageBox.Show("Messages not loaded!!")

            End If
        Else
            MessageBox.Show("Not Connected to Mail Server!!")
        End If
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs)

    End Sub


    Private Sub InitializeComponent()
        Me.btnRead = New System.Windows.Forms.Button()
        Me.lstMsg = New System.Windows.Forms.ListView()
        Me.btnLoadAttachment = New System.Windows.Forms.Button()
        Me.lblMsg = New System.Windows.Forms.Label()
        Me.label1 = New System.Windows.Forms.Label()
        Me.lblAttach = New System.Windows.Forms.Label()
        Me.SuspendLayout()
        '
        'btnRead
        '
        Me.btnRead.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None
        Me.btnRead.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.btnRead.Location = New System.Drawing.Point(39, 284)
        Me.btnRead.Name = "btnRead"
        Me.btnRead.Size = New System.Drawing.Size(174, 23)
        Me.btnRead.TabIndex = 0
        Me.btnRead.Text = "Read Mails"
        Me.btnRead.UseVisualStyleBackColor = True
        '
        'lstMsg
        '
        Me.lstMsg.Location = New System.Drawing.Point(27, 70)
        Me.lstMsg.Name = "lstMsg"
        Me.lstMsg.Size = New System.Drawing.Size(664, 191)
        Me.lstMsg.TabIndex = 1
        Me.lstMsg.UseCompatibleStateImageBehavior = False
        '
        'btnLoadAttachment
        '
        Me.btnLoadAttachment.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btnLoadAttachment.Location = New System.Drawing.Point(517, 284)
        Me.btnLoadAttachment.Name = "btnLoadAttachment"
        Me.btnLoadAttachment.Size = New System.Drawing.Size(174, 23)
        Me.btnLoadAttachment.TabIndex = 2
        Me.btnLoadAttachment.Text = "Load Attachments"
        Me.btnLoadAttachment.UseVisualStyleBackColor = True
        '
        'lblMsg
        '
        Me.lblMsg.AutoSize = True
        Me.lblMsg.Location = New System.Drawing.Point(36, 361)
        Me.lblMsg.Name = "lblMsg"
        Me.lblMsg.Size = New System.Drawing.Size(38, 13)
        Me.lblMsg.TabIndex = 3
        Me.lblMsg.Text = "Ready"
        '
        'label1
        '
        Me.label1.AutoSize = True
        Me.label1.Location = New System.Drawing.Point(24, 54)
        Me.label1.Name = "label1"
        Me.label1.Size = New System.Drawing.Size(82, 13)
        Me.label1.TabIndex = 4
        Me.label1.Text = "Today's Messages"
        '
        'lblAttach
        '
        Me.lblAttach.AutoSize = True
        Me.lblAttach.Location = New System.Drawing.Point(514, 361)
        Me.lblAttach.Name = "lblAttach"
        Me.lblAttach.Size = New System.Drawing.Size(148, 13)
        Me.lblAttach.TabIndex = 5
        Me.lblAttach.Text = "No attachmment downloaded"
        '
        'Form1
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(812, 591)
        Me.Controls.Add(Me.lblAttach)
        Me.Controls.Add(Me.label1)
        Me.Controls.Add(Me.lblMsg)
        Me.Controls.Add(Me.btnLoadAttachment)
        Me.Controls.Add(Me.lstMsg)
        Me.Controls.Add(Me.btnRead)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub
    Friend WithEvents btnRead As System.Windows.Forms.Button
    Friend WithEvents lstMsg As System.Windows.Forms.ListView
    Friend WithEvents btnLoadAttachment As System.Windows.Forms.Button
    Friend WithEvents lblMsg As System.Windows.Forms.Label
    Friend WithEvents label1 As System.Windows.Forms.Label
    Friend WithEvents lblAttach As System.Windows.Forms.Label
End Class

结束命名空间

推荐答案

对于开头所述的问题,当前代码提供了一种解决方案.因此,我想标记这是一个答案并关闭此线程(我知道,通常不应将自己的答案标记为答案).希望这种方法可以.

For the issue described in the beginning, the present code provides a solution. Thus I would like to mark this is an answer and close this thread (I know, usually one should not mark their very own answer as answer). Hope this approach is ok.

这篇关于在VB.Net中使用IMAP从MS Exchange Server检索邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆