VB.NET在一个单独的线程中发送电子邮件

时间:2016-04-06 10:23:07

标签: vb.net vb.net-2010

我在vb.net中有一个带有按钮的主窗体,单击该按钮将显示一个包含另一个按钮的Windows对话框。单击对话框中的按钮,我必须发送电子邮件并关闭对话框。

这是问题

电子邮件发送大约需要5到6秒。我需要在发送电子邮件之前关闭对话框。我想把电子邮件发送到一个帖子中。实现这一目标的最佳方法是什么?你能发一个示例代码吗?如果在关闭对话框时线程正在运行会发生什么?

另外,使用背景工作者会更好吗?我不确定线程​​是否是最好的方法。

1 个答案:

答案 0 :(得分:0)

试试这个

 Public Class libMail   

  Private WithEvents bw As New BackgroundWorker

    Public Sub BackgW()
        bw.RunWorkerAsync()
    End Sub

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles bw.DoWork

        SendMail("Subject", "SendingMail")

    End Sub

      Public Shared Function CheckForInternetConnection() As Boolean


        Try
            Return My.Computer.Network.Ping("www.google.com")
        Catch
            Return False
        End Try

    End Function

    Public Function SendMail(subject As String, msg As String) As String
        Try

            Select Case CheckForInternetConnection()
                Case True

                    Dim smtpServer As New SmtpClient
                    Dim eMail As New MailMessage()
                    smtpServer.UseDefaultCredentials = False
                    smtpServer.Credentials = New System.Net.NetworkCredential("YourMail", "yourPassword")
                    smtpServer.Port = 587
                    smtpServer.EnableSsl = True
                    smtpServer.Host = "smtp.gmail.com"


                    eMail = New MailMessage()
                    eMail.From = New MailAddress("yourMail")
                    eMail.To.Add("MailToSend")
                    eMail.Subject = subject

                    eMail.IsBodyHtml = False
                    eMail.Body = msg
                    smtpServer.Send(eMail)

                    Return "SENT"
            End Select
            Return Nothing
        Catch ex As Exception

            Return Nothing
        End Try

    End Function

   Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles bw.RunWorkerCompleted

             'do some work when is over
  End Sub

   End class

'叫它

        Using l As New libMail
            l.BackgW()
            'CLOSE FORM
        End Using