/// <summary> /// 发送邮件,如果发送过程出现错误则会抛出异常 /// </summary> /// <param name="message">邮件内容</param> public void Send(MailMessage message) { if (this.Server.UseLocalService) //采用本地邮件服务 { if (message.To.Count < 1) { return; } Exception ex = null; try { string[] mailMX = DnsMxRecord.Query(message.To[0]); if (mailMX != null) { this.BeforeLocalSend(message); foreach (string mx in mailMX) { //构造SMTP的连接器 SmtpClient smtp = this.GetSmtpClient(mx, MailServer.DefaultPort); try { smtp.Send(message); ex = null; break; } catch (Exception e) { ex = e; } } } } catch { } //如果没有发送成功.则抛出最后一个错误 if (ex != null) { throw ex; } } else { //构造SMTP的连接器 SmtpClient smtp = this.GetSmtpClient(this.Server.HostName, this.Server.Port); smtp.Send(message); } }
/// <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); } }