2

我有一个场景,我需要一次发送 100 封电子邮件(使用循环),但我也不允许每个 SMTP 会话发送 1 封电子邮件。

现在所有 100 封电子邮件都共享同一个 SMTP 会话。

我在想调用 SmtpClient.Dispose() 会照顾我需要的东西。如果我错了,请纠正我。

所以,基本上3个问题:

  1. SmtpClient.Dispose() 会照顾我需要的东西吗?
  2. 如果是,在不影响服务器上其他服务的情况下 Dispose() SmtpClient 是否安全?
  3. 如果否,实现我想要的正确方法是什么?

示例代码:

Private Shared Sub SendMail(ByVal MailServer As SmtpClient, ByVal body As String, ByVal Subject As String, ByVal FromEmail As String, _
                               ByVal ToEmailList As String, Optional ByVal AttFile As Attachment = Nothing)

    Dim message As New MailMessage

    Try
        message.From = New MailAddress(FromEmail)

        message.Subject = Subject
        message.IsBodyHtml = False
        message.Body = body
        message.Priority = MailPriority.High

        If Not AttFile Is Nothing Then
            message.Attachments.Add(AttFile)
        Else
            message.Attachments.Add(AttFile)
        End If

        MailServer.Send(message)
    Catch ex As Exception
        Throw New ApplicationException("SERVICE1.SendMail ERROR -- Error sending email [ERROR]:[" & ex.Message.ToString & "] " & vbCrLf & "To:" & ToEmailList & vbCrLf & "From:" & FromEmail & vbCrLf & "Subject: " & Subject & vbCrLf & "Body: " & body)
    End Try
    message.Dispose()
End Sub

这就是该方法的执行方式:

 For Each Item In ItemListCollection
 m_MailServer = New SmtpClient(MailServerName)
 MailServer.Credentials = New System.Net.NetworkCredential(MailServerUserName, MailServerPassword)
 SendMail(WeeklyMailServer, msgBody, msgSubject, MsgFromEmail, "xyz@abc.com", rptAttachment)
 Next
4

2 回答 2

3

您可以将其包装在 using 语句中,并确保在执行离开块时将其处理掉。您可以使用同一个 SmtpClient 在一个循环中多次调用 Send。

Using client = New SmtpClient()

    For i As Integer = 0 To 99
        Dim message = New MailMessage()
        'initialization of whatever is needed
        ' message creation

        client.Send(message)

    Next
End Using
于 2013-01-17T23:01:54.233 回答
1

在执行循环内部,您可以将代码包含在一个Using块中。这将为每封电子邮件使用单独smtpclient的电子邮件,并正确处理/关闭它。

 For Each Item In ItemListCollection
   using m_MailServer as New SmtpClient(MailServerName)
     MailServer.Credentials = New System.Net.NetworkCredential(MailServerUserName, MailServerPassword)
     SendMail(WeeklyMailServer, msgBody, msgSubject, MsgFromEmail, "xyz@abc.com", rptAttachment)
   end using
   Next
于 2013-01-17T23:47:15.803 回答