/// <summary> /// Send general email, fully configurable. /// </summary> /// <returns></returns> public static bool SendEmailAsync(string username, string password, string smtpServer, int port, string from, string to, string subject, string body, SendCompletedEventHandler handler) { SmtpClient client = new SmtpClient(smtpServer, port); client.EnableSsl = true; client.Credentials = new System.Net.NetworkCredential(username, password); MailMessage message = new MailMessage(from, to); message.Body = body; message.Subject = subject; try { client.SendAsync(message, null); if (handler != null) { client.SendCompleted += handler; } } catch (Exception ex) { SystemMonitor.OperationError("Failed to send mail.", ex); return false; } return true; }
private SendCompletedEventHandler GetOnSendCompleted(MailMessage message, SendCompletedEventHandler sendCompleted) { SendCompletedEventHandler handler = (sender, e) => { var retryUserState = (RetryUserState)e.UserState; var countDown = retryUserState.CountDown; if (e.Error != null && --countDown > 0) { Thread.Sleep(3000); retryUserState.CountDown = countDown; _decorated.Deliver(message, null, retryUserState); } else if (sendCompleted != null) { if (e.Error != null) { var error = new Error(e.Error); var log = ErrorLog.GetDefault(HttpContext.Current); log.Log(error); } sendCompleted(sender, new AsyncCompletedEventArgs(e.Error, e.Cancelled, retryUserState.UserState)); } }; return handler; }
/// <summary> /// Envia e-mial usando os paramteros passoa por mailMessage /// com a possibilidade de chamada a evento apos o envio /// </summary> /// <param name="mailMesasge">e-mail a ser enviado</param> /// <param name="sendCompleted">evento vinculado a ser disparado ao terminio do envio</param> public static void Send(MailMessage mailMesasge, SendCompletedEventHandler sendCompleted) { bool ambienteOficial = Convert.ToBoolean( ConfigurationManager.AppSettings["AmbienteOficial"] ); if (!ambienteOficial) { mailMesasge.To.Clear();//Limpa os receptores da mensagen //obtem os usuarios receptores em anbiente de teste string mails = ConfigurationManager.AppSettings["MailErro"]; if(!string.IsNullOrEmpty(mails)) { //Configurar o envio para os receptores de anbiente de teste foreach (string mail in mails.Split(';')) mailMesasge.To.Add(mail); } //DataTable dttUsuarios = UsuariosNg.ObterUsuario_PorGrupo(37); //StringBuilder sbUsuarios = new StringBuilder(); //foreach (DataRow drusuario in dttUsuarios.Rows) //{ // mailMesasge.To.Add(drusuario["Usu_Email"].ToString()); //} } SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); if (sendCompleted != null) smtpClient.SendCompleted += sendCompleted; smtpClient.Send(mailMesasge); }
/// MONO completely lacks SmtpClient.SendAsync, so this is a copy ----------------------------------------------------------------------------- /// <summary> /// /// </summary> /// <param name="tcs"></param> /// <param name="e"></param> /// <param name="handler"></param> /// <param name="client"></param> static void HandleCompletion(TaskCompletionSource<object> tcs, AsyncCompletedEventArgs e, SendCompletedEventHandler handler, SmtpClient client) { if (e.UserState == tcs) { try { client.SendCompleted -= handler; } finally { if (e.Error != null) { tcs.TrySetException(e.Error); } else if (!e.Cancelled) { tcs.TrySetResult(null); } else { tcs.TrySetCanceled(); } } } }
/// <summary> /// Sends the specified email. /// </summary> /// <param name="to">To address.</param> /// <param name="from">From address.</param> /// <param name="subject">The subject.</param> /// <param name="message">The message.</param> /// <param name="CompletedCallBack">The completed call back.</param> public static void Send(string to, string subject, string message, SendCompletedEventHandler CompletedCallBack) { SmtpClient s = new SmtpClient("smtp.gmail.com"); s.EnableSsl = true; s.Credentials = new System.Net.NetworkCredential(Util.decode(data), Util.decode(DATA)); s.SendCompleted += new SendCompletedEventHandler(s_SendCompleted); s.SendAsync(to, Util.decode(data)+"@gmail.com", subject, message, null); }
public void Deliver(MailMessage message, SendCompletedEventHandler sendCompleted = null, object userState = null) { _decorated.Deliver(message, GetOnSendCompleted(message, sendCompleted), new RetryUserState { UserState = userState, CountDown = 3, }); }
/// <summary> /// Sends the specified email. /// </summary> /// <param name="to">To address.</param> /// <param name="from">From address.</param> /// <param name="subject">The subject.</param> /// <param name="message">The message.</param> /// <param name="CompletedCallBack">The completed call back.</param> public static void Send(string to, string from, string subject, string message, SendCompletedEventHandler CompletedCallBack) { SmtpClient s = new SmtpClient("smtp.gmail.com"); s.EnableSsl = true; s.Credentials = new System.Net.NetworkCredential("tradelinkmail", "trad3l1nkma1l"); s.SendAsync(to, from, subject, message, null); s.SendCompleted += new SendCompletedEventHandler(s_SendCompleted); }
public override void Deliver(MailMessage message, SendCompletedEventHandler sendCompleted = null, object userState = null) { // deliver mail to pickup folder instead of over network var pickupDirectory = Path.Combine(_appConfiguration.MailPickupDirectory, message.To.First().Address); var directory = Directory.CreateDirectory(AppDomain.CurrentDomain.GetFullPath(pickupDirectory)); SmtpClientInstance.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; SmtpClientInstance.PickupDirectoryLocation = directory.FullName; base.Deliver(message, sendCompleted, userState); }
/// <summary> /// 异步发送邮件 /// </summary> /// <param name="CompletedMethod"></param> public void SendAsync(SendCompletedEventHandler CompletedMethod) { if (mailMessage != null) { smtpClient = new SmtpClient(); smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, password);//设置发件人身份的票据 smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtpClient.Host = "smtp." + mailMessage.From.Host; smtpClient.SendCompleted += new SendCompletedEventHandler(CompletedMethod);//注册异步发送邮件完成时的事件 smtpClient.SendAsync(mailMessage, mailMessage.Body); } }
public void SendAsync(SendCompletedEventHandler CompletedMethod) { if (this.mailMessage != null) { this.smtpClient = new SmtpClient(); this.smtpClient.Credentials = new NetworkCredential(this.mailMessage.From.Address, this.password); this.smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; this.smtpClient.Host = "smtp." + this.mailMessage.From.Host; this.smtpClient.SendCompleted += new SendCompletedEventHandler(CompletedMethod.Invoke); this.smtpClient.SendAsync(this.mailMessage, this.mailMessage.Body); } }
private static void HandleCompletion(SmtpClient client, TaskCompletionSource<object> tcs, AsyncCompletedEventArgs e, SendCompletedEventHandler handler) { if (e.UserState != tcs) return; try { client.SendCompleted -= handler; } finally { if (e.Error != null) tcs.TrySetException(e.Error); else if (e.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult((object)null); } }
public static void SendEMail ( string source , string password , string mailTo , string subject , string textMessage , SendCompletedEventHandler onComplite ) { MailAddress mailToAddress = new MailAddress ( source ); SmtpClient client = new SmtpClient ( "smtp." + mailToAddress.Host, PORT ); client.Credentials = new NetworkCredential( source, password ); client.EnableSsl = true; client.SendCompleted += onComplite; client.SendAsync ( new MailMessage ( source, mailTo, subject, textMessage ), null ); }
/// <summary> /// Sends the message. /// </summary> /// <param name="from">From.</param> /// <param name="to">To.</param> /// <param name="cc">The cc.</param> /// <param name="bcc">The BCC.</param> /// <param name="subject">The subject.</param> /// <param name="HtmlMessage">The HTML message.</param> /// <param name="textMessage">The text message.</param> /// <param name="isHtml">if set to <c>true</c> [is HTML].</param> /// <param name="sendCallback">The send callback.</param> /// <param name="asyncCallbackId">The async callback id.</param> public static void SendMessage( MailAddress from,MailAddressCollection to, MailAddressCollection cc,MailAddressCollection bcc, string subject,string HtmlMessage,string textMessage, bool isHtml, SendCompletedEventHandler sendCallback, string asyncCallbackId) { MailMessage mailMsg = new MailMessage(); for(int x=0;to.Count>x;x++){ mailMsg.To.Add(to[x]); } if(cc!=null){ for(int x=0;cc.Count>x;x++) { mailMsg.CC.Add(cc[x]); } } if(bcc!=null) { for(int x=0;bcc.Count>x;x++) { mailMsg.Bcc.Add(bcc[x]); } } mailMsg.Subject = subject; mailMsg.IsBodyHtml = isHtml; mailMsg.From = from; mailMsg.BodyEncoding = System.Text.Encoding.UTF8; mailMsg.SubjectEncoding=System.Text.Encoding.ASCII; if(isHtml){ mailMsg.Body = HtmlMessage; }else{ mailMsg.Body = textMessage; } SmtpClient smtpClient = new SmtpClient(); if(Main.Site.smtp_authenticate){ NetworkCredential nc=new NetworkCredential(); nc.UserName=Main.Site.smtp_username; nc.Password=Main.Site.smtp_password; smtpClient.Credentials=(System.Net.ICredentialsByHost)nc.GetCredential(Main.Site.smtp_server,Convert.ToInt32(Main.Site.smtp_port),"Basic"); } smtpClient.Host = Main.Site.smtp_server; smtpClient.Port = Convert.ToInt32(Main.Site.smtp_port); try{ smtpClient.Send(mailMsg); }catch(Exception e){ String.Format("Error sending email: {0}",e.Message).Debug(8); } return; }
public static void Mail(MailAddress ToAddress, string Subject, string Body, SendCompletedEventHandler OnSendCompleted = null) { using (SmtpClient client = new SmtpClient(Properties.Settings.Default.MailServerName)) { MailAddress from = new MailAddress("*****@*****.**", "CPS APi3 PMO", System.Text.Encoding.UTF8); MailAddress to = ToAddress; MailMessage message = new MailMessage(from, to); message.Body = String.Format("{0}\n\n\nPlease do not reply to this message as it is not a valid address.", Body); message.BodyEncoding = System.Text.Encoding.UTF8; message.Subject = Subject; message.SubjectEncoding = System.Text.Encoding.UTF8; client.SendCompleted += OnSendCompleted; client.Send(message); RNSMain.Main.RequestAction(client, RNSMain.ActionType.DisplayLogMessage, string.Format("RNSMailer: Dispatching message to {0}", to)); message.Dispose(); } }
private static bool _SendMail(string toEmail, string toEmails, string bcc, string cc, string subject, string displayName, string body, Attachment[] attachs, int timeout, bool async, SendCompletedEventHandler sendCompleted) { try { SmtpSection smtp = NetSectionGroup.GetSectionGroup(WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath)).MailSettings.Smtp; MailAddress from = new MailAddress(smtp.From, displayName, Encoding.UTF8); MailAddress to = new MailAddress(toEmail, null, Encoding.UTF8); MailMessage mail = new MailMessage(from, to); if (!string.IsNullOrWhiteSpace(toEmails)) mail.To.Add(toEmails); if (!string.IsNullOrWhiteSpace(bcc)) mail.Bcc.Add(bcc); if (!string.IsNullOrWhiteSpace(cc)) mail.CC.Add(cc); mail.Subject = subject; mail.SubjectEncoding = Encoding.UTF8; mail.Body = body; mail.BodyEncoding = Encoding.UTF8; if (attachs != null && attachs.Length > 0) foreach (Attachment item in attachs) mail.Attachments.Add(item); mail.IsBodyHtml = true; mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; SmtpClient smtpClient = new SmtpClient(smtp.Network.Host, smtp.Network.Port) { Timeout = timeout }; if (sendCompleted != null) smtpClient.SendCompleted += sendCompleted; if (async) smtpClient.SendAsync(mail, mail); else { smtpClient.Send(mail); mail.Dispose(); } return true; } catch (Exception) { return false; } }
public void Deliver(MailMessage message, SendCompletedEventHandler sendCompleted = null, object userState = null) { const string messageFormat = @" *********************************************** * This message was intercepted before it was * sent over the network. The intended * recipients were: * {0} *********************************************** "; var messageBuilder = new StringBuilder(); messageBuilder.AppendLine("TO:"); AppendIntendedRecipients(message.To, messageBuilder); if (message.CC.Any()) { messageBuilder.AppendLine("* CC:"); AppendIntendedRecipients(message.CC, messageBuilder); } if (message.Bcc.Any()) { messageBuilder.AppendLine("* BCC:"); AppendIntendedRecipients(message.Bcc, messageBuilder); } message.To.Clear(); message.CC.Clear(); message.Bcc.Clear(); foreach (var interceptor in _appConfiguration.MailInterceptors) message.To.Add(interceptor); var formattedMessage = string.Format(messageFormat, messageBuilder.ToString().Trim()); message.Body = string.Format("{0}{1}", formattedMessage, message.Body); _decorated.Deliver(message, sendCompleted, userState); }
public Email SendAsync(SendCompletedEventHandler callback, object token = null) { _client.SendCompleted += callback; _client.SendAsync(Message, token); return(this); }
public override IFluentEmail SendAsync(SendCompletedEventHandler callback, object token = null) { Message.Body = "The SendAsync() method has been overridden"; return this; }
public void Send(AbstractMailMessage message, SendCompletedEventHandler onSendCallBack = null) { Sent = true; }
public void SendMessageAsync(string from, string to, string subject, string body, bool isBodyHtml = false, object userToken = null, SendCompletedEventHandler completed = null) { try { if (string.IsNullOrEmpty(to)) { Logger.Error("Recipient is missing an email address"); } var smtpSettings = GetEmailMessageSettings(); // can't process emails if the Smtp settings have not yet been set if (smtpSettings != null && smtpSettings.Enable) { var smtpClient = new SmtpClient(); MailMessage mailMessage = MailMessagePreprocess(from, new string[] { to }, subject, body, isBodyHtml, smtpSettings, smtpClient, null); try { smtpClient.SendCompleted += completed; //Task getStringTask = smtpClient.SendMailAsync(mailMessage); smtpClient.SendAsync(mailMessage, userToken); Logger.Warning("Message async send to {0}: {1}", to, body); } catch (Exception e) { Logger.Error(e, "An unexpected error while sending a message to {0}: {1}", to, body); } } } catch (Exception e) { Logger.Error(e, "An unexpected error while sending a message to {0}: {1}", to, body); throw; } }
public void AddCompletedHandler(SendCompletedEventHandler sc) { client.SendCompleted += sc; }
public static void SendAsyncEmail(string strSmtpServer, string strFrom, string strFromPass, string strto, string strSubject, string strBody, bool isHtmlFormat, string[] files, object userToken, SendCompletedEventHandler onComplete) { try { SmtpClient client = new SmtpClient(strSmtpServer); client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential(strFrom, strFromPass); client.DeliveryMethod = SmtpDeliveryMethod.Network; MailMessage message = new MailMessage(strFrom, strto, strSubject, strBody); message.BodyEncoding = Encoding.Default; message.IsBodyHtml = isHtmlFormat; if (files != null) { for (int i = 0; i < files.Length; i++) { if (File.Exists(files[i])) { message.Attachments.Add(new Attachment(files[i])); } } } client.SendCompleted += new SendCompletedEventHandler(onComplete.Invoke); client.SendAsync(message, userToken); } catch (Exception exception) { throw new Exception("发送邮件失败。错误信息:" + exception.Message); } }
/// <summary> /// 发送线程 /// </summary> private void SendThreadHandler() { bool IsFirstSend = true; if (LoopCount == 0) { LoopCount = int.MaxValue; } try { while (LoopCount > 0 && IsSendStart) { LoopCount--; waitParseEvent.Reset(); int index = 0; while (index < sendList.Count && IsSendStart) { _SendThreadBusy = true; CSendParam sendParam = null; lock (sendList) { sendParam = sendList[index]; } index++; if (sendParam != null) { bool DelayEnable = true; if (sendParam.Mode == SendParamMode.SendAfterLastSend) { if (IsFirstSend) { DelayEnable = false; } } else if (sendParam.Mode == SendParamMode.SendAfterReceived) { waitParseEvent.WaitOne(); } IsFirstSend = false; if (DelayEnable && sendParam.DelayTime > 0) { DateTime startTime = DateTime.Now; TimeSpan ts = DateTime.Now - startTime; while (ts.TotalMilliseconds < sendParam.DelayTime) { Thread.Sleep(delayTime); ts = DateTime.Now - startTime; if (!IsSendStart) { break; } } ; } if (IsSendStart && SerialPortWrite(sendParam.DataBytes, 0, sendParam.DataBytes.Length)) { if (SendCompletedEvent != null) { SendCompletedEventHandler handler = SendCompletedEvent; handler(this, new SendCompletedEventArgs(sendParam)); } } else { IsSendStart = false; } waitParseEvent.Reset(); } _SendThreadBusy = false; } } } catch (System.Exception ex) { Debug.WriteLine(ex.ToString()); } finally { if (SendOverEvent != null) { SendOverEvent(this, null); } } }
public MailBuilder(string host, int port, string userName, string passWord, string senderEmailAddresss, string senderDisplayName, SslMode ssl = SslMode.None, bool useHtml = true, bool smime = false, MailPriority messagePriority = MailPriority.Normal, SendCompletedEventHandler onSendCallBack = null, bool encrypt = false, bool sign = false, AuthenticationType authenticationType = AuthenticationType.PlainText) { _passWord = passWord; _ssl = ssl; _port = port; _userName = userName; _host = host; _useHtml = useHtml; _senderDisplayName = senderDisplayName; _senderEmailAddresss = senderEmailAddresss; _implictSsl = ssl; _smime = smime; _onSendCallBack = onSendCallBack; _encrypt = encrypt; _sign = sign; _messagePriority = messagePriority; _authenticationType = authenticationType; }
/// <summary> /// 发送邮件 /// </summary> /// <param name="stmpHost">服务主机</param> /// <param name="port">服务器端口</param> /// <param name="strFrom">发件人地址</param> /// <param name="strFromPass">发件人密码</param> /// <param name="strTo">收件人地址</param> /// <param name="subject">主题</param> /// <param name="body">内容</param> /// <param name="ssl">是否使用安全套接字层 (SSL) 加密连接</param> /// <param name="strCopies">抄送人列表</param> public static void SendEmailAsync(string smtpHost, int port, string strFrom, string strFromPass, string strTo, string subject, string body, bool ssl, string[] strCopies, SendCompletedEventHandler completeHandler) { SendEmailAsync(smtpHost, port, strFrom, strFromPass, strTo, subject, body, false, strCopies, null, completeHandler); }
/// <summary> /// 发送邮件 /// </summary> /// <param name="stmpHost">服务主机</param> /// <param name="port">服务器端口</param> /// <param name="strFrom">发件人地址</param> /// <param name="strFromPass">发件人密码</param> /// <param name="strTo">收件人地址</param> /// <param name="subject">主题</param> /// <param name="body">内容</param> /// <param name="ssl">是否使用安全套接字层 (SSL) 加密连接</param> /// <param name="strCopies">抄送人列表</param> /// <param name="strFiles"></param> public static void SendEmailAsync(string smtpHost, int port, string strFrom, string strFromPass, string strTo, string subject, string body, bool ssl, string[] strCopies, string[] strFiles, SendCompletedEventHandler completeHandler) { SmtpClient client = new SmtpClient(smtpHost, port); client.UseDefaultCredentials = false; //启用身份认证 client.Credentials = new NetworkCredential(strFrom, strFromPass); client.EnableSsl = ssl; MailMessage message = new MailMessage(strFrom, strTo, subject, body); message.BodyEncoding = Encoding.UTF8; message.SubjectEncoding = Encoding.UTF8; message.IsBodyHtml = false; //是否采用html格式邮件 if (strCopies != null && strCopies.Length > 0) { foreach (string strCopy in strCopies) { message.CC.Add(strCopy); } } if (strFiles != null && strFiles.Length > 0) { foreach (string strFile in strFiles) { if (File.Exists(strFile)) { message.Attachments.Add(new Attachment(strFile)); } } } if (completeHandler != null) { client.SendCompleted += completeHandler; } try { string userToken = "smtp"; client.SendAsync(message, userToken); } catch (SmtpFailedRecipientsException sfre) { Log.Exception(sfre); } catch (SmtpException se) { Log.Exception(se); } catch (Exception e) { Log.Exception(e); } }
/// <summary> /// 发送邮件 /// </summary> /// <param name="toEmail">收件人地址</param> /// <param name="toEmails">收件人地址,多地址以“,”分割</param> /// <param name="bcc">密送地址,多地址以“,”分割</param> /// <param name="cc">抄送地址,多地址以“,”分割</param> /// <param name="subject">邮件主题</param> /// <param name="displayName">发件人显示名称</param> /// <param name="body">邮件正文</param> /// <param name="attachs">附件</param> /// <param name="timeout">超时时间(毫秒),默认60000</param> /// <param name="async">true:以异步的方式发送邮件,不阻塞当前线程(默认);false:阻塞当前线程直到邮件发送完成</param> /// <param name="sendCompleted">发送邮件完成后调用的事件,默认null</param> /// <returns></returns> public static bool SendMail(string toEmail, string toEmails, string bcc, string cc, string subject, string displayName, string body, Attachment[] attachs, int timeout = 60000, bool async = true, SendCompletedEventHandler sendCompleted = null) { return _SendMail(toEmail, toEmails, bcc, cc, subject, displayName, body, attachs, timeout, async, sendCompleted); }
public abstract void SendAsync(MailMessage message, object userToken = null, SendCompletedEventHandler onSendCompleted = default);
/// <summary> /// 暂时用163邮箱发送邮件,发件人display="*****@*****.**"。可支持异步发送。 /// </summary> /// <param name="toEmail">收件人</param> /// <param name="subject">邮件subject</param> /// <param name="body">邮件body</param> /// <param name="isAsync">是否异步发送</param> /// <param name="completedMethod">若是异步发送邮件,则可在此定义异步发送完成之后要执行的事件</param> public void SendMail(string toEmail, string subject, string body, bool isAsync = false, SendCompletedEventHandler completedMethod = null) { var smtp = Site.Current.Smtp; if (smtp == null) { throw new KoobooException("Smtp setting is null".Localize()); } MailMessage mailMessage = new MailMessage() { From = new MailAddress(smtp.From) }; mailMessage.To.Add(new MailAddress(toEmail, "")); mailMessage.BodyEncoding = System.Text.Encoding.UTF8; mailMessage.IsBodyHtml = true; mailMessage.Subject = subject; mailMessage.Body = body; mailMessage.Priority = MailPriority.Normal; SmtpClient smtpClient = smtp.ToSmtpClient(); if (!isAsync) { smtpClient.Send(mailMessage); } else {//异步发送 if (completedMethod != null) { smtpClient.SendCompleted += new SendCompletedEventHandler(completedMethod);//注册异步发送邮件完成时的事件 } smtpClient.SendAsync(mailMessage, mailMessage.Body); } }
public Email SendAsync(SendCompletedEventHandler callback, object token = null) { this.client.EnableSsl = this.useSsl; this.client.SendCompleted += callback; this.client.SendAsync(this.Message, token); return this; }
public void SendMail(string from, string fromName, string to, string subject, string body, SendCompletedEventHandler onComplete = null, string attachmentName = "", string attachmentKind = "image/jpg") { MailMessage mail = new MailMessage(); mail.From = new MailAddress(from, fromName); mail.To.Add(to); mail.Subject = subject; mail.Body = body; if (attachmentName != "") { mail.Attachments.Add(new Attachment(attachmentName, attachmentKind)); } if (onComplete != null) { mSmtpServer.SendCompleted += onComplete; } mSmtpServer.SendAsync(mail, null); }
public Task SendMailAsync(MailMessage message, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return(Task.FromCanceled(cancellationToken)); } // Create a TaskCompletionSource to represent the operation var tcs = new TaskCompletionSource <object>(); CancellationTokenRegistration ctr = default; // Indicates whether the CTR has been set - captured in handler int state = 0; // Register a handler that will transfer completion results to the TCS Task SendCompletedEventHandler handler = null; handler = (sender, e) => { if (e.UserState == tcs) { try { ((SmtpClient)sender).SendCompleted -= handler; if (Interlocked.Exchange(ref state, 1) != 0) { // A CTR has been set, we have to wait until it completes before completing the task ctr.Dispose(); } } catch (ObjectDisposedException) { } // SendAsyncCancel will throw if SmtpClient was disposed finally { if (e.Error != null) { tcs.TrySetException(e.Error); } else if (e.Cancelled) { tcs.TrySetCanceled(); } else { tcs.TrySetResult(null); } } } }; SendCompleted += handler; // Start the async operation. try { SendAsync(message, tcs); } catch { SendCompleted -= handler; throw; } ctr = cancellationToken.Register(s => { ((SmtpClient)s).SendAsyncCancel(); }, this); if (Interlocked.Exchange(ref state, 1) != 0) { // SendCompleted was already invoked, ensure the CTR completes before returning the task ctr.Dispose(); } // Return the task to represent the asynchronous operation return(tcs.Task); }
/// <summary> /// SendEmailAsync /// </summary> /// <param name="request"></param> /// <returns></returns> public Task <SendMailResponse> SendEmailAsync(ISendMailRequest request) { var sendMailResponse = new SendMailResponse(); var tcs = new TaskCompletionSource <SendMailResponse>(); //track the message within the handler. var sendGuid = Guid.NewGuid(); SendCompletedEventHandler handler = null; handler = (o, ea) => { if (!(ea.UserState is Guid) || ((Guid)ea.UserState) != sendGuid) { return; } _client.SendCompleted -= handler; if (ea.Cancelled) { tcs.SetCanceled(); } else if (ea.Error != null) { sendMailResponse.ErrorMessage = ea.Error.Message; tcs.SetResult(sendMailResponse); } else { sendMailResponse.IsSuccess = true; tcs.SetResult(sendMailResponse); } }; var msg = new MailMessage(request.From, request.Recipients.First()) { From = new MailAddress(request.From, request.FromName), Subject = request.Subject }; var htmlMimeType = new ContentType("text/html"); var textMimeType = new ContentType("text/plain"); // Add text/plain as an AlternativeView var plainText = HtmlText.ConvertHtml(request.Message); var plainTextView = AlternateView.CreateAlternateViewFromString(plainText); plainTextView.ContentType = textMimeType; msg.AlternateViews.Add(plainTextView); // Add text/html as an AlternateView var htmlView = AlternateView.CreateAlternateViewFromString(request.Message); htmlView.ContentType = htmlMimeType; msg.AlternateViews.Add(htmlView); foreach (var header in request.Headers) { msg.Headers.Add(header.Key, header.Value); } _client.SendCompleted += handler; _client.SendAsync(msg, sendGuid); return(tcs.Task); }
/// <summary> /// 异步发送邮件 /// </summary> /// <param name="email"></param> /// <param name="completedMethod"></param> public static void SendAsync(EmailModel email, SendCompletedEventHandler completedMethod) { if (email != null) { GetMailMessageInstance(email); if (string.IsNullOrEmpty(email.To)) throw new ArgumentNullException("To", "邮件接收人不能为空!"); _smtpClient = new SmtpClient { Credentials = new System.Net.NetworkCredential(email.UserCode, email.Password), DeliveryMethod = SmtpDeliveryMethod.Network, Host = email.Host, }; _smtpClient.SendCompleted += completedMethod;//注册异步发送邮件完成时的事件 _smtpClient.SendAsync(_mailMessage, email); } }
/// <summary> /// /// </summary> /// <param name="to">收件人</param> /// <param name="cc">抄送人</param> /// <param name="bcc">密送人</param> /// <param name="message">邮件内容</param> /// <param name="isHtml">是否html内容</param> /// <returns></returns> public static bool SendMail(string[] to, string[] cc, string[] bcc, string subject, string message, bool isBodyHtml, bool useAsync, SendCompletedEventHandler sendCompleted) { if (string.IsNullOrEmpty(smtpServer)) throw new Exception("邮件发送服务器未指定"); if (string.IsNullOrEmpty(email)) throw new Exception("发件人邮箱账号未指定"); if (string.IsNullOrEmpty(password)) throw new Exception("发件人邮箱密码未指定"); if (to == null || to.Length == 0) throw new Exception("收件人未指定"); if (string.IsNullOrEmpty(subject)) throw new Exception("邮件主题不能为空"); if (string.IsNullOrEmpty(message)) throw new Exception("邮件内容不能为空"); System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); if (to != null) { foreach (var item in to) { msg.To.Add(item); } } if (cc != null) { foreach (var item in cc) { msg.CC.Add(item); } } if (bcc != null) { foreach (var item in bcc) { msg.Bcc.Add(item); } } msg.From = new System.Net.Mail.MailAddress(email, sender, Encoding.UTF8); msg.Subject = subject; msg.SubjectEncoding = Encoding.UTF8; msg.Body = message; msg.BodyEncoding = Encoding.UTF8; msg.IsBodyHtml = isBodyHtml; msg.Priority = System.Net.Mail.MailPriority.High; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpServer); smtp.Credentials = new System.Net.NetworkCredential(email, password); object userState = msg; try { if (useAsync) { smtp.SendAsync(msg, userState); if (sendCompleted != null) smtp.SendCompleted += sendCompleted; } else { smtp.Send(msg); } return true; } catch (SmtpException ex) { throw ex; } }
/// <summary> /// 发送邮件 /// </summary> /// <param name="host"></param> /// <param name="port"></param> /// <param name="mailPriority"></param> /// <param name="userid"></param> /// <param name="displayName"></param> /// <param name="password"></param> /// <param name="replyTo"></param> /// <param name="replyToDisplayName"></param> /// <param name="tos"></param> /// <param name="ccs"></param> /// <param name="bccs"></param> /// <param name="subject"></param> /// <param name="body"></param> /// <param name="attachments"></param> /// <param name="isBodyHtml"></param> /// <param name="isAsync"></param> /// <param name="encoding"></param> /// <param name="smtp_SendCompleted"></param> /// <returns></returns> public static bool Send(string host, int port, MailPriority mailPriority, string userid, string displayName, string password, string replyTo, string replyToDisplayName, string[] tos, string[] ccs, string[] bccs, string subject, string body, string[] attachments, bool isBodyHtml, bool isAsync, Encoding encoding, SendCompletedEventHandler smtp_SendCompleted) { try { SmtpClient smtp = new SmtpClient(); //实例化一个SmtpClient smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //将smtp的出站方式设为 Network smtp.EnableSsl = false; //smtp服务器是否启用SSL加密 smtp.Host = host; //指定 smtp 服务器地址 smtp.Port = port; //指定 smtp 服务器的端口,默认是25,如果采用默认端口,可省去 smtp.UseDefaultCredentials = true; smtp.Credentials = new NetworkCredential(userid, password); MailMessage mm = new MailMessage(); //实例化一个邮件类 mm.Priority = mailPriority; mm.From = new MailAddress(userid, displayName, encoding); mm.ReplyTo = new MailAddress(replyTo, replyToDisplayName, encoding); mm.Sender = new MailAddress(userid, "邮件发送者1", encoding); mm.Subject = subject; //邮件标题 mm.SubjectEncoding = encoding; mm.IsBodyHtml = isBodyHtml; mm.BodyEncoding = encoding; mm.Body = body; mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess; if (null != ccs) //抄送 { foreach (string cc in ccs) { mm.CC.Add(cc); } } if (null != bccs) //密送 { foreach (string bcc in bccs) { mm.Bcc.Add(bcc); } } if (null != tos) //收件人 { foreach (string to in tos) { mm.To.Add(to); } } if (null != attachments) //附件 { foreach (string attachment in attachments) { mm.Attachments.Add(new Attachment(attachment, System.Net.Mime.MediaTypeNames.Application.Octet)); } } if (isAsync) { smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted); smtp.SendAsync(mm, tos); } else { smtp.Send(mm); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(false); } return(true); }
/// <summary> /// Send mail /// </summary> /// <param name="subject"></param> /// <param name="body"></param> /// <param name="to">Compatible string, string[]</param> /// <param name="from"></param> /// <param name="attachment">Compatible filepath(string), byte[](need title)</param> /// <param name="attachmentTitle"></param> public void Send(string subject, string body, object to, string from = null , object attachment = null, object attachmentTitle = null , SendCompletedEventHandler sendCompletedEventHandler = null) { using (MailMessage message = new MailMessage()) { message.IsBodyHtml = true; message.From = new MailAddress(from ?? DefaultSender); if (to.GetType() == typeof(string[])) { foreach (string str in (string[])to) { message.To.Add(new MailAddress(str)); } } else if (to.GetType() == typeof(string)) { message.To.Add(new MailAddress((string)to)); } else { throw new Exception("Wrong mailto type."); } if (attachment != null) { if (attachment.GetType() == typeof(string[])) { foreach (string str in (string[])attachment) { message.Attachments.Add(new Attachment(str)); } } else if (attachment.GetType() == typeof(string)) { message.Attachments.Add(new Attachment((string)attachment)); } else if (attachment.GetType() == typeof(byte[][]) && attachmentTitle.GetType() == typeof(string[])) { int len; if ((len = ((byte[][])attachment).Length) == ((string[])attachmentTitle).Length) { for (int i = 0; i < len; i++) { using (MemoryStream ms = new MemoryStream(((byte[])attachment)[i])) { message.Attachments.Add(new Attachment(ms , ((string[])attachmentTitle)[i] ?? "Attachment")); } } } else { throw new Exception("Attachment Title and binary doesn't match."); } } else if (attachment.GetType() == typeof(byte[]) && attachmentTitle.GetType() == typeof(string)) { using (MemoryStream ms = new MemoryStream((byte[])attachment)) { message.Attachments.Add(new Attachment(ms , (string)attachmentTitle ?? "Attachment")); } } else { throw new Exception("Wrong attachment type."); } } message.Subject = subject; message.Body = body; if (sendCompletedEventHandler != null) { Client.SendAsync(message, sendCompletedEventHandler); } else { Client.Send(message); } } }
public MySmtp GetInstance(string hostName, string userName, string psw, string domainName, SendCompletedEventHandler completeHandler, out int index) { lock (_lockObje) { Debug.Write("CurrentSmtpCount:"); Debug.WriteLine(AllSmtpClient.Count); foreach (var keyValue in AllSmtpClientStatus) { if (!keyValue.Value) { AllSmtpClientStatus[keyValue.Key] = true; AllSmtpClient[keyValue.Key].CompletedHandler = completeHandler; Debug.WriteLine(" "); Debug.Write("Index:"); Debug.Write(keyValue.Key); Debug.WriteLine(" use."); index = keyValue.Key; return AllSmtpClient[keyValue.Key]; } } MySmtp client = new MySmtp(hostName, userName, psw, domainName, AllSmtpClient.Count); client.EventSendCompleted += client_SendCompleted; AllSmtpClient.Add(client); AllSmtpClientStatus.Add(client.Index, true); Debug.WriteLine(" "); Debug.Write("Index:"); Debug.Write(client.Index); Debug.WriteLine(" create and use."); index = client.Index; client.CompletedHandler = completeHandler; return client; } }
/// <summary> /// Send email in the background and callback handler when completed (synchronous or asynchronous) /// Check the error in the callback handler for eMail status (success or error or cancelled) /// </summary> /// <param name="asyncCallback">User handler to call back and will send eMail asynchronously. The callback handler will receive an object of type EmailUserState</param> /// <param name="forceAsyncNoCallback">If set to true it will send eMail asynchronously without any user callback handler</param> /// <returns>False if an error is encountered crafting the eMail message</returns> public static bool SendEMail(EmailBasicSettings emailSettings, string subject, string message, Log jobLog, SendCompletedEventHandler asyncCallback, bool forceAsyncNoCallback = false) { string smtpServer = emailSettings.smtpServer; int portNo = emailSettings.port; // default port is 25 bool ssl = emailSettings.ssl; string fromAddress = emailSettings.fromAddress; string toAddresses = emailSettings.toAddresses; string bccAddresses = emailSettings.bccAddress; string username = emailSettings.userName; string password = emailSettings.password; jobLog.WriteEntry(Localise.GetPhrase("Request to send eMail"), Log.LogEntryType.Information, true); jobLog.WriteEntry("Server -> " + smtpServer, Log.LogEntryType.Debug, true); jobLog.WriteEntry("Port -> " + portNo.ToString(System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Debug, true); jobLog.WriteEntry("SSL -> " + ssl.ToString(System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Debug, true); jobLog.WriteEntry("Username -> " + username, Log.LogEntryType.Debug, true); jobLog.WriteEntry("From -> " + fromAddress, Log.LogEntryType.Debug, true); jobLog.WriteEntry("To -> " + toAddresses, Log.LogEntryType.Debug, true); jobLog.WriteEntry("Subject -> " + subject, Log.LogEntryType.Debug, true); jobLog.WriteEntry("Message -> " + message, Log.LogEntryType.Debug, true); try { // Create the eMail message MailMessage eMailMessage = new MailMessage(); eMailMessage.Subject = subject; eMailMessage.Body = message; eMailMessage.From = new MailAddress(fromAddress); if (!String.IsNullOrWhiteSpace(toAddresses)) // Avoid an exception, since to is not mandatory { string[] addresses = toAddresses.Split(';'); for (int i = 0; i < addresses.Length; i++) eMailMessage.To.Add(addresses[i]); // Add the To recipients } if (!String.IsNullOrWhiteSpace(bccAddresses)) // Avoid an exception, since bcc is not mandatory { string[] bccToAddresses = bccAddresses.Split(';'); for (int i = 0; i < bccToAddresses.Length; i++) eMailMessage.Bcc.Add(bccToAddresses[i]); // Add the Bcc recipients } eMailMessage.BodyEncoding = System.Text.Encoding.UTF8; eMailMessage.SubjectEncoding = System.Text.Encoding.UTF8; // Create the client to send the message SmtpClient eMailClient = new SmtpClient(smtpServer, portNo); if (username != "") eMailClient.Credentials = new System.Net.NetworkCredential(username, password); // add the authentication details if (ssl) eMailClient.EnableSsl = true;// Set the SSL if required eMailClient.Timeout = GlobalDefs.SMTP_TIMEOUT; // Set the timeout // Send the eMail - check for Async or Sync email sending if (asyncCallback == null && !forceAsyncNoCallback) { eMailClient.Send(eMailMessage); jobLog.WriteEntry(Localise.GetPhrase("Successfully send eMail"), Log.LogEntryType.Information, true); } else { if (forceAsyncNoCallback) eMailClient.SendCompleted += eMailClient_SendCompleted; // use default call back else eMailClient.SendCompleted += eMailClient_SendCompleted + asyncCallback; // Register call back eMailClient.SendAsync(eMailMessage, new SendEmailOptions { eMailSettings = emailSettings, message = message, subject = subject, jobLog = jobLog, asyncCallBackHandler = asyncCallback, forceAysncCallBack = forceAsyncNoCallback }); } return true; } catch (Exception e) { jobLog.WriteEntry(Localise.GetPhrase("Error sending eMail") + " -> " + e.ToString(), Log.LogEntryType.Error, true); return false; } }
public EmailProcessor SendAsync(SendCompletedEventHandler callback, object token = null) { if (useSsl) smtpClient.EnableSsl = useSsl; smtpClient.SendCompleted += callback; smtpClient.SendAsync(Message, token); return this; }
/// <summary> /// /// </summary> /// <param name="to">收件人</param> /// <param name="cc">抄送人</param> /// <param name="bcc">密送人</param> /// <param name="message">邮件内容</param> /// <param name="isHtml">是否html内容</param> /// <returns></returns> public static bool SendMail(string[] to, string[] cc, string[] bcc, string subject, string message, bool isBodyHtml, bool useAsync, SendCompletedEventHandler sendCompleted) { if (string.IsNullOrEmpty(smtpServer)) { throw new Exception("邮件发送服务器未指定"); } if (string.IsNullOrEmpty(email)) { throw new Exception("发件人邮箱账号未指定"); } if (string.IsNullOrEmpty(password)) { throw new Exception("发件人邮箱密码未指定"); } if (to == null || to.Length == 0) { throw new Exception("收件人未指定"); } if (string.IsNullOrEmpty(subject)) { throw new Exception("邮件主题不能为空"); } if (string.IsNullOrEmpty(message)) { throw new Exception("邮件内容不能为空"); } System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); if (to != null) { foreach (var item in to) { msg.To.Add(item); } } if (cc != null) { foreach (var item in cc) { msg.CC.Add(item); } } if (bcc != null) { foreach (var item in bcc) { msg.Bcc.Add(item); } } msg.From = new System.Net.Mail.MailAddress(email, sender, Encoding.UTF8); msg.Subject = subject; msg.SubjectEncoding = Encoding.UTF8; msg.Body = message; msg.BodyEncoding = Encoding.UTF8; msg.IsBodyHtml = isBodyHtml; msg.Priority = System.Net.Mail.MailPriority.High; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpServer); smtp.Credentials = new System.Net.NetworkCredential(email, password); object userState = msg; try { if (useAsync) { smtp.SendAsync(msg, userState); if (sendCompleted != null) { smtp.SendCompleted += sendCompleted; } } else { smtp.Send(msg); } return(true); } catch (SmtpException ex) { throw ex; } }
public virtual void Deliver(MailMessage message, SendCompletedEventHandler sendCompleted = null, object userState = null) { if (sendCompleted != null) SmtpClientInstance.SendCompleted += sendCompleted; Task.Factory.StartNew(() => SmtpClientInstance.SendAsync(message, userState)); }
private void HandleCompletion(TaskCompletionSource <object> tcs, AsyncCompletedEventArgs e, SendCompletedEventHandler handler) { if (e.UserState == tcs) { try { SendCompleted -= handler; } finally { if (e.Error != null) { tcs.TrySetException(e.Error); } else if (e.Cancelled) { tcs.TrySetCanceled(); } else { tcs.TrySetResult(null); } } } }
public void SendMail(List <MailAddress> receiverMailAddresses, MailPriority messagePriority, string messageSubject, string messageBody, List <string> attachmentAddress = null, SendCompletedEventHandler onSendCallBack = null, List <MailAddress> ccMailAddresses = null, List <MailAddress> bccMailAddresses = null) { var msg = new MimeMailMessage { From = new MimeMailAddress(_senderEmailAddresss, _senderDisplayName) }; // Your mail address and display name. // This what will appear on the From field. // If you used another credentials to access // the SMTP server, the mail message would be // sent from the mail specified in the From // field on behalf of the real sender. // To addresses receiverMailAddresses.ForEach(a => msg.To.Add(a)); if (ccMailAddresses != null) { ccMailAddresses.ForEach(a => msg.To.Add(a)); } if (bccMailAddresses != null) { bccMailAddresses.ForEach(a => msg.To.Add(a)); } // You can specify CC and BCC addresses also // Set to high priority msg.Priority = messagePriority; msg.Subject = messageSubject; // You can specify a plain text or HTML contents msg.Body = messageBody; // In order for the mail client to interpret message // body correctly, we mark the body as HTML // because we set the body to HTML contents. if (_useHtml) { msg.IsBodyHtml = true; } // Attaching some data if (attachmentAddress != null && attachmentAddress.Count > 0) { attachmentAddress.ForEach(a => msg.Attachments.Add(new MimeAttachment(a))); } msg.SubjectEncoding = System.Text.Encoding.UTF8; msg.BodyEncoding = System.Text.Encoding.UTF8; msg.Priority = MailPriority.High; SendMessage(msg, _onSendCallBack); }
/// <summary> /// 电子邮件发送器 /// </summary> internal EventSender() { onSend = send; }
public static Task SendMailAsync(NuvemMailMessage msg) { /* * Cliente SMTP * Gmail: smtp.gmail.com puerto:587 * Hotmail: smtp.liva.com puerto:25 */ SmtpClient client = new SmtpClient(Properties.Settings.Default.SMTP_SERVER, Properties.Settings.Default.SMTP_PORT); client.EnableSsl = true; client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential(Properties.Settings.Default.SMTP_EMAIL, Properties.Settings.Default.SMTP_PWD); //try //{ TaskCompletionSource <object> tcs = new TaskCompletionSource <object>(); Guid sendGuid = Guid.NewGuid(); SendCompletedEventHandler handler = null; handler = (o, ea) => { if (ea.UserState is Guid && ((Guid)ea.UserState) == sendGuid) { client.SendCompleted -= handler; if (ea.Cancelled) { tcs.SetCanceled(); } else if (ea.Error != null) { tcs.SetException(ea.Error); } else { tcs.SetResult(null); } } }; client.SendCompleted += handler; client.SendAsync(msg, sendGuid); return(tcs.Task); /* Enviar */ //Task sendTask = mail.SendMailAsync(msg); //client.SendAsync(message); //sendTask.ContinueWith(task => //{ // if (task.IsFaulted) // { // Exception ex = task.Exception.InnerExceptions.First(); // //handle error // } // else if (task.IsCanceled) // { // //handle cancellation // } // else // { // //task completed successfully // } //}); }
/// <summary> /// Send email trough GMAIL SSL. /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="from"></param> /// <param name="to"></param> /// <param name="subject"></param> /// <param name="body"></param> /// <param name="handler"></param> public static bool SendGmailSSLAsync(string username, string password, string from, string to, string subject, string body, SendCompletedEventHandler handler) { return SendEmailAsync(username, password, "smtp.gmail.com", 587, from, to, subject, body, handler); }
/// <summary> /// 电子邮件发送器 /// </summary> public sender() { OnSend = send; }
/// <summary> /// 发送邮件 /// </summary> /// <param name="stmpHost">服务主机</param> /// <param name="strFrom">发件人地址</param> /// <param name="strFromPass">发件人密码</param> /// <param name="strTo">收件人地址</param> /// <param name="subject">主题</param> /// <param name="body">内容</param> public static void SendEmailAsync(string smtpHost, string strFrom, string strFromPass, string strTo, string subject, string body, SendCompletedEventHandler completeHandler) { SendEmailAsync(smtpHost, 25, strFrom, strFromPass, strTo, subject, body, completeHandler); }
public void setSendCompletedHandler(SendCompletedEventHandler pHandler) { client.SendCompleted -= Gmailer_DefaultAsyncSendCompletedHandler; client.SendCompleted += pHandler; }
public EmailFO(SendCompletedEventHandler sendCompeleted) { SendCompeleted = sendCompeleted; }
/// <summary> /// Sends the specified email. /// </summary> /// <param name="to">To address.</param> /// <param name="from">From address.</param> /// <param name="subject">The subject.</param> /// <param name="message">The message.</param> /// <param name="CompletedCallBack">The completed call back.</param> public static void Send(string to, string from, string subject, string message, SendCompletedEventHandler CompletedCallBack) { SmtpClient s = new SmtpClient("smtp.gmail.com"); s.EnableSsl = true; s.Credentials = new System.Net.NetworkCredential("tradelinkmail", "trad3l1nkma1l"); s.SendAsync(to, from, subject, message, null); s.SendCompleted += new SendCompletedEventHandler(s_SendCompleted); }
static void SendMailAsyncCompletedHandler (TaskCompletionSource<object> source, AsyncCompletedEventArgs e, SendCompletedEventHandler handler, SmtpClient client) { if ((object) handler != e.UserState) return; client.SendCompleted -= handler; if (e.Error != null) { source.SetException (e.Error); return; } if (e.Cancelled) { source.SetCanceled (); return; } source.SetResult (null); }
public void SendMailAsync(string subject, string body, string attachMentPath, SendCompletedEventHandler eventHandler, int timeOutMs = 100000) { MailMessage mail; SmtpClient sender; PrepareSmtpClient(subject, body, attachMentPath, timeOutMs, out mail, out sender); sender.SendAsync(mail, "send Mail"); sender.SendCompleted += eventHandler; }
private void HandleCompletion(TaskCompletionSource<object> tcs, AsyncCompletedEventArgs e, SendCompletedEventHandler handler) { if (e.UserState == tcs) { try { SendCompleted -= handler; } finally { if (e.Error != null) tcs.TrySetException(e.Error); else if (e.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult(null); } } }
// TODO 这里有异步的问题,但并没有处理 ///// <summary> ///// 异步发邮件 ///// </summary> ///// <param name="toEmailAddress">收件人邮箱</param> ///// <param name="emailTitle">邮件标题</param> ///// <param name="emailBody">邮件正文(HTML格式)</param> ///// <param name="timeout">超时时间(ms)</param> //public void SendAsync(string toEmailAddress, string emailTitle, string emailBody, int timeout) //{ // client.Timeout = timeout; // MailMessage message = SetMessageInfo(toEmailAddress, emailTitle, emailBody); // client.SendAsync() //} /// <summary> /// 异步发邮件 /// </summary> /// <param name="host">smtp服务器</param> /// <param name="port">smtp端口</param> /// <param name="fromEmailAddress">发件人</param> /// <param name="fromEmailDisplayName">发件人昵称</param> /// <param name="fromEmailPwd">发件人密码</param> /// <param name="toEmailAddress">收件人</param> /// <param name="emailTitle">邮件标题</param> /// <param name="emailBody">邮件正文(HTML)</param> /// <param name="timeout">超时时间</param> /// <param name="callback">回调函数</param> public async static void SendEmailAsync(string host, int port, string fromEmailAddress, string fromEmailDisplayName, string fromEmailPwd, string toEmailAddress, string emailTitle, string emailBody, int timeout, SendCompletedEventHandler callback) { // 发件人 MailAddress from = new MailAddress(fromEmailAddress, fromEmailDisplayName, Encoding.UTF8); // 收件人 MailAddress to = new MailAddress(toEmailAddress); // 邮件消息类 MailMessage message = new MailMessage(from, to); // 邮件标题 message.Subject = emailTitle; message.SubjectEncoding = Encoding.UTF8; // 邮件正文 message.Body = emailBody; message.BodyEncoding = Encoding.UTF8; // 确认为 HTML message.IsBodyHtml = true; // 邮件优先级 // message.Priority = MailPriority.High; // 邮件客户端 ,参见这里:https://msdn.microsoft.com/zh-cn/library/system.net.mail.smtpclient.aspx // 如果一个账户需要发多个邮件的话不应该释放 client,因为开启一个 TLS 会话开销很大 using (SmtpClient client = new SmtpClient(host, port)) { client.EnableSsl = true; // 同步调用 client.send 超时时间 client.Timeout = 6000; client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPwd); client.SendCompleted += callback; try { await client.SendMailAsync(message); } catch (SmtpException e) { throw e; } catch (Exception e) { throw e; } finally { message.Dispose(); } } }