public Authenticate ( Portable.Text.Encoding encoding, ICredentials credentials, |
||
encoding | Portable.Text.Encoding | The text encoding to use for the user's credentials. |
credentials | ICredentials | The user's credentials. |
cancellationToken | The cancellation token. | |
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); } }
public static bool SendMail(string mailTo, string mailTitle, string mailContent) { 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; // 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("*****@*****.**", "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) { throw e; // Console.WriteLine(e.Message); // return false; } }
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 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 Mail() { var message = new MimeMessage(); message.From.Add(new MailboxAddress("bellroy", "*****@*****.**")); message.To.Add(new MailboxAddress("igna", "*****@*****.**")); message.Subject = "Invoice From Bellroy"; var get = from i in _AppDbContext.purchases.OrderBy(i => i.id) select i; var last = get.LastOrDefault(); message.Body = new TextPart("plain") { Text = @"Hello " + last.nama + "\nThanks for purchasing our best collection \n" + "Here is your purchase details :\n" + "Amount : Rp. " + last.totalPurchase }; using (var emailClient = new MailKit.Net.Smtp.SmtpClient()) { emailClient.ServerCertificateValidationCallback = (s, c, h, e) => true; emailClient.Connect("smtp.mailtrap.io", 587, false); emailClient.Authenticate("31e443602f2a8a", "187ef92862e63c"); emailClient.Send(message); } return(View("Success")); }
// 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 SendEmail() { try { var message = new MimeMessage(); message.From.Add(new MailboxAddress("TheCodeBuzz", "*****@*****.**")); message.To.Add(new MailboxAddress("TheCodeBuzz", "*****@*****.**")); message.Subject = "My First Email"; message.Body = new TextPart("plain") { Text = "Email is Working Fine" }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.gmail.com", 587, false); client.Authenticate("*****@*****.**", "password"); //SMTP server authentication if needed // client.Authenticate("*****@*****.**", "xxxxx"); client.Send(message); client.Disconnect(true); } } catch (Exception ex) { Console.WriteLine(ex.Message); return(StatusCode(500, "Error occured")); } return(Ok(true)); }
public IActionResult SendMail(string email, string messagecontent, string subject, string name) { if (email == null || messagecontent == null || subject == null || name == null) { ModelState.AddModelError("Hata", "Eksik Bilgi"); return(View("ErrorPage")); } else { var message = new MimeMessage(); message.From.Add(new MailboxAddress("*****@*****.**")); message.To.Add(new MailboxAddress("*****@*****.**")); message.Subject = subject; message.Body = new TextPart("html") { Text = "BAŞLIK:" + subject + "<br>" + name + " 'dan <br> " + email + " 'dan <br> " + " Mesaj : " + messagecontent }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { //587 client.Connect("srvm04.turhost.com", 587, false); client.Authenticate("*****@*****.**", "Qwerty123"); client.Send(message); client.Disconnect(true); }; return(RedirectToAction("Index", "Home")); } }
private void EMSend_Click(object sender, RoutedEventArgs e) { try { buildTolist(); if (sendTo.Length == 0 || EMservice.Text.Equals("Select One")) { Console.WriteLine(sendTo + EMservice.Text); MessageBox.Show("Check your entries"); return; } Console.WriteLine("to be sent to:" + sendTo.TrimEnd(',')); var mailMessage = new MailMessage { From = new MailAddress(EMuser.Text), Subject = EMHead.Text, Body = EMmessage.Text }; mailMessage.To.Add(sendTo.TrimEnd(',')); if (!EMattatchment.Text.Contains("Want to attatch")) { Console.WriteLine("Attempting attachment"); var attachment = new Attachment(EMattatchment.Text); mailMessage.Attachments.Add(attachment); Console.WriteLine("attachment Complete"); } Console.WriteLine("Attempting to send"); using (var smtpClient = new SmtpClient()) { switch (EMservice.Text) { case "Gmail": smtpClient.Connect("smtp.gmail.com", 465, true); break; case "ICloud": smtpClient.Connect("smtp.mail.me.com", 587, MailKit.Security.SecureSocketOptions.StartTlsWhenAvailable); break; case "Office365": smtpClient.Connect("smtp.office365.com", 587, MailKit.Security.SecureSocketOptions.StartTlsWhenAvailable); break; case "Outlook": smtpClient.Connect("smtp.outlook.com", 587, MailKit.Security.SecureSocketOptions.StartTlsWhenAvailable); break; } smtpClient.Authenticate(EMuser.Text, EMpass.Text); smtpClient.Send((MimeKit.MimeMessage)mailMessage); smtpClient.Disconnect(true); } MessageBox.Show("Emails sent!"); } catch (Exception x) { MessageBox.Show($"Uh oh something went wrong\n {x.ToString()}", "UGH"); } }
public static void TestSendMailDemo() { var message = new MimeKit.MimeMessage(); message.From.Add(new MailboxAddress("Joey Tribbiani", "*****@*****.**")); message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "*****@*****.**")); message.Subject = "This is a Test Mail"; var plain = new MimeKit.TextPart("plain") { Text = @"不好意思,我在测试程序,Sorry!" }; // now create the multipart/mixed container to hold the message text and the // image attachment using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.live.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 var mailFromAccount = "*****@*****.**"; var mailPassword = "******"; client.Authenticate(mailFromAccount, mailPassword); client.Send(message); client.Disconnect(true); } }
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.SslOnConnect); smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password); await smtp.SendAsync(email); smtp.Disconnect(true); }
public ActionResult <IEnumerable <bool> > SendEmail([FromBody] string confirmationLink) { try { var message = new MimeMessage(); message.From.Add(new MailboxAddress("Alchematic", "*****@*****.**")); message.To.Add(new MailboxAddress("User", "*****@*****.**")); message.Subject = "Confirmation Link"; message.Body = new TextPart("plain") { Text = confirmationLink }; 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); } } catch (Exception ex) { Console.WriteLine(ex.Message); return(StatusCode(500, "Error occured")); } return(Ok(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 HttpStatusCode Connect(ProviderParams providerParams) { _imapClient = new ImapClient(); _smtpClient = new MailKit.Net.Smtp.SmtpClient(); _imapClient.ServerCertificateValidationCallback = (s, c, h, e) => true; try { _imapClient.Connect(providerParams.ImapServerName, providerParams.ImapPortNumber, true); _smtpClient.Connect(providerParams.SmtpServerName, providerParams.SmtpPortNumber, true); _imapClient.AuthenticationMechanisms.Remove("XOAUTH2"); _smtpClient.Authenticate(providerParams.EmailAddress, providerParams.Password); _imapClient.Authenticate(providerParams.EmailAddress, providerParams.Password); } catch (Exception exception) { Console.WriteLine(exception.ToString()); return(HttpStatusCode.ExpectationFailed); } if (_imapClient.IsConnected && _smtpClient.IsConnected) { _currentFolder = ""; return(HttpStatusCode.OK); } else { return(HttpStatusCode.InternalServerError); } }
public static void Send(Order order, bool Add) { var message = new MimeMessage { Sender = new MailboxAddress("Cinema - Pawel Dziwura (Comarch)", "*****@*****.**"), Subject = "Order confirmed" }; if (Add) { message.Body = new TextPart(TextFormat.Plain) { Text = "Hello " + order.OrderUser.Name + " \nYour order (" + order.OrderSeance.StartDate + ") has been confirmed." }; } else { message.Body = new TextPart(TextFormat.Plain) { Text = "Hello " + order.OrderUser.Name + " \nYour order (" + order.OrderSeance.StartDate + ") has been deleted." }; } message.To.Add(new MailboxAddress("Client", "*****@*****.**")); using (var client = new SmtpClient()) { client.SslProtocols = SslProtocols.Tls; client.Connect("smtp.comarch.com", 465); client.Authenticate("*****@*****.**", "type your password"); client.Send(message); } }
public IActionResult Create(UserDetails userDetails) { if (ModelState.IsValid) { var messsage = new MimeMessage(); Random random = new Random(); String number = random.Next(0, 999999).ToString("D6"); messsage.From.Add(new MailboxAddress("Test Address", "*****@*****.**")); messsage.To.Add(new MailboxAddress("Test", "*****@*****.**")); messsage.Subject = "testmail"; messsage.Body = new TextPart("plain") { //"Dear " + signUpModel.Email + ", <br /><br /> '" + number + "' is the password to Register <br /><br /> Thanks & Regards, <br />Rashmi"; Text = "Dear " + userDetails.Name + ", <br /><br /> '" + number + "' is the password to Register <br /><br /> Thanks & Regards, <br />Rashmi" }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.gmail.com", 587, false); client.Authenticate("", ""); client.Send(messsage); client.Disconnect(true); } return(RedirectToAction("about", "home")); } return(View()); }
private void Send(MimeMessage mailMessage) { using (var client = new MailKit.Net.Smtp.SmtpClient()) { try { //client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect(_emailConfig.SmtpServer, _emailConfig.Port, SecureSocketOptions.Auto); client.AuthenticationMechanisms.Remove("XOAUTH2"); // Note: only needed if the SMTP server requires authentication client.Authenticate(_emailConfig.UserName, _emailConfig.Password); client.Send(mailMessage); } catch (Exception ex) { throw; } finally { client.Disconnect(true); client.Dispose(); } } }
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 async void Send(string toAddress, string subject, string body, bool sendAsync = true) { var mimeMessage = new MimeMessage(); // MIME : Multipurpose Internet Mail Extension mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress)); mimeMessage.To.Add(new MailboxAddress(toAddress)); mimeMessage.Subject = subject; var bodyBuilder = new MimeKit.BodyBuilder { HtmlBody = body }; mimeMessage.Body = bodyBuilder.ToMessageBody(); using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect(_smtpServer, _smtpPort, _enableSsl); client.Authenticate(_username, _password); // If using GMail this requires turning on LessSecureApps : https://myaccount.google.com/lesssecureapps if (sendAsync) { await client.SendAsync(mimeMessage); } else { client.Send(mimeMessage); } client.Disconnect(true); } }
private void Send(MimeMessage mailMessage) { using (var client = new MailKit.Net.Smtp.SmtpClient()) { try { client.Connect(_emailConfig.SmtpServer, _emailConfig.Port, SecureSocketOptions.None); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(_emailConfig.UserName, _emailConfig.Password); client.Send(mailMessage); } catch (Exception ex) { ErrMsg = ex.Message; //log an error message or throw an exception or both. //throw; } finally { client.Disconnect(true); client.Dispose(); } } }
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 IActionResult Send(Purchase email) { var message = new MimeMessage(); var user = (from i in _AppDbContext.purchases.OrderBy(x => x.id) select i).LastOrDefault(); var nama = user.firstName + " " + user.lastName; var emailAddress = user.email; var amount = user.totalPrice; message.From.Add(new MailboxAddress("Essence", "*****@*****.**")); message.To.Add(new MailboxAddress(nama, emailAddress)); message.Subject = "Your Purchase"; message.Body = new TextPart("Plain") { Text = @"Dear " + nama + "," + "\nThank You For Your Purchasing. \n" + "Your Total Amount is : Rp. " + amount }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect("smtp.mailtrap.io", 587, false); client.Authenticate("785fd04dea6d9c", "6057ae43ba12a4"); client.Send(message); client.Disconnect(true); } return(RedirectToAction("Checkout", "Home")); }
public bool SendEmail(EmailModel model) { try { var message = new MimeMessage(); message.From.Add(new MailboxAddress(model.Alias, model.FromEmail)); message.To.Add(new MailboxAddress(model.ToName, model.ToEmail)); message.Subject = model.Subject; message.Body = new TextPart() { Text = model.Message }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect("smtp.gmail.com", 587, false); // email //SMTP server authentication if needed client.Authenticate("*****@*****.**", "Harder01!"); client.Send(message); client.Disconnect(true); return(true); } } catch (Exception e) { Console.WriteLine(e); throw; } }
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); } }
public void SendEmailAsync(SendModel sendModel) { var senderEmail = "*****@*****.**"; var senderPassword = "******"; var senderSMTP = "smtp.yandex.ru"; var email = new MimeMessage { Body = new TextPart { Text = sendModel.Body }, Subject = sendModel.Subject, }; email.From.Add(new MailboxAddress(senderEmail)); email.To.Add(new MailboxAddress(sendModel.MailTo)); MailMessage mail = new MailMessage { From = new MailAddress(senderEmail) //адрес отправителя }; //создание экземпляра MailMessage mail.To.Add(new MailAddress(sendModel.MailTo)); //адрес получателя mail.Subject = sendModel.Subject; //заголовок письма mail.Body = sendModel.Body; //сам текст письма using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect(senderSMTP, 465, true); client.Authenticate(senderEmail, senderPassword); client.Send(email); client.Disconnect(true); } }
public IActionResult Mail(string inputName, string inputEmail, string inputMessage) { try { var message = new MimeMessage(); message.From.Add(new MailboxAddress(inputEmail)); message.To.Add(new MailboxAddress("*****@*****.**")); message.Subject = "Message from: " + inputName; message.Body = new TextPart("plain") { Text = inputMessage }; using (var client = new SmtpClient()) { client.Connect("smtp.gmail.com", 587, true); client.Authenticate("*****@*****.**", "Tiger021"); client.Send(message); client.Disconnect(true); }; return(RedirectToAction("Index")); } catch (Exception exp) { ModelState.Clear(); ViewBag.Message = $" We have a problem here {exp.Message}"; return(RedirectToAction("Index")); } }
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 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 }
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 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")); } }
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 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 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 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 static SmtpClient CreateConnectedSmtpClient([NotNull] this ForwardRule forwardRule) { if (forwardRule == null) throw new ArgumentNullException(nameof(forwardRule)); var client = new SmtpClient(); client.Connect(forwardRule.SMTPServer, forwardRule.SMTPPort, forwardRule.SmtpUseSSL); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); if (!string.IsNullOrWhiteSpace(forwardRule.SMTPPassword) && !string.IsNullOrWhiteSpace(forwardRule.SMTPUsername)) { // Note: only needed if the SMTP server requires authentication client.Authenticate(forwardRule.SMTPUsername, forwardRule.SMTPPassword); } return client; }
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 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); } }
/// <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 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); }
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); }
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 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 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 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 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 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 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"); }