/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MailSendCompleted(object sender, AsyncCompletedEventArgs e) { SmtpClient client = sender as SmtpClient; if (client != null) { client.SendCompleted -= MailSendCompleted; } object userToken = e.UserState; SendCompletedToken token = e.UserState as SendCompletedToken; if (token != null) { userToken = token.UserToken; } if (e.Error != null && !e.Cancelled && token != null) { if ((++token.Index) < token.MxRecords.Length) { //继续连接下一个MX Record SmtpClient smtp = this.GetSmtpClient(token.MxRecords[token.Index], token.Port); smtp.SendCompleted += MailSendCompleted; smtp.SendAsync(token.Message, token); return; } } AsyncCompletedEventArgs args = new AsyncCompletedEventArgs(e.Error, e.Cancelled, userToken); if (this.SendCompleted != null) { this.SendCompleted(sender, args); } }
/// <summary> /// 异步发送邮件,如果发送过程出现错误则会抛出异常 /// </summary> /// <param name="message">邮件内容</param> /// <param name="userToken">一个用户定义对象,此对象将被传递给完成异步操作时所调用的方法。</param> public void SendAsync(MailMessage message, object userToken) { if (this.Server.UseLocalService) //采用本地邮件服务 { if (message.To.Count < 1) { return; } try { string[] mailMX = DnsMxRecord.Query(message.To[0]); if (mailMX != null && mailMX.Length > 0) { this.BeforeLocalSend(message); SendCompletedToken token = new SendCompletedToken() { MxRecords = mailMX, Index = 0, Port = MailServer.DefaultPort, Message = message, UserToken = userToken }; //构造SMTP的连接器 SmtpClient smtp = this.GetSmtpClient(mailMX[token.Index], token.Port); smtp.SendCompleted += MailSendCompleted; smtp.SendAsync(message, token); } } catch { } } else { //构造SMTP的连接器 SmtpClient smtp = this.GetSmtpClient(this.Server.HostName, this.Server.Port); smtp.SendCompleted += this.SendCompleted; smtp.SendAsync(message, userToken); } }