我有一个场景,我需要一次发送 100 封电子邮件(使用循环),但我也不允许每个 SMTP 会话发送 1 封电子邮件。
现在所有 100 封电子邮件都共享同一个 SMTP 会话。
我在想调用 SmtpClient.Dispose() 会照顾我需要的东西。如果我错了,请纠正我。
所以,基本上3个问题:
- SmtpClient.Dispose() 会照顾我需要的东西吗?
- 如果是,在不影响服务器上其他服务的情况下 Dispose() SmtpClient 是否安全?
- 如果否,实现我想要的正确方法是什么?
示例代码:
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