public void Send(EmailDependencies email) { try { var message = new MimeMessage(); message.From.Add(new MailboxAddress(email.FromName, email.FromAddress)); message.To.Add(new MailboxAddress(email.ToName, email.ToAddress)); message.To.Add(new MailboxAddress(email.FromName, email.FromAddress)); message.Subject = email.Title; message.Body = new TextPart("html") { Text = email.content }; using (var client = new SmtpClient()) { client.Connect("mail.bizmonger.net", 587, false); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); // Note: only needed if the SMTP server requires authentication client.Authenticate(Configuration.ServerEmail, Configuration.Password); client.Send(message); client.Disconnect(true); } } catch (Exception ex) { var errorMessage = ex.GetBaseException().Message; Debug.WriteLine(errorMessage); } }
public void SendMessage() { string msg = ""; switch (CurrEmailType) { case EmailType.PRENOTA: msg = PrenotaSubject; FromMailAddress = PrenotaFromAddress; break; case EmailType.INFO: msg = InfoSubject; FromMailAddress = InfoFromAddress; break; } string subject = string.Format(msg, Message.Nome, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")); string body = string.Format("Nome : {0}\nNumero : {1}\nE-Mail : {2}\nMessaggio :\n{3}", Message.Nome, Message.Telefono, Message.Email, Message.Messaggio); var message = new MimeMessage(); message.From.Add(FromMailAddress); message.To.Add(ToAddress); message.Subject = subject; message.Body = new TextPart("plain") {Text = body}; try { using (var client = new SmtpClient()) { client.Connect("smtp.gmail.com", 465, true); client.AuthenticationMechanisms.Remove("XOAUTH"); client.Authenticate("*****@*****.**", "At066bn1!"); client.Send(message); client.Disconnect(true); } Result = EmailResult.SUCCESS; MessageResult = "Messaggio inviato correttamente"; } catch (Exception ex) { Result = EmailResult.FAIL; MessageResult = ex.Message; } }
public static void SendEmail(System.Net.Mail.MailMessage message, bool enableSsl) { try { var m = new MimeMessage(); m.From.Add(new MailboxAddress("Forgot Password", message.From.Address)); m.To.Add(new MailboxAddress("", message.To[0].Address)); m.Subject = message.Subject; if (message.IsBodyHtml) m.Body = new TextPart("html") { Text = message.Body }; else m.Body = new TextPart("plain") { Text = message.Body }; using (var client = new SmtpClient()) { client.Connect(Settings.GetValue<string>("smtpHost"), Settings.GetValue<int>("smtpPort"), enableSsl); client.Authenticate(new NetworkCredential(Settings.GetValue<string>("serverEmail"), Settings.GetValue<string>("serverEmailPassword"))); client.Send(m); client.Disconnect(true); } } catch (Exception ex) { Logger.Error(ex); } }
/// <summary> /// Called when the operation finishes /// </summary> /// <param name="result">The result object, if this derives from an exception, the operation failed</param> public void OnFinish(object result) { //If no email is supplied, then skip if (string.IsNullOrEmpty(m_to)) return; //If we do not report this action, then skip if (!m_sendAll && !string.Equals(m_operationname, "Backup", StringComparison.InvariantCultureIgnoreCase)) return; if (string.Equals(m_operationname, "Backup", StringComparison.InvariantCultureIgnoreCase)) { MailLevels level; if (result is Exception) level = MailLevels.Error; else if (result != null && result is Library.Interface.IBackupResults && (result as Library.Interface.IBackupResults).Errors.Count() > 0) level = MailLevels.Warning; else level = MailLevels.Success; m_parsedresultlevel = level.ToString(); if (m_level != MailLevels.All) { //Check if this level should send mail if ((m_level & level) == 0) return; } } try { string body = m_body; string subject = m_subject; if (body != DEFAULT_BODY && System.IO.File.Exists(body)) body = System.IO.File.ReadAllText(body); body = ReplaceTemplate(body, result, false); subject = ReplaceTemplate(subject, result, true); var message = new MimeMessage(); MailboxAddress mailbox; foreach (string s in m_to.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)) if(MailboxAddress.TryParse(s.Replace("\"", ""), out mailbox)) message.To.Add(mailbox); MailboxAddress mailboxToFirst = (MailboxAddress) message.To[0]; string toMailDomain = mailboxToFirst.Address.Substring(mailboxToFirst.Address.LastIndexOf("@") + 1); string from = m_from.Trim().Replace("\"", ""); if (from.IndexOf('@') < 0) { if (from.EndsWith(">")) from = from.Insert(from.Length - 1, "@" + toMailDomain); else from = string.Format("No Reply - Backup report <{0}@{1}>", from, toMailDomain); } if (MailboxAddress.TryParse(from, out mailbox)) message.From.Add(mailbox); message.Subject = subject; message.Body = new TextPart("plain") { Text = body, ContentTransferEncoding = ContentEncoding.EightBit }; List<string> servers = null; if (string.IsNullOrEmpty(m_server)) { var dnslite = new DnsLib.DnsLite(); var dnslist = new List<string>(); //Grab all IPv4 adresses foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces()) try { foreach (IPAddress dnsAdress in networkInterface.GetIPProperties().DnsAddresses) if (dnsAdress.AddressFamily == AddressFamily.InterNetwork) dnslist.Add(dnsAdress.ToString()); } catch { } dnslist = dnslist.Distinct().ToList(); // If we have no DNS servers, try Google and OpenDNS if (dnslist.Count == 0) { // https://developers.google.com/speed/public-dns/ dnslist.Add("8.8.8.8"); dnslist.Add("8.8.4.4"); //http://www.opendns.com/opendns-ip-addresses/ dnslist.Add("208.67.222.222"); dnslist.Add("208.67.220.220"); } var oldStyleList = new ArrayList(); foreach(var s in dnslist) oldStyleList.Add(s); dnslite.setDnsServers(oldStyleList); servers = dnslite.getMXRecords(toMailDomain).OfType<MXRecord>().OrderBy(record => record.preference).Select(x => "smtp://" + x.exchange).Distinct().ToList(); if (servers.Count == 0) throw new IOException(Strings.SendMail.FailedToLookupMXServer(OPTION_SERVER)); } else { servers = (from n in m_server.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries) let srv = (n == null || n.IndexOf("://", StringComparison.InvariantCultureIgnoreCase) > 0) ? n : "smtp://" + n where !string.IsNullOrEmpty(srv) select srv).Distinct().ToList(); } Exception lastEx = null; string lastServer = null; foreach(var server in servers) { if (lastEx != null) Logging.Log.WriteMessage(Strings.SendMail.SendMailFailedRetryError(lastServer, lastEx.Message, server), LogMessageType.Warning, lastEx); lastServer = server; try { using (MemoryStream ms = new MemoryStream()) { try { using (var client = new SmtpClient(new MailKit.ProtocolLogger(ms))) { client.Timeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; client.Connect(new System.Uri(server)); if (!string.IsNullOrEmpty(m_username) && !string.IsNullOrEmpty(m_password)) client.Authenticate(m_username, m_password); client.Send(message); client.Disconnect(true); } } finally { var log = Encoding.UTF8.GetString(ms.GetBuffer()); Logging.Log.WriteMessage(Strings.SendMail.SendMailLog(log), LogMessageType.Profiling); } } lastEx = null; Logging.Log.WriteMessage(Strings.SendMail.SendMailSuccess(server), LogMessageType.Information); break; } catch (Exception ex) { lastEx = ex; } } if (lastEx != null) throw lastEx; } catch (Exception ex) { Exception top = ex; var sb = new StringBuilder(); while (top != null) { if (sb.Length != 0) sb.Append("--> "); sb.AppendFormat("{0}: {1}{2}", top.GetType().FullName, top.Message, Environment.NewLine); top = top.InnerException; } Logging.Log.WriteMessage(Strings.SendMail.SendMailFailedError(sb.ToString()), LogMessageType.Warning, ex); } }
// Gửi email, theo nội dung trong mailContent public async Task SendMail(MailContent mailContent) { var email = new MimeMessage(); email.Sender = MailboxAddress.Parse(mailSettings.Mail); email.To.Add(MailboxAddress.Parse(mailContent.To)); email.Subject = mailContent.Subject; var builder = new BodyBuilder(); builder.HtmlBody = mailContent.Body; email.Body = builder.ToMessageBody(); // dùng SmtpClient của MailKit using var smtp = new MailKit.Net.Smtp.SmtpClient(); try { smtp.Connect(mailSettings.Host, mailSettings.Port, SecureSocketOptions.StartTls); smtp.Authenticate(mailSettings.Mail, mailSettings.Password); await smtp.SendAsync(email); } catch (Exception ex) { logger.LogInformation("Lỗi gửi mail"); logger.LogError(ex.Message); } smtp.Disconnect(true); logger.LogInformation("send mail to " + mailContent.To); }
public bool Send(string subject, string message, string senderEmail, string receiverEmail) { using (SmtpClient client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect(_emailConfiguration.Host, _emailConfiguration.Port, MailKit.Security.SecureSocketOptions.SslOnConnect); client.Authenticate(_emailConfiguration.Username, _emailConfiguration.Password); MimeMessage mailMessage = new MimeMessage { Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = message }, From = { new MailboxAddress(_emailConfiguration.DisplayName, senderEmail) }, To = { new MailboxAddress(receiverEmail) }, Subject = subject }; client.Send(mailMessage); client.Disconnect(true); } return(true); }
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 void SendMail(AlarmMail _alarm) { client = new MailKit.Net.Smtp.SmtpClient(); List <User> recipients = GetMailRecipients(_alarm); if (recipients.Count > 0) { var message = new MimeMessage(); foreach (User recipient in recipients) { message.To.Add(new MailboxAddress(recipient.Name + " " + recipient.Surname, recipient.Email)); } message.From.Add(new MailboxAddress(Constants.MessageBoxHeader, UserName)); message.Subject = _alarm.EMailSubject; message.Body = new TextPart("plain") { Text = @_alarm.EmailText }; if (ConnectToMailServer()) { client.Send(message); Log.Instance.Info("{0}: {1} adlı alarm {2} grubundaki tüm kullanıcılara gönderildi.", this.GetType().Name, _alarm.Name, _alarm.MailGroupName); client.Disconnect(true); } else { Log.Instance.Error("{0} isimli alarm mail server'a bağlanılamadı için gönderilemedi", _alarm.Name); } } }
public void Send(TaskReminder reminder) { var message = _translator.Translate(reminder); using (var client = new SmtpClient()) { //_smtpDetails = new SmtpDetails() //{ // Server = "smtp.friends.com", // Port = 587, // UserName = "******", // Password = "******" //}; client.Connect(_smtpDetails.Server, _smtpDetails.Port, false); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); // Note: only needed if the SMTP server requires authentication client.Authenticate(_smtpDetails.UserName, _smtpDetails.Password); client.Send(message); client.Disconnect(true); } }
public bool Send(string toEmail, string toName, string subject, string body) { var message = new MimeMessage(); message.From.Add(new MailboxAddress(Config.DisplayName, Config.Username)); message.To.Add(new MailboxAddress(toName, toEmail)); message.Subject = subject; var bodyBuilder = new BodyBuilder(); var newBody = "<img src='https://vfr.beawre.com/Beawre_logo.png' style='width: 140px; height: 40px;' /><br/><br/>" + body; bodyBuilder.HtmlBody = newBody; message.Body = bodyBuilder.ToMessageBody(); using (var client = new SmtpClient()) { // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect(Config.Url, 587, false); // Note: only needed if the SMTP server requires authentication client.Authenticate(Config.Username, Config.Password); client.Send(message); client.Disconnect(true); return(true); } }
public IActionResult Index() { var message = new MimeMessage(); message.From.Add(new MailboxAddress("Hello", "*****@*****.**")); message.To.Add(new MailboxAddress("Send mail asp net core", "*****@*****.**")); message.Subject = "Learn to send mail using asp net core"; //message.Body = new TextPart("plain") //{ // Text = "I am using mailkit to send email with asp net core 2.2" + // "<h1>HEllO<h1>" //}; BodyBuilder bodyBuilder = new BodyBuilder(); using (StreamReader SourceReader = System.IO.File.OpenText(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\TextFile.txt", ""))) { bodyBuilder.HtmlBody = SourceReader.ReadToEnd(); } message.Body = bodyBuilder.ToMessageBody(); using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.ServerCertificateValidationCallback = (s, c, h, e) => true; //client.Connect("MAIL_SERVER", 465, SecureSocketOptions.SslOnConnect); client.Connect("smtp.gmail.com", 587, false); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate("*****@*****.**", "09041998123"); client.Send(message); client.Disconnect(true); } return(View()); }
public static void FrontEnd(string[] args) { MainActivity = new MainActivity (); var message = new MimeMessage (); message.From.Add (new MailboxAddress ("test", "*****@*****.**")); message.To.Add (new MailboxAddress (MainActivity.nome, MainActivity.email)); message.Subject = "Obrigado por se candidatar"; message.Body = new TextPart ("plain") { Text = @"Obrigado por se candidatar, assim que tivermos uma vaga disponível para programador Front-End entraremos em contato." }; using (var client = new SmtpClient ()) { client.Connect ("smtp.test.com", 587, false); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove ("XOAUTH2"); // Note: only needed if the SMTP server requires authentication client.Authenticate ("test", "password"); client.Send (message); client.Disconnect (true); } }
public static void PrintCapabilities () { using (var client = new SmtpClient ()) { client.Connect ("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect); if (client.Capabilities.HasFlag (SmtpCapabilities.Authentication)) { var mechanisms = string.Join (", ", client.AuthenticationMechanisms); Console.WriteLine ("The SMTP server supports the following SASL mechanisms: {0}", mechanisms); // Note: if we don't want MailKit to use a particular SASL mechanism, we can disable it like this: client.AuthenticationMechanisms.Remove ("XOAUTH2"); client.Authenticate ("username", "password"); } if (client.Capabilities.HasFlag (SmtpCapabilities.Size)) Console.WriteLine ("The SMTP server has a size restriction on messages: {0}.", client.MaxSize); if (client.Capabilities.HasFlag (SmtpCapabilities.Dsn)) Console.WriteLine ("The SMTP server supports delivery-status notifications."); if (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime)) Console.WriteLine ("The SMTP server supports Content-Transfer-Encoding: 8bit"); if (client.Capabilities.HasFlag (SmtpCapabilities.BinaryMime)) Console.WriteLine ("The SMTP server supports Content-Transfer-Encoding: binary"); if (client.Capabilities.HasFlag (SmtpCapabilities.UTF8)) Console.WriteLine ("The SMTP server supports UTF-8 in message headers."); client.Disconnect (true); } }
/// <summary> /// MAIL KIT /// Info : http://dotnetthoughts.net/how-to-send-emails-from-aspnet-core/ /// </summary> public static void SendEmail(string email, string name, string subject, string message,byte[] attachment = null,string attachmentName ="Facture") { var mimeMessage = new MimeMessage(); mimeMessage.From.Add(new MailboxAddress(Configurations.Application.StolonsLabel, Configurations.Application.MailAddress)); mimeMessage.To.Add(new MailboxAddress(name, email)); mimeMessage.Subject = subject; var bodyBuilder = new BodyBuilder(); if(attachment != null) bodyBuilder.Attachments.Add(attachmentName,attachment); bodyBuilder.HtmlBody = message; mimeMessage.Body = bodyBuilder.ToMessageBody(); try { using (var client = new SmtpClient()) { client.Connect(Configurations.Application.MailSmtp, Configurations.Application.MailPort, false); client.AuthenticationMechanisms.Remove("XOAUTH2"); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.Authenticate(Configurations.Application.MailAddress, Configurations.Application.MailPassword); client.Send(mimeMessage); client.Disconnect(true); } } catch (Exception except) { Console.WriteLine("Error on sending mail : " + except.Message); } }
public async Task SendEmailAsync(MailRequest mailRequest) { var email = new MimeMessage(); email.Sender = MailboxAddress.Parse(_mailSettings.Mail); email.To.Add(MailboxAddress.Parse(mailRequest.ToEmail)); email.Subject = mailRequest.Subject; var builder = new BodyBuilder(); if (mailRequest.Attachments != null) { byte[] fileBytes; foreach (var file in mailRequest.Attachments) { if (file.Length > 0) { using (var ms = new MemoryStream()) { file.CopyTo(ms); fileBytes = ms.ToArray(); } builder.Attachments.Add(file.FileName, fileBytes, ContentType.Parse(file.ContentType)); } } } builder.HtmlBody = mailRequest.Body; email.Body = builder.ToMessageBody(); using var smtp = new MailKit.Net.Smtp.SmtpClient(); smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls); smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password); await smtp.SendAsync(email); smtp.Disconnect(true); }
public void BtnSubmit_Clicked(object sender, EventArgs e) { if (FormValidation()) //TODO: Remove comments { return; } #region WriteMessage string msg = "Jméno:" + editName.Text + Environment.NewLine + "Příjmení:" + editName2.Text + Environment.NewLine + "Email:" + editMail.Text + Environment.NewLine + "Telefon:" + editPhone.Text + Environment.NewLine + "Počet bodů:" + Visited; MailMessage message; try { message = new MailMessage() { From = new MailAddress("*****@*****.**"), To = { new MailAddress("*****@*****.**") }, Subject = "Tropic - Soutěž", Body = msg }; } catch (Exception ex) { DisplayAlert("Chyba", ex.ToString(), "Ok"); return; } #endregion #region SendEmail try { using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.gmail.com", 587); client.SslProtocols = System.Security.Authentication.SslProtocols.Default; client.Authenticate("*****@*****.**", "tropic213021"); client.Send((MimeMessage)message); client.Disconnect(true); } Settings.FinishedEvents += Settings.CurrentEvent.Id.ToString() + ";"; List <string> list = Settings.Stands.Split('.').ToList(); list.RemoveAll(x => x.StartsWith(Settings.CurrentEvent.Id + ".")); DisplayAlert("Posláno", "Jste úspěšně zaregistrováni do soutěže.", "Ok"); } catch (Exception ex) { DisplayAlert("Chyba", ex.Message, "Ok"); Crashes.TrackError(ex); return; } #endregion }
public ActionResult EditEvent(Event events) { var CurrentUser = User.Identity.GetUserId(); var FoundEvent = db.events.Where(e => e.EventId == events.EventId).SingleOrDefault(); try { FoundEvent.EventName = events.EventName; FoundEvent.EventDate = events.EventDate; FoundEvent.Street = events.Street; FoundEvent.City = events.City; FoundEvent.State = events.State; FoundEvent.Zip = events.Zip; FoundEvent.TicketsAvailable = events.TicketsAvailable; FoundEvent.TicketPrice = events.TicketPrice; db.SaveChanges(); var foundbookmarkers = db.bookmarks.Where(b => b.EventId == FoundEvent.EventId).ToList(); List <Guest> foundGuest = new List <Guest>(); foreach (var item in foundbookmarkers) { var guestFound = db.guests.Where(g => g.GuestId == item.GuestId).Single(); foundGuest.Add(guestFound); } foreach (Guest guest in foundGuest) { var message = new MimeMessage(); message.From.Add(new MailboxAddress($"{FoundEvent.EventName}", "*****@*****.**")); message.To.Add(new MailboxAddress($"{guest.FirstName}, {guest.LastName}", "*****@*****.**")); message.Subject = "Event Update"; message.Body = new TextPart("plain") { Text = $@"Hello , We would like to notify you on our updates to our event. -- GroupCapStone" }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect("smtp.gmail.com", 587, false); client.Authenticate("sweepsstackproject", "sweep12!!"); client.Send(message); client.Disconnect(true); } } return(RedirectToAction("MyEvents")); } catch { return(RedirectToAction("MyEvents")); } }
private static void SendMimeMessage(MimeMessage mail) { var client = new MailKit.Net.Smtp.SmtpClient(); client.Connect(HostIP, HostPort, false); client.Authenticate(Username, Pass); client.Send(mail); client.Disconnect(true); }
public static void SendMessage (MimeMessage message) { using (var client = new SmtpClient (new ProtocolLogger ("smtp.log"))) { client.Connect ("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect); client.Authenticate ("username", "password"); client.Send (message); client.Disconnect (true); } }
public bool SendForgotPasswordResetLink(string path, AppUser appUser, AppUserAccessKey accessKey) { bool sucess = false; //From Address var FromAddress = "*****@*****.**"; var FromAdressTitle = "Camerack Studio"; //To Address var toVendor = appUser.Email; //var toCustomer = email; var ToAdressTitle = "Camerack Studio"; var Subject = "Password Reset."; //var BodyContent = message; //Smtp Server var smtpServer = new AppConfig().EmailServer; //Smtp Port Number var smtpPortNumber = new AppConfig().Port; var mimeMessageVendor = new MimeMessage(); mimeMessageVendor.From.Add(new MailboxAddress(FromAdressTitle, FromAddress)); mimeMessageVendor.To.Add(new MailboxAddress(ToAdressTitle, toVendor)); mimeMessageVendor.Subject = Subject; BodyBuilder bodyBuilder = new BodyBuilder(); using (StreamReader data = File.OpenText(path)) { if (data.BaseStream != null) { //manage content bodyBuilder.HtmlBody = data.ReadToEnd(); var body = bodyBuilder.HtmlBody; var replace = body.Replace("NAME", appUser.Name); replace = replace.Replace("DATE", DateTime.Now.ToString(CultureInfo.InvariantCulture)); replace = replace.Replace("URL", new AppConfig().MarketPlaceBaseUrl + "Account/ForgotPassword?accessCode=" + accessKey.PasswordAccessCode); bodyBuilder.HtmlBody = replace; mimeMessageVendor.Body = bodyBuilder.ToMessageBody(); } } using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect(smtpServer, smtpPortNumber, true); // Note: only needed if the SMTP server requires authentication // Error 5.5.1 Authentication client.Authenticate(new AppConfig().Email, new AppConfig().Password); client.Send(mimeMessageVendor); sucess = true; client.Disconnect(true); } return(sucess); }
public async Task SendEmailAsync(History history) { var user = await _userService.GetUserAsync(history.CreatorId.ToString()); var bonus = await _bonusService.FindBonusByIdAsync(history.BonusId); var vendor = await _vendorService.GetVendorByIdAsync(bonus.Company.Id); string promoCode = vendor.Name + RandomString(5); var strToUser = String.Format("Hi {0} {1} your order recived. You ordered {2} by {3} company." + " For more information, please call {4} or email {5}." + " Validity period from {6} to {7}." + " Your promo code is {8}", user.FirstName, user.LastName, bonus.Title, bonus.Company.Name, bonus.Phone, vendor.Email, bonus.DateStart, bonus.DateEnd, promoCode); var strToVendor = String.Format("Dear {0}, {1} {2} will come to you with promo. PromoCode is {3}", vendor.Name, user.FirstName, user.LastName, promoCode); MimeMessage messageToUser = new MimeMessage(); messageToUser.From.Add(new MailboxAddress(vendor.Name, vendor.Email)); messageToUser.To.Add(new MailboxAddress(user.Email)); messageToUser.Subject = "Get bonus"; messageToUser.Body = new BodyBuilder() { HtmlBody = String.Format("<div>{0}</div>", strToUser) }.ToMessageBody(); MimeMessage messageToVendor = new MimeMessage(); messageToVendor.From.Add(new MailboxAddress(user.FirstName, user.Email)); messageToVendor.To.Add(new MailboxAddress(vendor.Email)); messageToVendor.Subject = "Get bonus"; messageToVendor.Body = new BodyBuilder() { HtmlBody = String.Format("<div>{0}</div>", strToVendor) }.ToMessageBody(); using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect(_emailSettings.Value.SMTPServer, _emailSettings.Value.SMTPServerPort, true); client.Authenticate(_emailSettings.Value.EmailAddress, _emailSettings.Value.Password); client.Send(messageToUser); client.Send(messageToVendor); client.Disconnect(true); } }
public async Task <ServiceResponse <int> > Register(User user, string password) { ServiceResponse <int> response = new ServiceResponse <int>(); if (await UserExists(user.Email)) { response.Success = false; response.Message = "User already exists"; return(response); } //koristimo da ne bismo slali password kao string, nije bezbedno CreatePasswordHash(password, out byte[] passwordHash, out byte[] passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; await _context.Users.AddAsync(user); await _context.SaveChangesAsync(); response.Data = user.Id; #region email string emailData = "http:localhost:4200/confirm/" + user.Id; var message = new MimeMessage(); message.From.Add(new MailboxAddress("Email confirmation", "*****@*****.**")); message.To.Add(new MailboxAddress("Luka", "*****@*****.**")); message.Subject = "Email confirmation"; var body = new StringBuilder(); body.AppendLine("Click the link to complete your registration proccess and activate your account: "); body.AppendFormat("<a href=\"http://*****:*****@gmail.com", "kostadin"); client.Send(message); client.Disconnect(true); } #endregion email return(response); }
public void SendChangeComissionEmail(string emaill, string sellerName, string productName, int comission) { // create email message var email = new MimeMessage(); email.Sender = MailboxAddress.Parse("*****@*****.**"); email.To.Add(MailboxAddress.Parse(emaill)); email.Subject = " ثبت نام در بازارچه اینترنتی صنایع دستی"; var body = "با سلام صنعتگر گرامی "; body += sellerName; body += System.Environment.NewLine; body += "کمیسیون محصول "; body += productName; body += " "; body += "شما به "; body += comission.ToString(); body += " "; body += "درصد تغییر یافت."; body += System.Environment.NewLine; body += "بازارچه صنایع دستی سارای"; body += System.Environment.NewLine; body += "بازارچه صنایع دستی سارای"; body += System.Environment.NewLine; body += "http://www.saraycrafts.com/"; email.Body = new TextPart(TextFormat.Text) { Text = body }; try { using var smtp = new MailKit.Net.Smtp.SmtpClient(); smtp.Connect("tabrizhandicrafts.com", 587, SecureSocketOptions.Auto); // hotmail //smtp.Connect("smtp.live.com", 587, SecureSocketOptions.StartTls); // office 365 //smtp.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls); smtp.Authenticate("*****@*****.**", "123456qQ"); smtp.Send(email); smtp.Disconnect(true); } catch (Exception ex) { } // send email }
public async Task <ActionResult> SendLetterAsync(int id) { var _user = await GetCurrentUserAsync(); var userstate = await GetUserDetails(_user); if (userstate == 2) { List <Registration> r = db.Registrations.ToList(); if (r.Count() == 0) { return(View("List")); } TipAndLetter t = db.TipAndLetters.Include(tl => tl.TipStatus).Include(tl => tl.Tag).SingleOrDefault(tl => tl.TipAndLetterID == id); string title = t.Title; string Message = t.Message; string status = t.TipStatus.TipStatusName; string subject = t.Tag.TagName + " From DRHC Hospital"; string mailmessage = "<h2 class='text-center'><strong>" + title + "</strong></h2>"; mailmessage += "<p>" + Message + "</p>"; foreach (var user in r) { string email = user.UserEmail; string username = user.UserFName + " " + user.UserLName; var msg = new MimeMessage(); msg.From.Add(new MailboxAddress("admin", "*****@*****.**")); msg.To.Add(new MailboxAddress(username, email)); msg.Subject = subject; msg.Body = new TextPart("html") { Text = mailmessage }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.gmail.com", 587, false); client.Authenticate("*****@*****.**", "mailtest1234"); client.Send(msg); client.Disconnect(true); } } return(RedirectToAction("List")); } else { return(RedirectToAction("index", "Home")); } }
private void SendEmail(string id) { try { var message = new MimeMessage(); message.From.Add(new MailboxAddress(_notify.FromAddress)); foreach (var addr in _notify.EmailActions[id].Addresses) { message.To.Add(new MailboxAddress(addr)); } message.Subject = _notify.EmailActions[id].Subject; message.Body = new TextPart("plain") { Text = _notify.EmailActions[id].Body }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect(_notify.SmtpServer, _notify.SmtpPort, _notify.SmtpIsSSl); if (!string.IsNullOrWhiteSpace(_notify.SmtpLogin)) { client.Authenticate(_notify.SmtpLogin, _notify.SmtpLoginPassword); } client.Send(message); client.Disconnect(true); } _logger.LogInformation($"Sent email action {id}"); lock (EmailEventLock) { _notify.EmailActions.Remove(id); } } catch (Exception err) { if (_notify.EmailActions[id].NextAttempt > _notify.EmailActions[id].SubmittedOn.AddSeconds(_notify.EmailActions[id].PerishSeconds)) { _logger.LogWarning($"Failed (perish) email action {id}, {_notify.EmailActions[id].Body}: {err.Message}"); return; } _logger.LogWarning($"Failed (retry) email action {id}, {_notify.EmailActions[id].Body}: {err.Message}"); lock (EmailEventLock) { _notify.EmailActions[id].IsSending = false; } } }
static void Main(string[] args) { var host = "smtp.gmail.com"; var port = 465; var fromAdd = "*****@*****.**"; //送信元アドレス var fromAddPass = "******"; //送信元アドレスパスワード var toAdd = "*****@*****.**"; //送信先アドレス var mailSubject = "エラー通知テスト"; //メールタイトル var mailText = "お疲れ様です。\r\nエラー通知のテストメールを送信いたしまします。"; //メール本文 using (var smtp = new MailKit.Net.Smtp.SmtpClient()) { try { //開発用のSMTPサーバが暗号化に対応していないときは、次の行をコメントアウト //smtp.ServerCertificateValidationCallback = (s, c, h, e) => true; smtp.Connect(host, port, MailKit.Security.SecureSocketOptions.Auto); //認証設定 smtp.Authenticate(fromAdd, fromAddPass); //送信するメールを作成する var mail = new MimeKit.MimeMessage(); var builder = new MimeKit.BodyBuilder(); mail.From.Add(new MimeKit.MailboxAddress("", fromAdd)); mail.To.Add(new MimeKit.MailboxAddress("", toAdd)); //メールタイトル mail.Subject = mailSubject; //メール本文 MimeKit.TextPart textPart = new MimeKit.TextPart("Plain"); textPart.Text = mailText; var multipart = new MimeKit.Multipart("mixed"); multipart.Add(textPart); mail.Body = multipart; //メールを送信する smtp.Send(mail); } catch (Exception exception) { Console.WriteLine(exception.Message); } finally { //SMTPサーバから切断する smtp.Disconnect(true); } } }
public IActionResult Rezervacija(int id) { MyContext db = new MyContext(); KorisnickiNalog korisnik = HttpContext.GetLogiraniKorisnik(); //int klijentid = korisnik.KorisnickiNalogID; Kupac k = db.Kupac.Where(x => x.KorisnickiNalog.KorisnickoIme == korisnik.KorisnickoIme).FirstOrDefault(); Rezervacija r = new Rezervacija() { DatumRezervacije = DateTime.Now, DatumIsteka = db.Let.Where(x => x.LetID == id).FirstOrDefault().VrijemePolaska, Odobrena = false, KupacID = korisnik.KorisnickiNalogID, Kupac = db.Kupac.Where(x => x.KorisnickiNalogID == korisnik.KorisnickiNalogID).FirstOrDefault(), LetID = id, Let = db.Let.Find(id) }; db.Rezervacija.Add(r); string kupac = db.Kupac.Where(x => x.KupacID == r.KupacID).Select(x => x.Ime + " " + x.Prezime).FirstOrDefault(); string let = db.Let.Where(x => x.LetID == r.LetID).Select(x => x.Grad.Naziv + "/" + x.VrijemePolaska).FirstOrDefault(); db.SaveChanges(); { var message = new MimeMessage(); message.To.Add(new MailboxAddress("*****@*****.**")); message.From.Add(new MailboxAddress("*****@*****.**")); message.Subject = "Zahtjev za rezervaciju"; message.Body = new TextPart("plain") { Text = "Dobili ste novi zahtjev za odobrenje rezervacije od kupca: " + kupac + ", za let: " + let }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.outlook.com", 587, false); client.Authenticate("*****@*****.**", "avio_k"); client.Send(message); client.Disconnect(true); } return(RedirectToAction("MojeRezervacije")); } }
public bool SendMail(string strfromAddres, string strtoAddress, string strBody, string strSubject, string strfromPassword, string strhost, int intPort) { try { var message = new MimeMessage(); string[] subsstrnameFrom = strfromAddres.Split('@'); string strnameFrom = ""; if (subsstrnameFrom.Length > 0) { strnameFrom = subsstrnameFrom[0]; } string[] subsstrtoAddress = strtoAddress.Split('@'); string strnamestrtoAddress = ""; if (subsstrtoAddress.Length > 0) { strnamestrtoAddress = subsstrtoAddress[0]; } message.From.Add(new MailboxAddress(strnameFrom, strfromAddres)); message.To.Add(new MailboxAddress(strnamestrtoAddress, strtoAddress)); message.Subject = strSubject; message.Body = new TextPart("html") { Text = strBody }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.CheckCertificateRevocation = false; client.Connect(strhost, intPort, false); client.Authenticate(strfromAddres, strfromPassword); client.Send(message); client.Disconnect(true); } return(true); } catch (Exception) { return(false); } }
public static async void SendEmail(string recipientEmail, string subject, string message) { logger.LogDebug("Send Mail"); try { //From Address string FromAddress = ConfigVars.NewInstance.From; string FromAdressTitle = ConfigVars.NewInstance.DisplayName; //To Address string ToAddress = recipientEmail; string Subject = subject; string BodyContent = message; //Smtp Server string SmtpServer = ConfigVars.NewInstance.Host; //Smtp Port Number int SmtpPortNumber = ConfigVars.NewInstance.Port; var mimeMessage = new MimeMessage(); mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress)); mimeMessage.To.Add(new MailboxAddress("", ToAddress)); mimeMessage.Subject = Subject; mimeMessage.Body = new TextPart("html") { Text = BodyContent }; await Task.Delay(1000); using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect(SmtpServer, SmtpPortNumber, false); // Note: only needed if the SMTP server requires authentication // Error 5.5.1 Authentication client.Authenticate(ConfigVars.NewInstance.From, ConfigVars.NewInstance.Password); client.Send(mimeMessage); client.Disconnect(true); } } catch (Exception ex) { logger.LogDebug("MAIL-ERROR:" + ex.Message, ex); } }
public IActionResult Send(MessageModel email) { if (!ModelState.IsValid) { return(View("Index")); } try { ViewBag.ErrorMessage = null; var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); var adminAdress = Configuration["SMTP:Admin"]; var adress = Configuration["SMTP:Email"]; var host = Configuration["SMTP:Host"]; var port = Convert.ToInt32(Configuration["SMTP:Port"]); var password = Configuration["SMTP:password"]; var message = new MimeMessage(); message.From.Add(new MailboxAddress(email.Address, adress)); message.To.Add(new MailboxAddress(adminAdress)); message.Subject = email.Topic; message.Body = new TextPart("plain") { Text = email.Text }; using (var smtpClient = new SmtpClient()) { smtpClient.Connect(host, port, true); smtpClient.Authenticate(adress, password); smtpClient.Send(message); smtpClient.Disconnect(true); _success = true; } } catch (Exception e) { _success = false; ViewBag.ErrorMessage = e.Message; } ViewBag.Success = _success; return(View("Index")); }
public void SendEmailFromTemplate(CBAUser user, string subject, MimeEntity content) { EmailMessage message = new EmailMessage { Sender = new MailboxAddress("CBA Admin", _emailMetadata.Sender), Reciever = new MailboxAddress($"{user.FirstName} {user.LastName}", user.Email), Subject = subject, Content = content }; var mimeMessage = EmailMessage.CreateEmailMessage(message); SmtpClient smtpClient = new SmtpClient(); smtpClient.Connect(_emailMetadata.SmtpServer, _emailMetadata.Port, true); smtpClient.Authenticate(_emailMetadata.UserName, _emailMetadata.Password); smtpClient.Send(mimeMessage); smtpClient.Disconnect(true); }
private void EnviarMensaje(MimeMessage mensaje) { using (var client = new SmtpClient()) { client.Connect("smtp.sendgrid.net", 25, false); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate( System.Environment.GetEnvironmentVariable("SENDGRID_USER"), System.Environment.GetEnvironmentVariable("SENDGRID_PASS") ); client.Send(mensaje); client.Disconnect(true); } }
public void SendRegisterEmail(string password, string emaill) { // create email message var email = new MimeMessage(); email.Sender = MailboxAddress.Parse("*****@*****.**"); email.To.Add(MailboxAddress.Parse("*****@*****.**")); email.Subject = " ثبت نام در بازارچه اینترنتی صنایع دستی"; var body = "نام کاربری و کلمه عبور شما در بازارچه اینترنتی صنایع دستی به شرح زیر می باشد:"; body += System.Environment.NewLine; body += "نام کاربری: "; body += emaill; body += System.Environment.NewLine; body += "کلمه عبور: "; body += password; body += System.Environment.NewLine; body += "لطفا به منظور ورود به فروشگاه ، به آدرس زیر مراجعه نمایید:"; body += System.Environment.NewLine; body += "tabrizhandicrafts.com"; email.Body = new TextPart(TextFormat.Text) { Text = body }; try { using var smtp = new MailKit.Net.Smtp.SmtpClient(); smtp.Connect("tabrizhandicrafts.com", 587, SecureSocketOptions.Auto); // hotmail //smtp.Connect("smtp.live.com", 587, SecureSocketOptions.StartTls); // office 365 //smtp.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls); smtp.Authenticate("*****@*****.**", "123456qQ"); smtp.Send(email); smtp.Disconnect(true); } catch (Exception ex) { } // send email }
public async Task sentEmailMailKit(string filename, string locationStr, int locationIndex) { List <string> emailList = _context.LocationEmail.Where(x => x.LocationIndex == locationIndex).Select(x => x.Email).ToList(); try { foreach (string emailStr in emailList) { var email = new MimeMessage(); email.From.Add(new MailboxAddress("SkyTech", "*****@gmail.com")); email.To.Add(new MailboxAddress("SecurityStaff", emailStr)); //email.To.Add(MailboxAddress.Parse("*****@*****.**")); email.Subject = "Notification of people without mask"; string bodyText = "Date Time: " + DateTime.Now + " < br /> "; bodyText = bodyText + "Location: " + locationStr + "<br/><br/>"; bodyText = bodyText + "A person not wearing mask is discovered in the premises.<br/> This is a system generated email. Please do not reply."; var builder = new BodyBuilder(); builder.HtmlBody = string.Format(@bodyText); //var image = builder.LinkedResources.Add(@filename); builder.Attachments.Add(@filename); email.Body = builder.ToMessageBody(); // send email using (var smtp = new MailKit.Net.Smtp.SmtpClient()) { smtp.Connect("***.com", 587, SecureSocketOptions.None); smtp.Authenticate("***@***.com", "******"); await smtp.SendAsync(email); smtp.Disconnect(true); } } } catch (Exception ex) { Debug.WriteLine("Sent Email"); Debug.WriteLine(ex.InnerException); } finally { } }
public IActionResult ForgotPassword(RegisterViewModel model) { string tempPassword = ""; string name = ""; string pass = ""; var getPassword = (from psd in context.Customers where psd.email == model.email select psd).ToList(); foreach (var item in getPassword) { tempPassword = item.password; name = item.firstName; pass = item.password; } ViewData["passwordsuccess"] = "Successfully sent, Please check your email inbox!"; var message = new MimeMessage(); message.From.Add(new MailboxAddress("Sifiso Mazibuko", "*****@*****.**")); message.To.Add(new MailboxAddress(model.email)); message.Subject = "Password"; var body = string.Format("Hi " + name + " Your password is: " + pass + " Thank You."); //message.Body = string.Format("Hi " + name + ",<br /><br />Your password is: " + pass + "<br /><br />Thank You. <br /> Regards, <br /> MrDelivery <img src=cid:mrd-food.jpg/>"); message.Body = new TextPart { Text = string.Format("Hi " + name + ", Your password is: " + tempPassword + " Thank You."), }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect("smtp.gmail.com", 587, false); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate("*****@*****.**", "Secretive2017"); client.Send(message); client.Disconnect(true); } model.email = string.Empty; ModelState.Clear(); return(View()); }
public IActionResult Checkout(Order order) { var items = _shoppingCart.GetShoppingCartItems(); _shoppingCart.ShoppingCartItems = items; if (_shoppingCart.ShoppingCartItems.Count == 0) { ModelState.AddModelError("", "Your card is empty, add some games first"); } if (ModelState.IsValid) { _orderRepository.CreateOrder(order); //_shoppingCart.ClearCart(); var message = new MimeMessage(); message.From.Add(new MailboxAddress("Computer Games Webshop", "*****@*****.**")); message.To.Add(new MailboxAddress("Computer Games Webshop", order.Email)); message.Subject = "Order confirmed"; message.Body = new TextPart("plain") { Text = "Thanks for your order!" }; using (var client = new SmtpClient()) { client.Connect("smtp.gmail.com", 587, false); client.Authenticate("*****@*****.**", "mebltest"); client.Send(message); client.Disconnect(true); } return(RedirectToAction("CheckoutComplete")); } return(View(order)); }
private void MailNotify(SweepStakes sweepstakes, Contestant winner) { if (emailflag) { SmtpClient smtpClient = new MailKit.Net.Smtp.SmtpClient(); smtpClient.Connect("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.Auto); smtpClient.Authenticate(company[1], company[2]); foreach (Contestant loser in sweepstakes) { if (loser.email != winner.email) { loser.Notify(company, winner.firstName + " has won " + sweepstakes.name, smtpClient); } } winner.Notify(company, "You have won " + sweepstakes.name + ", Contact us to claim your prize.", smtpClient); smtpClient.Disconnect(true); } }
public void SendMail(User user) { var message = new MimeMessage(); message.From.Add(new MailboxAddress("Test Project", "*****@*****.**")); message.To.Add(new MailboxAddress("Test", user.UserMail)); message.Subject = "Test"; message.Body = new TextPart("plain") { Text = "Hello!" }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.gmail.com", 587, false); client.Authenticate("*****@*****.**", "20398657"); client.Send(message); client.Disconnect(true); } }
//public bool SendMail() //{ // MailAddress from = new MailAddress("*****@*****.**" // , "Location tracking"); // MailAddress to = new MailAddress("*****@*****.**"); // MailMessage message = new MailMessage(from, to); // message.Subject = "Tracking Location " + DateTime.Now.ToString(); // string content = ""; // StreamReader reader = null; // using (reader = new StreamReader(filename)) // //AppDomain.CurrentDomain.BaseDirectory + "\\" + // { // content = reader.ReadToEnd(); // } // message.Body = content; // System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient() // { // Host = "smtp.gmail.com", // Port = 587, // EnableSsl = true, // UseDefaultCredentials = false, // Credentials = new NetworkCredential("*****@*****.**" // , "dongphan987654321") // }; // try // { // client.Send(message); // } // catch (Exception e) // { // Log("Error in sending mail process " + e.Message); // return false; // } // return true; //} public bool SendingMailUsingMailKit() { try { string content = ""; StreamReader reader = null; using (reader = new StreamReader(filename, true)) { content = reader.ReadToEnd(); } if (content.Trim().Equals(String.Empty)) { return(true); } var message = new MimeMessage(); MailboxAddress from = new MailboxAddress("Location tracking" , "*****@*****.**"); MailboxAddress to = new MailboxAddress("*****@*****.**"); message.From.Add(from); message.To.Add(to); message.Subject = "Tracking Location " + DateTime.Now.ToString(); message.Body = new TextPart() { Text = content }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.gmail.com", 587); client.Authenticate("*****@*****.**", "dongphan987654321"); client.Send(message); client.Disconnect(true); File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\" + filename , String.Empty); return(true); } } catch (Exception e) { Log("Error in sending mail process " + e.Message); return(false); } }
public void SendEmail(object state) { using (var scope = _scopeFactory.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>(); var emails = context.Subscribers.Select(s => s.Email).ToList(); using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.gmail.com", 465, true); //SMTP server authentication if needed client.Authenticate("*****@*****.**", "huutai123456"); foreach (var mail in emails) { var message = new MimeMessage(); var post_id = context.Posts.Select(p => p.Id); var list_id = post_id.ToList(); string content = string.Format("Có {0} bài viết mới. <br/> <a href=\"https://*****:*****@gmail.com")); message.To.Add(new MailboxAddress("user", mail)); message.Subject = "Subject"; message.Body = new TextPart("html") { Text = content }; client.Send(message); } client.Disconnect(true); } } }
public void SendEmail(MimeMessage emailMessage) { try { using (var client = new SmtpClient()) { client.LocalDomain = PinoacresConstants.SMTPServerUrl; client.Connect(PinoacresConstants.SMTPServerUrl, 587, false); NetworkCredential networkCredential = new NetworkCredential() { UserName = PinoacresConstants.EmailFromAddress, Password = PinoacresConstants.EmailFromPassword }; client.Authenticate(networkCredential); client.Send(emailMessage); client.Disconnect(true); } } catch (Exception ex) { Console.WriteLine("Exception Message"); Console.WriteLine(ex.Message); throw; } }
public override void Execute() { if (!IsValidEmail(Invoice.Customer.Email)) return; var message = new MimeMessage(); message.From.Add(new MailboxAddress("Anchorage Kid to Kid", "*****@*****.**")); message.To.Add(new MailboxAddress(Invoice.Customer.ToString(), Invoice.Customer.Email)); message.Subject = "Receipt: " + Invoice.Id; var body = new BodyBuilder(); body.HtmlBody = GetHtmlBody(Invoice); body.TextBody = ""; message.Body = body.ToMessageBody(); using (var client = new SmtpClient()) { var userName = SharedDb.PosimDb.GetString("SELECT StringValue FROM DBA.BYR_PREFS where PrefTitle = 'emailUN'"); var pw = SharedDb.PosimDb.GetString("SELECT StringValue FROM DBA.BYR_PREFS where PrefTitle = 'emailPW'"); var credentials = new NetworkCredential(userName, pw); // Note: if the server requires SSL-on-connect, use the "smtps" protocol instead var uri = new Uri("smtp://smtp.gmail.com:587"); using (var cancel = new CancellationTokenSource()) { client.Connect(uri, cancel.Token); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); // Note: only needed if the SMTP server requires authentication client.Authenticate(credentials, cancel.Token); client.Send(message, cancel.Token); client.Disconnect(true, cancel.Token); } } }
public Task SendEmailAsync(string email, string subject, string message) { using (var client = new SmtpClient()) { // client.Connect("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect); // client.Authenticate("username", "password"); var mimeMessage = new MimeMessage(); mimeMessage.From.Add(new MailboxAddress("BodyReport", WebAppConfiguration.SmtpEmail)); mimeMessage.To.Add(new MailboxAddress(email, email)); mimeMessage.Subject = subject; mimeMessage.Body = new TextPart("html") { Text = message }; client.Connect(WebAppConfiguration.SmtpServer, WebAppConfiguration.SmtpPort, SecureSocketOptions.None); client.Authenticate(WebAppConfiguration.SmtpUserName, WebAppConfiguration.SmtpPassword); client.Send(mimeMessage); client.Disconnect(true); } // Plug in your email service here to send an email. return Task.FromResult(0); }
/// <summary> /// Sends an email <paramref name="msg" />. /// </summary> /// <param name="msg">Message to send.</param> public void SendEmail(MimeMessage msg) { if (msg == null) { throw new ArgumentNullException(nameof(msg)); }; using (var client = new SmtpClient()) { if (_options.UseSsl) { client.Connect(_options.Server, _options.Port, SecureSocketOptions.StartTls); } else { client.Connect(_options.Server, _options.Port, false); client.AuthenticationMechanisms.Remove("XOAUTH2"); } client.Authenticate(_options.Username, _options.Password); client.Send(msg); client.Disconnect(true); } }
internal void SendMail(Contact contact) { MimeMessage message = new MimeMessage(); message.Subject = $"Contact depuis le formulaire du site"; message.Body = new TextPart { Text = $"Message envoyé par [{contact.Name}]\r\n mail saisi [{contact.Mail}] \r\n Message : \r\n {contact.Text}" }; message.From.Add(new MailboxAddress("contact", this._smtpFrom)); message.To.Add(new MailboxAddress("contact", this._smtpTo)); using (var client = new SmtpClient()) { client.Timeout = 3000; client.Connect(this._smtpAddress, this._smtpPort, SecureSocketOptions.SslOnConnect); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); // Note: only needed if the SMTP server requires authentication client.Authenticate(this._smtpUser, this._smtpPassword); client.Send(message); client.Disconnect(true); } }
public Task SendEmailAsync(string server, string username, string password, string email, string subject, string message) { var mimeMessage = new MimeMessage(); mimeMessage.From.Add(new MailboxAddress("Orlando Codecamp", username)); mimeMessage.To.Add(new MailboxAddress(email,email)); mimeMessage.Subject = subject; mimeMessage.Body = new TextPart("plain") { Text = message }; using (var client = new SmtpClient()) { client.Connect(server, 587, false); // We don't have an OAuth2 token, so we've disabled it client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(username, password); client.Send(mimeMessage); client.Disconnect(true); } return Task.FromResult(0); }
public void TestBinaryMime () { var message = CreateBinaryMessage (); string bdat; using (var memory = new MemoryStream ()) { var options = FormatOptions.Default.Clone (); long size; options.NewLineFormat = NewLineFormat.Dos; using (var measure = new MeasuringStream ()) { message.WriteTo (options, measure); size = measure.Length; } var bytes = Encoding.ASCII.GetBytes (string.Format ("BDAT {0} LAST\r\n", size)); memory.Write (bytes, 0, bytes.Length); message.WriteTo (options, memory); bytes = memory.GetBuffer (); bdat = Encoding.UTF8.GetString (bytes, 0, (int) memory.Length); } var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo+binarymime.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**> BODY=BINARYMIME\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<*****@*****.**>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand (bdat, "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands), CancellationToken.None); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { var credentials = new NetworkCredential ("username", "password"); client.Authenticate (credentials, CancellationToken.None); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.BinaryMime), "Failed to detect BINARYMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Chunking), "Failed to detect CHUNKING extension"); try { client.Send (message, CancellationToken.None); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { client.Disconnect (true, CancellationToken.None); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } }
/* * sends message */ internal static void SendMessage(Node ip, Node dp, MimeMessage msg) { string host = Expressions.GetExpressionValue<string>(ip.GetValue("host", ""), dp, ip, false); int port = Expressions.GetExpressionValue<int>(ip.GetValue("port", "-1"), dp, ip, false); bool implicitSsl = Expressions.GetExpressionValue<bool>(ip.GetValue("implicit-ssl", "false"), dp, ip, false); string username = Expressions.GetExpressionValue<string>(ip.GetValue("username", ""), dp, ip, false); string password = Expressions.GetExpressionValue<string>(ip.GetValue("password", ""), dp, ip, false); using (SmtpClient client = new SmtpClient()) { client.Connect(host, port, implicitSsl); client.AuthenticationMechanisms.Remove("XOAUTH2"); if (!string.IsNullOrEmpty(username)) client.Authenticate(username, password); client.Send(msg); client.Disconnect(true); } }
public RC sendMessage(string sReceiverAddress, string sMessage, int iSmtpPort=587) { var message = new MimeMessage (); message.From.Add(new MailboxAddress(m_AuthInfo.m_sId, m_AuthInfo.m_sId)); message.To.Add (new MailboxAddress (sReceiverAddress, sReceiverAddress)); message.Subject = ""; string sEncryptedMessage = ""; //TODO: return error if mail cannot be send encrypted try { sEncryptedMessage = m_OpenPgpCrypter.encryptPgpString (sMessage, sReceiverAddress, true, false); } catch(Exception e) { m_Logger.log (ELogLevel.LVL_WARNING, e.Message, m_sModuleName); } message.Body = new TextPart ("plain") { Text = @sEncryptedMessage }; using (var client = new SmtpClient ()) { client.Connect (m_EmailServiceDescription.SmtpUrl, iSmtpPort, true); // disable the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove ("XOAUTH2"); client.Authenticate (m_AuthInfo.m_sId, m_AuthInfo.m_sPassword); client.Send (message); client.Disconnect (true); this.m_ConversationManager.addMessage (m_sProtocol, sMessage, m_AuthInfo.m_sId, sReceiverAddress); } return RC.RC_OK; }
public void Send(MimeMessage message, string user, string pwd, string uri) { using (var client = new SmtpClient()) { var credentials = new NetworkCredential(user, pwd); // Note: if the server requires SSL-on-connect, use the "smtps" protocol instead var uriObj = new Uri(uri); using (var cancel = new CancellationTokenSource()) { client.Connect(uriObj, cancel.Token); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); // Note: only needed if the SMTP server requires authentication client.Authenticate(credentials, cancel.Token); client.Send(message, cancel.Token); client.Disconnect(true, cancel.Token); } } }
public static void SendMessage (MimeMessage message) { using (var client = new SmtpClient ()) { // Note: since GMail requires SSL at connection time, use the "smtps" // protocol instead of "smtp". var uri = new Uri ("smtps://smtp.gmail.com:465"); client.Connect (uri); client.Authenticate ("username", "password"); client.Send (message); client.Disconnect (true); } }
public async Task SendEmailAsync( SmtpOptions smtpOptions, string to, string from, string subject, string plainTextMessage, string htmlMessage) { if(string.IsNullOrEmpty(plainTextMessage) && string.IsNullOrEmpty(htmlMessage)) { throw new ArgumentException("no message provided"); } var m = new MimeMessage(); m.From.Add(new MailboxAddress("", from)); m.To.Add(new MailboxAddress("", to)); m.Subject = subject; //m.Importance = MessageImportance.Normal; //Header h = new Header(HeaderId.Precedence, "Bulk"); //m.Headers.Add() BodyBuilder bodyBuilder = new BodyBuilder(); if(plainTextMessage.Length > 0) { bodyBuilder.TextBody = plainTextMessage; } if (htmlMessage.Length > 0) { bodyBuilder.HtmlBody = htmlMessage; } m.Body = bodyBuilder.ToMessageBody(); using (var client = new SmtpClient()) { //client.ServerCertificateValidationCallback = delegate ( // Object obj, X509Certificate certificate, X509Chain chain, // SslPolicyErrors errors) //{ // return (true); //}; await client.ConnectAsync(smtpOptions.Server, smtpOptions.Port, smtpOptions.UseSsl); //await client.ConnectAsync(smtpOptions.Server, smtpOptions.Port, SecureSocketOptions.StartTls); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); // Note: only needed if the SMTP server requires authentication if(smtpOptions.RequiresAuthentication) { await client.AuthenticateAsync(smtpOptions.User, smtpOptions.Password); } client.Send(m); client.Disconnect(true); } }
public static void SendMessageWithOptions (MimeMessage message) { using (var client = new SmtpClient ()) { client.Connect ("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect); client.Authenticate ("username", "password"); var options = FormatOptions.Default.Clone (); if (client.Capabilities.HasFlag (SmtpCapabilities.UTF8)) options.International = true; client.Send (options, message); client.Disconnect (true); } }
public JsonResult Compose(Email email) { JsonResult jsonResult = new JsonResult(); string outputMessage = ""; try { userGmailConfig = FetchUserGmailProfile(); var message = new MimeMessage(); message.From.Add(new MailboxAddress(email.FromEmail, email.FromEmail)); if (email.ToAsCsv.Contains(',')) { foreach (var item in email.ToAsCsv.Split(',')) { message.To.Add(new MailboxAddress(item, item)); } } else if (email.ToAsCsv.Contains(';')) { foreach (var item in email.ToAsCsv.Split(';')) { message.To.Add(new MailboxAddress(item, item)); } } else { message.To.Add(new MailboxAddress(email.ToAsCsv, email.ToAsCsv)); } message.Subject = email.Subject; message.Body = new TextPart("plain") { Text = email.Body }; using (var client = new SmtpClient()) { try { client.Connect(userGmailConfig.OutgoingServerAddress, userGmailConfig.OutgoingServerPort); client.Authenticate(new NetworkCredential(userGmailConfig.GmailUsername, userGmailConfig.GmailPassword)); client.Send(message); client.Disconnect(true); outputMessage = "Your message was sent successfully"; } catch (Exception) { outputMessage = "There was an error sending your mail."; } } } catch (Exception ex) { outputMessage = "There was an error in processing your request. Exception: " + ex.Message; } jsonResult.Data = new { message = outputMessage, }; return jsonResult; }
public static void SendMessages (IList<MimeMessage> messages) { using (var client = new SmtpClient ()) { client.Connect ("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect); client.Authenticate ("username", "password"); foreach (var message in messages) { client.Send (message); } client.Disconnect (true); } }
public static void SendMessage (MimeMessage message) { using (var client = new SmtpClient ()) { try { client.Connect ("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect); } catch (SmtpCommandException ex) { Console.WriteLine ("Error trying to connect: {0}", ex.Message); Console.WriteLine ("\tStatusCode: {0}", ex.StatusCode); return; } catch (SmtpProtocolException ex) { Console.WriteLine ("Protocol error while trying to connect: {0}", ex.Message); return; } // Note: Not all SMTP servers support authentication, but GMail does. if (client.Capabilities.HasFlag (SmtpCapabilities.Authentication)) { try { client.Authenticate ("username", "password"); } catch (AuthenticationException ex) { Console.WriteLine ("Invalid user name or password."); return; } catch (SmtpCommandException ex) { Console.WriteLine ("Error trying to authenticate: {0}", ex.Message); Console.WriteLine ("\tStatusCode: {0}", ex.StatusCode); return; } catch (SmtpProtocolException ex) { Console.WriteLine ("Protocol error while trying to authenticate: {0}", ex.Message); return; } } try { client.Send (message); } catch (SmtpCommandException ex) { Console.WriteLine ("Error sending message: {0}", ex.Message); Console.WriteLine ("\tStatusCode: {0}", ex.StatusCode); switch (ex.ErrorCode) { case SmtpErrorCode.RecipientNotAccepted: Console.WriteLine ("\tRecipient not accepted: {0}", ex.Mailbox); break; case SmtpErrorCode.SenderNotAccepted: Console.WriteLine ("\tSender not accepted: {0}", ex.Mailbox); break; case SmtpErrorCode.MessageNotAccepted: Console.WriteLine ("\tMessage not accepted."); break; } } catch (SmtpProtocolException ex) { Console.WriteLine ("Protocol error while sending message: {0}", ex.Message); } client.Disconnect (true); } }
public async Task SendAsync(string from,string from_name, string to,string cc, string subject, string messageBody, string host) { System.Text.Encoding utf_8 = System.Text.Encoding.UTF8; var message = new MimeMessage(); var e_from = new MailboxAddress(from, from_name); e_from.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1"); message.From.Add(e_from); var e_to = new MailboxAddress("", to); e_to.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1"); message.To.Add(e_to); if (cc != null && cc != "" ) { message.Cc.Add(new MailboxAddress("", cc)); } message.Subject = subject; var builder = new BodyBuilder(); //Microsoft.Extensions.PlatformAbstractions.IApplicationEnvironment //var app_environment = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Runtime.RuntimePath;// var app_environment = host; var filename = "http://"+ app_environment + "/templates/Mail/Signature.html"; WebClient clients = new WebClient(); string mailboy = clients.DownloadString(new Uri(filename)); //var mailboy = System.IO.File.ReadAllText(filename); var image_source = new Uri("http://" + app_environment + "/images/M32G2.png"); var image = builder.LinkedResources.Add("M32G2.png", clients.DownloadData(image_source)) ; image.ContentId = Path.GetFileName("M32G2.png"); //imagepath= app_environment.ApplicationBasePath + mailboy = mailboy.Replace("#imageLogo#", image.ContentId); mailboy = mailboy.Replace("#body#", messageBody); builder.HtmlBody = mailboy; //message.Body.ContentLocation = "pt-PT"; //builder.HtmlBody = messageBody; //builder.HtmlBody = string.Format(@"<p>Hey!</p><img src=""cid:{0}"">", image.ContentId); message.Body = builder.ToMessageBody(); using (var client = new SmtpClient()) { client.Connect("smtp.gmail.com", 587, false); // Note: only needed if the SMTP server requires authentication client.Authenticate("*****@*****.**", "Meridian321"); client.Send(message); client.Disconnect(true); } }
public void TestBasicFunctionality () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**>\r\n", "comcast-mail-from.txt")); commands.Add (new SmtpReplayCommand ("RCPT TO:<*****@*****.**>\r\n", "comcast-rcpt-to.txt")); commands.Add (new SmtpReplayCommand ("DATA\r\n", "comcast-data.txt")); commands.Add (new SmtpReplayCommand (".\r\n", "comcast-data-done.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands), CancellationToken.None); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { var credentials = new NetworkCredential ("username", "password"); client.Authenticate (credentials, CancellationToken.None); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex); } try { client.Send (CreateSimpleMessage (), CancellationToken.None); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Send: {0}", ex); } try { client.Disconnect (true, CancellationToken.None); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } }
public void TestUnauthorizedAccessException () { var commands = new List<SmtpReplayCommand> (); commands.Add (new SmtpReplayCommand ("", "comcast-greeting.txt")); commands.Add (new SmtpReplayCommand ("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add (new SmtpReplayCommand ("MAIL FROM:<*****@*****.**>\r\n", "auth-required.txt")); commands.Add (new SmtpReplayCommand ("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient ()) { try { client.ReplayConnect ("localhost", new SmtpReplayStream (commands), CancellationToken.None); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue (client.IsConnected, "Client failed to connect."); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue (client.AuthenticationMechanisms.Contains ("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual (36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue (client.Capabilities.HasFlag (SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { client.Send (CreateSimpleMessage (), CancellationToken.None); Assert.Fail ("Expected an ServiceNotAuthenticatedException"); } catch (ServiceNotAuthenticatedException) { // this is the expected exception } catch (Exception ex) { Assert.Fail ("Did not expect this exception in Send: {0}", ex); } Assert.IsTrue (client.IsConnected, "Expected the client to still be connected"); try { client.Disconnect (true, CancellationToken.None); } catch (Exception ex) { Assert.Fail ("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse (client.IsConnected, "Failed to disconnect"); } }
public IActionResult Submit(ContactForm form) { if (!ModelState.IsValid) return View("Index", form); var emailMessage = new MimeMessage(); var address = new MailboxAddress(Settings.Title, Settings.EmailFromAndTo); emailMessage.From.Add(address); emailMessage.To.Add(address); emailMessage.Subject = Settings.EmailSubject; var message = "Name: " + form.Name + Environment.NewLine + "Company: " + form.Company + Environment.NewLine + form.PreferredMethod + ": " + form.Email + form.Phone + Environment.NewLine + "Message:" + Environment.NewLine + form.Message; emailMessage.Body = new TextPart("plain") { Text = message }; using (var client = new SmtpClient()) { client.Connect(Settings.EmailServer, 465); client.Authenticate(Settings.EmailUser, Cache.Config["EmailPassword"]); client.Send(emailMessage); client.Disconnect(true); } return View("Thanks"); }