public Send ( MimeKit.FormatOptions options, |
||
options | MimeKit.FormatOptions | The formatting options. |
message | The message. | |
cancellationToken | The cancellation token. | |
progress | ITransferProgress | The progress reporting mechanism. |
return | void |
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; } }
/// <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); } }
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> /// 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 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 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 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); } }
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 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); }
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 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)); }
//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 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 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); } } }
/// <summary> /// Occurs when the control is clicked. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void SendMailButton_Click(object sender, EventArgs e) { Int32.TryParse(imapPortTextBox.Text, out int port); MimeMessage message = new MimeMessage(); message.From.Add(new MailboxAddress(smtpUsernameTextBox.Text)); message.To.Add(new MailboxAddress(users.ElementAt(GetIdOfSelectedUserInGrid()).MailAddress.Address)); message.Subject = smtpSubjectTextBox.Text; message.Body = new TextPart("plain") { Text = smtpMessageBodyTextBox.Text }; try { using (MailKitSmtp.SmtpClient client = new MailKitSmtp.SmtpClient()) { client.ServerCertificateValidationCallback = (s, c, h, err) => true; if (smtpSslCheckBox.Enabled) { client.Connect(smtpHostTextBox.Text, port, true); } else if (smtpTlsCheckBox.Enabled) { client.Connect(smtpHostTextBox.Text, port, SecureSocketOptions.StartTlsWhenAvailable); } else { client.Connect(smtpHostTextBox.Text, port, SecureSocketOptions.Auto); } client.Authenticate(smtpUsernameTextBox.Text, smtpPasswordTextBox.Text); client.Send(message); client.Disconnect(true); } } catch (Exception) { MessageBox.Show("Unable to send message, please check the connection.", "Connection error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void Send(string to, string subject, string html, string from = null) { // create message var email = new MimeMessage(); email.From.Add(MailboxAddress.Parse(from ?? _emailConfiguration.EmailFrom)); email.To.Add(MailboxAddress.Parse(to)); email.Subject = subject; email.Body = new TextPart(TextFormat.Html) { Text = html }; // send email using var smtp = new MailKit.Net.Smtp.SmtpClient(); smtp.Connect(_emailConfiguration.SmtpHost, _emailConfiguration.SmtpPort, SecureSocketOptions.StartTls); smtp.Authenticate(_emailConfiguration.SmtpUser, _emailConfiguration.SmtpPass); smtp.Send(email); smtp.Disconnect(true); }
public void SendSuccessOrderPayment(string emaill, string orderNo, long orderId) { // create email message var email = new MimeMessage(); email.Sender = MailboxAddress.Parse(emaill); email.To.Add(MailboxAddress.Parse(emaill)); email.Subject = "ثبت سفارش"; var body = "سفارش شما با شماره "; body += orderNo; body += "در بازارچه اینترنتی صنایع دستی در حال آماده سازی می باشد. "; body += System.Environment.NewLine; body += "tabrizhandicrafts.com/Home/CoustomerOrderTrace/"; body += orderId; body += System.Environment.NewLine; email.Body = new TextPart(TextFormat.Text) { Text = body }; try { using var smtp = new MailKit.Net.Smtp.SmtpClient(); smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls); // hotmail //smtp.Connect("smtp.live.com", 587, SecureSocketOptions.StartTls); // office 365 //smtp.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls); smtp.Authenticate("*****@*****.**", "cama1390"); smtp.Send(email); smtp.Disconnect(true); } catch (Exception ex) { } // send email }
public IActionResult Odobri(int id) { MyContext db = new MyContext(); KorisnickiNalog korisnik = HttpContext.GetLogiraniKorisnik(); Rezervacija r = db.Rezervacija.Find(id); if (r.Odobrena == false) { r.Odobrena = true; } string mailKupca = db.Rezervacija.Where(x => x.KupacID == r.KupacID).Select(x => x.Kupac.Email).FirstOrDefault(); db.SaveChanges(); { var message = new MimeMessage(); message.To.Add(new MailboxAddress(mailKupca)); message.From.Add(new MailboxAddress("*****@*****.**")); message.Subject = "Zahtjev za rezervaciju"; message.Body = new TextPart("plain") { Text = "Vaša rezervacija je odobrena!" }; using (var client = new SmtpClient()) { client.Connect("smtp.outlook.com", 587, false); client.Authenticate("*****@*****.**", "pozoriste123"); client.Send(message); client.Disconnect(true); } return(RedirectToAction("Prikazi")); } }
public void SendEmail2(string userEmail, string url) { var mailMessage = new MimeMessage(); mailMessage.From.Add(MailboxAddress.Parse("*****@*****.**")); mailMessage.To.Add(MailboxAddress.Parse(userEmail)); mailMessage.Subject = "Confirm your email account"; // mailMessage.IsBodyHtml = true; mailMessage.Body = new TextPart(TextFormat.Html) { Text = url }; using var smtp = new MailKit.Net.Smtp.SmtpClient(); smtp.Connect(_emailConfiguration.SmtpHost, _emailConfiguration.SmtpPort, SecureSocketOptions.StartTls); smtp.Authenticate(_emailConfiguration.SmtpUser, _emailConfiguration.SmtpPass); smtp.Send(mailMessage); smtp.Disconnect(true); //var mailMessage = new MimeMessage(); //mailMessage.From.Add(MailboxAddress.Parse("*****@*****.**")); //mailMessage.To.Add(MailboxAddress.Parse(userEmail)); //mailMessage.Subject = "Confirm your email account"; //// mailMessage.IsBodyHtml = true; //mailMessage.Body = new TextPart(TextFormat.Html) { Text = url }; //using var smtp = new MailKit.Net.Smtp.SmtpClient(); //smtp.Connect(_emailConfiguration.SmtpHost, _emailConfiguration.SmtpPort, SecureSocketOptions.StartTls); //smtp.Authenticate(_emailConfiguration.SmtpUser, _emailConfiguration.SmtpPass); //smtp.Send(mailMessage); //smtp.Disconnect(true); //SmtpClient client = new SmtpClient(); ////client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "2AaG8bbGjHzfKjvB7r"); //client //client.Host = "smtp.ethereal.email"; //client.Port = 587; }
// 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>")); } }
private void SendEmailMessage(MimeMessage message) { //((TextPart)(message.Body)).Text //Be careful that the SmtpClient class is the one from Mailkit not the framework! using (var emailClient = new MailKit.Net.Smtp.SmtpClient()) { emailClient.ServerCertificateValidationCallback = (s, c, h, e) => true; //The last parameter here is to use SSL (Which you should!) emailClient.Connect(this.emailConfig.smtpServer, this.emailConfig.port, MailKit.Security.SecureSocketOptions.Auto); //Remove any OAuth functionality as we won't be using it. emailClient.AuthenticationMechanisms.Remove("XOAUTH2"); emailClient.Authenticate(this.emailConfig.userName, this.emailConfig.Password); emailClient.Send(message); emailClient.Disconnect(true); } }
public void sendmail(string msg) { var message = new MimeMessage(); message.From.Add(new MailboxAddress("*****@*****.**", "*****@*****.**")); message.To.Add(new MailboxAddress("*****@*****.**", "*****@*****.**")); message.Subject = msg; message.Body = new TextPart("plain") { Text = msg }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.gmail.com", 587, false); client.Authenticate("USERNAME", "PASSWORD"); 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; } }
/// <summary> /// 简单邮件的发送 /// </summary> /// <param name="mailto">发送人的地址</param> /// <param name="message"></param> /// <param name="subject"></param> public void SendEmail(string mailto, string message, string subject) { var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress(FromAccount, FROM)); emailMessage.To.Add(new MailboxAddress("mail", mailto)); emailMessage.Subject = string.Format(subject); emailMessage.Body = new TextPart("plain") { Text = message }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect(HOST, PORT, false); client.AuthenticationMechanisms.Remove("XALIOAUTH");//取消验证 client.Authenticate(FROM, PASSWORD); client.Send(emailMessage); client.Disconnect(true); } }
private void sendUpdatedRequestEmail(User user) { var message = new MimeMessage(); message.From.Add(new MailboxAddress("PTO System", "*****@*****.**")); message.To.Add(new MailboxAddress($"{user.firstName} {user.lastName}", user.email)); message.Subject = "PTO Request Update"; message.Body = new TextPart("plain") { Text = "The status on one of your PTO requests has been updated" }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.gmail.com", 587, false); //SMTP server authentication if needed client.Authenticate("*****@*****.**", "xxxxx"); client.Send(message); client.Disconnect(true); } }
private void sendNewRequestEmail(User user) { var message = new MimeMessage(); message.From.Add(new MailboxAddress("PTO System", "*****@*****.**")); message.To.Add(new MailboxAddress($"{user.firstName} {user.lastName}", user.email)); message.Subject = "A PTO Request Needs Your Attention"; message.Body = new TextPart("plain") { Text = "A new PTO request has been created by someone you manage" }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.gmail.com", 587, false); //SMTP server authentication if needed client.Authenticate("*****@*****.**", "xxxxx"); client.Send(message); client.Disconnect(true); } }
public void SendResetPassEmail(string emaill, long code) { // create email message var email = new MimeMessage(); email.Sender = MailboxAddress.Parse(emaill); email.To.Add(MailboxAddress.Parse(emaill)); email.Subject = "بازیابی رمز عبور"; var body = " کد تایید شما برای بازیابی رمز عبور در "; body += "tabrizhandicrafts.com"; body += System.Environment.NewLine; body += ""; body += code.ToString(); body += " می باشد."; email.Body = new TextPart(TextFormat.Text) { Text = body }; try { using var smtp = new MailKit.Net.Smtp.SmtpClient(); smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls); // hotmail //smtp.Connect("smtp.live.com", 587, SecureSocketOptions.StartTls); // office 365 //smtp.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls); smtp.Authenticate("*****@*****.**", "sa19881213"); smtp.Send(email); smtp.Disconnect(true); } catch (Exception ex) { } // send email }
public static bool SendMailWithAttach(string mailTo, string mailTitle, string mailContent, IFormFile file) { try { var message = new MimeMessage(); message.To.Add(new MailboxAddress(mailTo)); message.From.Add(new MailboxAddress("AbleMusicStudio", "*****@*****.**")); message.Subject = mailTitle; var builder = new BodyBuilder(); builder.HtmlBody = mailContent; using (var ms = new MemoryStream()) { file.CopyTo(ms); var fileBytes = ms.ToArray(); Attachment att = new Attachment(new MemoryStream(fileBytes), file.FileName); builder.Attachments.Add("Invoice.pdf", fileBytes); } // builder.Attachments.Add(attachment); message.Body = builder.ToMessageBody(); using (var emailClient = new MailKit.Net.Smtp.SmtpClient()) { emailClient.Connect("smtp.gmail.com", 587, false); // emailClient.Authenticate("*****@*****.**", "ablemusic1234"); emailClient.Authenticate("*****@*****.**", "er345ssDl5Ddxss"); emailClient.Send(message); emailClient.Disconnect(true); } Console.WriteLine("Email has been sent\nMail To: " + mailTo + "\n MailTitle: " + mailTitle + "\nMail Content: " + mailContent + "\n"); return(true); } catch (Exception e) { Console.WriteLine(e.Message); return(false); } }
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(); } }
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 static bool SendEmail(string email, string subject, string body) { var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress("Spoken Past Auto Sender", "*****@*****.**")); emailMessage.To.Add(new MailboxAddress("", email)); emailMessage.Subject = subject; emailMessage.Body = new TextPart("plain") { Text = body }; using (var client = new SmtpClient()) { //begin using client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTlsWhenAvailable); client.AuthenticationMechanisms.Remove("XOAUTH2"); // Must be removed for Gmail SMTP client.Authenticate("*****@*****.**", "password"); client.Send(emailMessage); client.Disconnect(true); }//end using return(true); }
public async Task SendEmailAsync(string toEmail, string subject, string content) { MimeMessage message = new MimeMessage(); MailboxAddress from = new MailboxAddress("Admin", "*****@*****.**"); message.From.Add(from); MailboxAddress to = new MailboxAddress("User", toEmail); message.To.Add(to); message.Subject = "Please conform your email"; BodyBuilder bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = content; message.Body = bodyBuilder.ToMessageBody(); using (var smtpClient = new SmtpClient()) { smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => true; smtpClient.Connect("smtp.gmail.com", 587); smtpClient.Authenticate("*****@*****.**", "Jamgod1234554321!!!!!"); smtpClient.Send(message); smtpClient.Disconnect(true); } //var apiKey = _configaration["SendGripkey"]; //var client = new SendGridClient(apiKey); //var from = new EmailAddress("*****@*****.**", "Test Mail"); //var to = new EmailAddress("*****@*****.**", "Example User"); //var msg = MailHelper.CreateSingleEmail(from, to, subject, content, content); //var response = await client.SendEmailAsync(msg); }
public void Envoyer() { try { using (var client = new MailKit.Net.Smtp.SmtpClient()){ try { client.Connect("smtp.gmail.com", 587, false); client.ConnectAsync("smtp.gmail.com", 587, false); client.Authenticate("*****@*****.**", "DICJ2020+"); client.Send(message); client.Disconnect(true); } catch (Exception) { } } } catch (Exception) { } }
/// <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); } }
public IActionResult SendLink(SingleVehicleViewModel model) { var message = new MimeMessage(); message.From.Add(new MailboxAddress("*****@*****.**")); message.To.Add(new MailboxAddress(model.SendMail)); message.Subject = "Här kommer din drömbil från BolindersBil"; message.Body = new TextPart("html") { Text = "<h2><strong>Klicka på länken för att se fordonet</strong></h2>" + "<br>" + $"<a href='{model.Url}' target='_blank'>{model.Url}</a>" }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect(_appSettings.FormSmtpServer, _appSettings.FormPort); client.Authenticate(_appSettings.FormUserName, _appSettings.FormPassWord); client.Send(message); client.Disconnect(true); } ModelState.Clear(); return(Redirect(model.Url)); }
public void SendMail(string mailbody, ContactFormModel model) { // using mimekit var message = new MimeMessage(); message.From.Add(new MailboxAddress($"{model.Name}", "*****@*****.**")); message.To.Add(new MailboxAddress("oliver fu", "*****@*****.**")); message.Subject = $"New message from {model.Name}, coming from Select Rents solution project"; message.Body = new TextPart("plain") { Text = $"Hello JT! {model.Message}. Sincerely, {model.Name}{model.LastName}" }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.mail.yahoo.com", 465, true); client.Authenticate("*****@*****.**", "Star213@!."); client.Send(message); Console.WriteLine(model.Name.ToString() + " sent at " + DateTime.Now.ToString()); client.Disconnect(true); } // display success page }
private void Send(MimeMessage mailMessage) { using (var client = new MailKit.Net.Smtp.SmtpClient()) { try { client.Connect(_emailConfig.SmtpServer, _emailConfig.Port, true); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(_emailConfig.UserName, _emailConfig.Password); client.Send(mailMessage); } catch { //log an error message or throw an exception or both. throw; } finally { client.Disconnect(true); client.Dispose(); } } }
public void SendMail(string from, List <string> toWho, MimeEntity _message, string _subject = "Enmon Enerji Takibi") { var message = new MimeMessage(); try { foreach (string mailAddress in toWho) { message.To.Add(new MailboxAddress(mailAddress, mailAddress)); } message.From.Add(new MailboxAddress(from, from)); message.Subject = _subject; message.Body = _message; client.Send(message); client.Disconnect(true); } catch (Exception ex) { Log.Instance.Error("{0}: {1} başlıklı e-postayı gönderirken hata => {1}", this.GetType().Name, _subject, ex.Message); throw; } }
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); }
public void SendNotification(IData data) { using (var client = new SmtpClient()) { var smtpConfig = _config.Notification.Sender; client.Connect(smtpConfig.Server, smtpConfig.Port); client.Authenticate(smtpConfig.Username, smtpConfig.Password); var message = new MimeMessage(); var mailboxAddresses = new List<MailboxAddress>(); mailboxAddresses.Add(new MailboxAddress(data.Recipient, data.Recipient)); message.From.Add(new MailboxAddress(smtpConfig.Username, smtpConfig.Username)); message.To.AddRange(mailboxAddresses); message.Subject = data.Subject; message.Body = new TextPart("html") {Text = data.Body}; client.Send(message); } }
public bool sendMailMailMessage(MailBodyDTO message) { EmailMessage _message = new EmailMessage() { Content = message.messageBody, Reciever = new MailboxAddress(message.to[1]), Subject = message.subject, Sender = new MailboxAddress(message.from) }; var mimeMessage = CreateMimeMessageFromEmailMessage(_message); using (MailKit.Net.Smtp.SmtpClient smtpClient = new MailKit.Net.Smtp.SmtpClient()) { smtpClient.Connect(_emailConfig.SmtpServer, _emailConfig.Port, true); smtpClient.Authenticate(_emailConfig.Username, _emailConfig.Password); smtpClient.Send(mimeMessage); smtpClient.Disconnect(true); } return(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); }
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); } }
private void SendEmail(MimeMessage message) { using (var client = new SmtpClient()) { var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); client.Connect(_config.Host, _config.Port, true, cts.Token); client.Authenticate(_config.Username, _config.Password, cts.Token); client.Send(message, cts.Token); } }
/* * 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 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 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 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 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 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 ()) { 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 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 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"); } }
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 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 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 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"); }