protected Dispose ( bool disposing ) : void | ||
disposing | bool | |
return | void |
private async Task SendAsync(MimeMessage mailMessage) { using (var client = new MailKit.Net.Smtp.SmtpClient()) { try { await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.PortResetPassword, true); client.AuthenticationMechanisms.Remove("XOAUTH2"); await client.AuthenticateAsync(_emailConfig.UserName, _emailConfig.Password); await client.SendAsync(mailMessage); } catch { //log an error message or throw an exception, or both. throw; } finally { await client.DisconnectAsync(true); client.Dispose(); } } }
private async Task SendAsync(MimeMessage mailMessage) { using (var client = new MailKit.Net.Smtp.SmtpClient()) { try { //client.ServerCertificateValidationCallback = (s, c, h, e) => true; await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.Port, SecureSocketOptions.Auto); client.AuthenticationMechanisms.Remove("XOAUTH2"); // Note: only needed if the SMTP server requires authentication await client.AuthenticateAsync(_emailConfig.UserName, _emailConfig.Password); await client.SendAsync(mailMessage); } catch (Exception ex) { throw; } finally { await client.DisconnectAsync(true); client.Dispose(); } } }
private async Task SendAsync(MimeMessage mailMessage) { using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient()) { try { await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.Port, true); //client.AuthenticationMechanisms.Remove("XOAUTH2"); await client.AuthenticateAsync(_emailConfig.UserName, _emailConfig.Password); await client.SendAsync(mailMessage); } catch (Exception) { throw; } finally { await client.DisconnectAsync(true); client.Dispose(); } } }
private void Send(MimeMessage mailMessage) { using (var client = new MailKit.Net.Smtp.SmtpClient()) { try { client.Connect(_emailConfig.SmtpServer, _emailConfig.Port, SecureSocketOptions.None); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(_emailConfig.UserName, _emailConfig.Password); client.Send(mailMessage); } catch (Exception ex) { ErrMsg = ex.Message; //log an error message or throw an exception or both. //throw; } finally { client.Disconnect(true); client.Dispose(); } } }
private async Task <int> SendAsync(MimeMessage mailMessage) { int Result = 0; using (var client = new MailKit.Net.Smtp.SmtpClient()) { try { await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.Port, SecureSocketOptions.None); client.AuthenticationMechanisms.Remove("XOAUTH2"); await client.AuthenticateAsync(_emailConfig.UserName, _emailConfig.Password); await client.SendAsync(mailMessage); Result = 1; } catch (Exception ex) { ErrMsg = ex.Message; Result = -1; //log an error message or throw an exception, or both. //throw; } finally { await client.DisconnectAsync(true); client.Dispose(); } } return(Result); }
public ActionResult <IEnumerable <bool> > SendEmail() { try { var message = new MimeMessage(); message.From.Add(new MailboxAddress("HomeShopping", "*****@*****.**")); message.To.Add(new MailboxAddress("User", "*****@*****.**")); message.Subject = "My First Email"; message.Body = new TextPart("plain") { Text = "ABC" }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.gmail.com", 587, false); client.Authenticate("*****@*****.**", "Minhman23199"); client.Send(message); client.Disconnect(true); client.Dispose(); } } catch (Exception ex) { Console.WriteLine(ex.Message); return(StatusCode(500, "Error occured")); } return(Ok(true)); }
public async Task <SmtpClient> BuildClientAsync() { var client = new SmtpClient(); try { await ConfigureClient(client); return(client); } catch { client.Dispose(); throw; } }
//[HttpGet] //public IEnumerable<string> Get() //{ // return new string[] { "value1", "value2" }; //} public async Task SendEmailAsync(string email, string subject, string message) { try { var mimeMessage = new MimeMessage(); mimeMessage.From.Add(new MailboxAddress(_emailSettings.SenderName, _emailSettings.Sender)); mimeMessage.To.Add(new MailboxAddress(email)); mimeMessage.Subject = subject; mimeMessage.Body = new TextPart("html") { Text = message }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; if (_env.IsDevelopment()) { // The third parameter is useSSL (true if the client should make an SSL-wrapped // connection to the server; otherwise, false). await client.ConnectAsync(_emailSettings.MailServer, _emailSettings.MailPort, false); } else { await client.ConnectAsync(_emailSettings.MailServer); } // Note: only needed if the SMTP server requires authentication await client.AuthenticateAsync(_emailSettings.Sender, _emailSettings.Password); await client.SendAsync(mimeMessage); await client.DisconnectAsync(true); client.Dispose(); } } catch (Exception ex) { // TODO: handle exception throw new InvalidOperationException(ex.Message); } }
// GET: Workers/SendEmail/ public IActionResult SendEmail(int id) { try { MimeMessage message = new MimeMessage(); MailboxAddress fromAddress = new MailboxAddress("Admin", "*****@*****.**"); message.From.Add(fromAddress); // Get worker from ID Worker worker = _context.Worker.FirstOrDefault(x => x.Id == id); MailboxAddress toAddress = new MailboxAddress(worker.FirstName, worker.Email); message.To.Add(toAddress); message.Subject = "Test email for ASP.net Core with MailKit"; BodyBuilder bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = (@"<h2><center> HELLO </center></h2> <b>You just received this automated email to ask for something using <u>HTMLBODY</u></b> <br /> <i>Kind Regars</i>"); message.Body = bodyBuilder.ToMessageBody(); MailKit.Net.Smtp.SmtpClient smtpClient = new MailKit.Net.Smtp.SmtpClient(); smtpClient.Connect("smtp.gmail.com", 587); smtpClient.Authenticate("*****@*****.**", "Destiny9955"); smtpClient.Send(message); smtpClient.Disconnect(true); smtpClient.Dispose(); TempData["alertMessage"] = "Whatever you want to alert the user with"; return(View()); } catch { return(Content("<script>alert('Email Not Sent');</script>")); } }
public void SendEmail(ApplicationUser reciever, string subject, string senderName, string senderEmail, string elementToSent, string textBody) { MimeMessage message = new MimeMessage(); MailboxAddress from = new MailboxAddress(senderName, senderEmail); message.From.Add(from); MailboxAddress to = new MailboxAddress(reciever.UserName, reciever.Email); message.To.Add(to); message.Subject = subject; BodyBuilder bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = textBody + elementToSent; bodyBuilder.TextBody = textBody; //bodyBuilder.Attachments.Add(_hostingEnvironment.WebRootPath + "\\file.png"); message.Body = bodyBuilder.ToMessageBody(); using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.SslProtocols = SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13; client.Connect("smtp.gmail.com", 465, true); client.Authenticate(" ***email address*** ", " ***password*** "); client.Send(message); client.Disconnect(true); client.Dispose(); } }
protected override void DoJob() { SmtpClient smtpClient = null; try { _tenantManager.SetCurrentTenant(_tenantID); _securityContext.AuthenticateMeWithoutCookie(_authManager.GetAccountByID(_tenantID, _currUser)); smtpClient = GetSmtpClient(); var userCulture = _userManager.GetUsers(_currUser).GetCulture(); Thread.CurrentThread.CurrentCulture = userCulture; Thread.CurrentThread.CurrentUICulture = userCulture; var contactCount = _contactID.Count; if (contactCount == 0) { Complete(); return; } var from = new MailboxAddress(_smtpSetting.SenderDisplayName, _smtpSetting.SenderEmailAddress); var filePaths = new List <string>(); var fileDao = _filesIntegration.DaoFactory.GetFileDao <int>(); foreach (var fileID in _fileID) { var fileObj = fileDao.GetFile(fileID); if (fileObj == null) { continue; } using (var fileStream = fileDao.GetFileStream(fileObj)) { var directoryPath = Path.Combine(Path.GetTempPath(), "teamlab", _tenantID.ToString(), "crm/files/mailsender/"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } var filePath = Path.Combine(directoryPath, fileObj.Title); using (var newFileStream = File.Create(filePath)) { fileStream.CopyTo(newFileStream); } filePaths.Add(filePath); } } var templateManager = new MailTemplateManager(_daoFactory); var deliveryCount = 0; try { Error = string.Empty; foreach (var contactID in _contactID) { _exactPercentageValue += 100.0 / contactCount; Percentage = Math.Round(_exactPercentageValue); PublishChanges(); if (IsCompleted) { break; // User selected cancel } var contactInfoDao = _daoFactory.GetContactInfoDao(); var startDate = DateTime.Now; var contactEmails = contactInfoDao.GetList(contactID, ContactInfoType.Email, null, true); if (contactEmails.Count == 0) { continue; } var recipientEmail = contactEmails[0].Data; if (!recipientEmail.TestEmailRegex()) { Error += string.Format(CRMCommonResource.MailSender_InvalidEmail, recipientEmail) + "<br/>"; continue; } var to = new MailboxAddress(recipientEmail); var mimeMessage = new MimeMessage { Subject = _subject }; mimeMessage.From.Add(from); mimeMessage.To.Add(to); var bodyBuilder = new BodyBuilder { HtmlBody = templateManager.Apply(_bodyTempate, contactID) }; foreach (var filePath in filePaths) { bodyBuilder.Attachments.Add(filePath); } mimeMessage.Body = bodyBuilder.ToMessageBody(); mimeMessage.Headers.Add("Auto-Submitted", "auto-generated"); _log.Debug(GetLoggerRow(mimeMessage)); var success = false; try { smtpClient.Send(mimeMessage); success = true; } catch (SmtpCommandException ex) { _log.Error(Error, ex); Error += string.Format(CRMCommonResource.MailSender_FailedDeliverException, recipientEmail) + "<br/>"; } if (success) { if (_storeInHistory) { AddToHistory(contactID, string.Format(CRMCommonResource.MailHistoryEventTemplate, mimeMessage.Subject), _daoFactory); } var endDate = DateTime.Now; var waitInterval = endDate.Subtract(startDate); deliveryCount++; var estimatedTime = TimeSpan.FromTicks(waitInterval.Ticks * (_contactID.Count - deliveryCount)); SetProperty("RecipientCount", _contactID.Count); SetProperty("EstimatedTime", estimatedTime.ToString()); SetProperty("DeliveryCount", deliveryCount); } if (Percentage > 100) { Percentage = 100; PublishChanges(); } } } catch (OperationCanceledException) { _log.Debug("cancel mail sender"); } finally { foreach (var filePath in filePaths) { if (File.Exists(filePath)) { File.Delete(filePath); } } } SetProperty("RecipientCount", _contactID.Count); SetProperty("EstimatedTime", TimeSpan.Zero.ToString()); SetProperty("DeliveryCount", deliveryCount); } catch (SocketException e) { Error = e.Message; _log.Error(Error); } finally { if (smtpClient != null) { smtpClient.Dispose(); } Complete(); } }
public IActionResult SenndEmail(string email) { MimeMessage message = new MimeMessage(); MailboxAddress from = new MailboxAddress("Admin", "*****@*****.**"); message.From.Add(from); MailboxAddress to = new MailboxAddress("User", "*****@*****.**"); message.To.Add(to); message.Subject = "This is email subject"; BodyBuilder bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = "<h1>Hello World!</h1>"; bodyBuilder.TextBody = "Hello World!"; message.Body = bodyBuilder.ToMessageBody(); MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient(); // client.Connect("smtp.wp.pl", 465, false); //client.Authenticate("*****@*****.**", "KAMI21`kami"); client.Connect("smtp.gmail.com", 465); client.Authenticate("kar.matgogle", "NieUrzGmail@"); client.Send(message); client.Disconnect(true); client.Dispose(); // Command-line argument must be the SMTP host. //SmtpClient client = new SmtpClient("smtp.wp.pl", 465); //// Specify the email sender. //// Create a mailing address that includes a UTF8 character //// in the display name. //MailAddress from = new MailAddress("*****@*****.**", // "KAMI21`kami", //System.Text.Encoding.UTF8); //// Set destinations for the email message. //MailAddress to = new MailAddress("*****@*****.**"); //// Specify the message content. //MailMessage message = new MailMessage(from, to); //message.Body = "This is a test email message sent by an application. "; //// Include some non-ASCII characters in body and subject. //string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' }); //message.Body += Environment.NewLine + someArrows; //message.BodyEncoding = System.Text.Encoding.UTF8; //message.Subject = "test message 1" + someArrows; //message.SubjectEncoding = System.Text.Encoding.UTF8; //// Set the method that is called back when the send operation ends. //client.SendCompleted += new //SendCompletedEventHandler(SendCompletedCallback); //// The userState can be any object that allows your callback //// method to identify this send operation. //// For this example, the userToken is a string constant. //string userState = "test message1"; //client.SendAsync(message, userState); ////Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit."); ////string answer = Console.ReadLine(); //// If the user canceled the send, and mail hasn't been sent yet, //// then cancel the pending operation. ////if (answer.StartsWith("c") && mailSent == false) ////{ //// client.SendAsyncCancel(); ////} //// Clean up. //message.Dispose(); //Console.WriteLine("Goodbye."); return(RedirectToAction("index", "Home")); }