使用System.Net.Mail命名空间

时间:2017-04-05 07:53:02

标签: vb.net smtp

这是我在调用Me.Close()时遇到的错误:

enter image description here

这是我的代码:

Imports System.Net.Mail
Imports System.IO

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Dim mail As New MailMessage()
            Dim SmtpServer As New SmtpClient("smtp.gmail.com")
            mail.From = New MailAddress("your email@domain.com")
            mail.[To].Add("to@domain.com")
            mail.Subject = "Trial"
            mail.Body = "Trial"


            Dim path As String = "C:\Users\CrystalUser\Desktop\trial"
            Dim dir As New DirectoryInfo(path)
            Dim filesInDirectory As FileInfo() = dir.GetFiles()
            Dim attach As System.Net.Mail.Attachment
            For Each file In filesInDirectory
                attach = New System.Net.Mail.Attachment(file.FullName)
                mail.Attachments.Add(attach)
            Next


            SmtpServer.Port = 587
            SmtpServer.Credentials = New System.Net.NetworkCredential("username", "password")
            SmtpServer.EnableSsl = True

            SmtpServer.Send(mail)
            MsgBox("Sent Successfuly", MsgBoxStyle.Information, "Send")

        Catch alvin As Exception
            MessageBox.Show(alvin.Message)
        End Try
        Me.Close()

    End Sub

End Class

我希望程序在发送MailMessage后自动关闭。

我使用了Me.Hide()Me.Close(),但都没有用。

1 个答案:

答案 0 :(得分:0)

虽然您的错误不太清楚且此答案可能无法解决您的问题,但在UsingMailMessageSmtpClient类上实施Attachment是明智的:< / p>

  

有时,您的代码需要非托管资源,例如文件句柄,COM包装器或SQL连接。使用块可确保在代码完成后处理一个或多个此类资源。这使得它们可供其他代码使用。

在使用.GetFiles()时,我还会考虑减少一些不必要的代码。

代码:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Try
        Using mail As New MailMessage("your email@domain.com", "to@domain.com", "Trial", "Trial"),
              smtpServer As New SmtpClient("smtp.gmail.com", 587)

            Dim filesInDirectory As FileInfo() = New DirectoryInfo("C:\Users\CrystalUser\Desktop\trial").GetFiles()
            For Each file In filesInDirectory
                Using attach As New Attachment(file.FullName)
                    mail.Attachments.Add(attach)
                End Using
            Next

            smtpServer.Credentials = New System.Net.NetworkCredential("username", "password")
            smtpServer.EnableSsl = True

            smtpServer.Send(mail)

            MessageBox.Show("Mail sent")
        End Using
    Catch alvin As Exception
        MessageBox.Show(alvin.Message)
    End Try

    Me.Close()

End Sub

实施Using的目的是在完成后正确处理对象。如果发生任何错误,在输入Catch语句之前,对象也将被丢弃。

放手一搏让我知道你是怎么过的。