System.Net.Mail.SmtpClient.SendMailAsync C# (CSharp) Method

SendMailAsync() private method

private SendMailAsync ( MailMessage message ) : System.Threading.Tasks.Task
message MailMessage
return System.Threading.Tasks.Task
        public Task SendMailAsync(MailMessage message)
        {
            // Create a TaskCompletionSource to represent the operation
            var tcs = new TaskCompletionSource<object>();

            // Register a handler that will transfer completion results to the TCS Task
            SendCompletedEventHandler handler = null;
            handler = (sender, e) => HandleCompletion(tcs, e, handler);
            SendCompleted += handler;

            // Start the async operation.
            try
            {
                SendAsync(message, tcs);
            }
            catch
            {
                SendCompleted -= handler;
                throw;
            }

            // Return the task to represent the asynchronous operation
            return tcs.Task;
        }

Same methods

SmtpClient::SendMailAsync ( string from, string recipients, string subject, string body ) : System.Threading.Tasks.Task

Usage Example

Esempio n. 1
1
        public async System.Threading.Tasks.Task<ActionResult> Contact(Email model)
        {
            ViewBag.Message = "Nice too meet you!";
            if (ModelState.IsValid)
            {
                var body = "";
                if (!string.IsNullOrEmpty(model.AboutProduct)) body = "<h2>Email From: {0} ({1})</h2></br><p>Message concerning {2}:</p><p>{3}</p>";
                else body = "<h2>Email From: {0} ({1})</h2></br><p>Message:</p><p>{3}</p>";

                var message = new MailMessage();
                message.To.Add(new MailAddress("*****@*****.**"));
                message.From = new MailAddress("*****@*****.**");
                message.Subject = "Your email subject";
                message.Body = string.Format(body, model.FromName, model.FromEmail, model.AboutProduct, model.Message);
                message.IsBodyHtml = true;

                using (var smtp = new SmtpClient())
                {
                    var credential = new NetworkCredential
                    {
                        UserName = "******",
                        Password = "******"
                    };
                    smtp.Credentials = credential;
                    smtp.Host = "smtp.gmail.com";
                    smtp.Port = 587;
                    smtp.EnableSsl = true;
                    await smtp.SendMailAsync(message);
                    return RedirectToAction("/Sent");
                }
            }
            return View(model);
        }
All Usage Examples Of System.Net.Mail.SmtpClient::SendMailAsync