public void Dispose() { //释放操作是将一个释放对象放入发送队列,然后当处理到该对象时进行真正的释放操作 var dispEntity = PostEntity.CreateDisposedEntity(this._client); _messages.Enqueue(dispEntity); }
static void Timer_TimeoutEvent(Object sender, EventArgs e) { for (var i = 0; i < BatchSendSize; i++) { PostEntity entity = null; if (_messages.TryDequeue(out entity)) { if (entity.PrepareToDispose) { entity.SmtpClient.Dispose(); return; } try { entity.SmtpClient.Send(entity.Message); } catch (Exception ex) { throw ex; } } } }
/// <summary> /// 执行发送邮件操作。 /// </summary> /// <param name="mailBody">邮件正文</param> /// <param name="mainTitle">邮件标题</param> /// <param name="bodyIsHtml">设置正文是否为HTML格式内容</param> /// <param name="attachments">设置附件</param> public void SendMail(String mailBody, String mainTitle, Boolean bodyIsHtml = false, Attachment[] attachments = null) { MailMessage msg = new MailMessage() { From = this._mainAccount, Body = mailBody, BodyEncoding = Encoding.UTF8, Subject = mainTitle, SubjectEncoding = Encoding.UTF8, IsBodyHtml = bodyIsHtml }; #region #设置抄送 if (attachments != null && attachments.Length > 0) { foreach (var atm in attachments) { msg.Attachments.Add(atm); } } if (this._receiveAccounts != null && this._receiveAccounts.Length > 0) { foreach (var ac in this._receiveAccounts) { msg.To.Add(ac); } } if (this._bccAccounts != null && this._bccAccounts.Length > 0) { foreach (var bcc in this._bccAccounts) { msg.Bcc.Add(bcc); } } if (this._ccAccounts != null && this._ccAccounts.Length > 0) { foreach (var cc in this._ccAccounts) { msg.CC.Add(cc); } } #endregion var entity = new PostEntity(this._client, msg); //如果已经存在相同的邮件,则不添加到邮件队列 if (_messages.Count(x => x.Key == entity.Key) > 0) { return; } //否则将邮件添加到队列 _messages.Enqueue(entity); }