Protected Sub btnLocalSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLocalSubmit.Click
Dim logic = New connections
logic.emailsToSend(User.Identity.Name, getURL, reportedBy)
SendAsync()
Response.Redirect(getRedirectionPath, False)
Catch ex As Exception
Response.Write(ex.Message)
Finally
_con.Close()
_con.Dispose()
_sqlComm.Dispose()
End Try
End Sub
Sub SendAsync()
Dim _con As New SqlConnection(ConfigurationManager.ConnectionStrings("CitizenJDBConnectionString").ConnectionString)
Dim _sqlDataAdapter As New SqlDataAdapter("SELECT * FROM EmailSender", _con)
Dim _table As New System.Data.DataTable
Try
_con.Open()
_sqlDataAdapter.Fill(_table)
_con.Close()
For i As Integer = 0 To _table.Rows.Count - 1
Dim AppPath As String = Request.PhysicalApplicationPath
Dim sr As New StreamReader(AppPath & "EmailTemplates/NewReport.txt")
Dim message As New MailMessage()
message.IsBodyHtml = True
message.From = New MailAddress("admin@xxxx.com")
message.To.Add(New MailAddress(_table.Rows(i).Item(1)))
message.Subject = "New User registration !"
message.Body = sr.ReadToEnd()
sr.Close()
message.Body = message.Body.Replace("<%ReporterName%>", _table.Rows(i).Item(3))
message.Body = message.Body.Replace("<%ReportURL%>", _table.Rows(i).Item(2))
Dim client As New SmtpClient()
client.Host = "smtp.xxxxx.com"
'smtp.gmail.com
client.Port = 25
client.UseDefaultCredentials = True
client.Credentials = New System.Net.NetworkCredential("admin@xxxx.com", "123456")
'client.EnableSsl = True
Dim userState As Object = message
'wire up the event for when the Async send is completed
AddHandler client.SendCompleted, AddressOf SmtpClient_OnCompleted
client.SendAsync(message, userState)
Next
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub 'SendAsync
Public Sub SmtpClient_OnCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
'Get the Original MailMessage object
Dim message As MailMessage = CType(e.UserState, MailMessage)
'write out the subject
Dim subject As String = message.Subject
If e.Cancelled Then
Console.WriteLine("Send canceled for mail with subject [{0}].", subject)
End If
If Not (e.Error Is Nothing) Then
Console.WriteLine("Error {1} occurred when sending mail [{0}] ", subject, e.Error.ToString())
Else
Console.WriteLine("Message [{0}] sent.", subject)
End If
End Sub 'SmtpClient_OnCompleted
我正在使用smtp客户端SendAsync()
函数异步发送电子邮件...但是这个功能不起作用......为什么?我没有收到任何电子邮件..当我发送它同步...我收到电子邮件,这意味着我的设置是正确的...所以SendAsync()
方法有什么问题?
答案 0 :(得分:0)
我一直这样做,经过多年的努力,我建议(2)解决你的问题:
您可能会说您需要知道发送电子邮件是否出错。让发送电子邮件的WCF服务处理此问题。进行任何登录服务。毕竟你正在做的就是记录。如果您在电子邮件失败时需要更好地使用工作流程,那么可以通过多种方式标记您的ASP.NET,但我认为您会发现,一旦发送电子邮件的服务稳定,您就会遇到很少的问题。
事实上,多年来我一直在使用ASP.NET调用的服务来发送电子邮件并发送了数以千计的不同电子邮件,并且从未遇到过这种即发即弃设计的任何问题。
最后,通过阻止主线程直到所有异步过程完成,设置页面Async=True
最终使页面整体同步。这可能使页面加载速度非常慢,通常不需要。