/// <summary> /// Carga la informacion de la base de datos y crea un objeto SMTP /// </summary> /// <returns></returns> public static SMTP GetSMTPSettings() { SMTP SMTP = new SMTP(); SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ConnectionString); SqlCommand comm = new SqlCommand("GetSettings", conn); comm.CommandType = CommandType.StoredProcedure; try { conn.Open(); SqlDataReader sqlDataReader = comm.ExecuteReader(); if (sqlDataReader.HasRows) { while (sqlDataReader.Read()) { SMTP.SMTPServer = HttpContext.Current.Server.HtmlDecode(sqlDataReader["smtpserver"].ToString()); SMTP.SMTPSSL = Convert.ToBoolean(HttpContext.Current.Server.HtmlDecode(sqlDataReader["SMTPSSL"].ToString())); SMTP.SMTPPort = Convert.ToInt32(HttpContext.Current.Server.HtmlDecode(sqlDataReader["SMTPPort"].ToString())); SMTP.DisplayName = HttpContext.Current.Server.HtmlDecode(sqlDataReader["companyname"].ToString()); SMTP.Email = HttpContext.Current.Server.HtmlDecode(sqlDataReader["SMTPEmail"].ToString()); SMTP.Password = HttpContext.Current.Server.HtmlDecode(sqlDataReader["EmailPassword"].ToString()); } } sqlDataReader.Close(); } catch (Exception ex) { PEDSS.Errorlog.Register(ex.Message, "Local", "GetSMTPSettings", ex.StackTrace, HttpContext.Current.Request.UserHostAddress, HttpContext.Current.Request.UserAgent); } finally { conn.Close(); } return(SMTP); }
public Task ValidateAsync(SMTP smtp) { if (smtp == null) { throw new ArgumentNullException(nameof(smtp)); } if (string.IsNullOrWhiteSpace(smtp.Server)) { throw new ArgumentNullException(nameof(smtp.Server)); } if (smtp.Port < AppConsts.SMTP_PORT_MIN) { throw new ArgumentOutOfRangeException(nameof(smtp.Port), $"Minimum value is {AppConsts.SMTP_PORT_MIN}"); } if (smtp.Port > AppConsts.SMTP_PORT_MAX) { throw new ArgumentOutOfRangeException(nameof(smtp.Port), $"Maximum value is {AppConsts.SMTP_PORT_MAX}"); } if (smtp.Timeout < AppConsts.SMTP_TIMEOUT_MIN) { throw new ArgumentOutOfRangeException(nameof(smtp.Timeout), $"Minimum value is {AppConsts.SMTP_TIMEOUT_MIN}"); } if (smtp.Timeout > AppConsts.SMTP_TIMEOUT_MAX) { throw new ArgumentOutOfRangeException(nameof(smtp.Timeout), $"Maximum value is {AppConsts.SMTP_TIMEOUT_MAX}"); } return(Task.CompletedTask); }
public void TestConstructor() { //Test on defaults of port 25 and var mock = new Mock <SMTP.ISmtpClient>(); mock.SetupProperty(foo => foo.EnableSsl); var client = mock.Object; var credentials = new NetworkCredential("username", "password"); var test = SMTP.GetInstance(client, credentials); mock.Verify(foo => foo.EnableSsl, Times.Never()); mock = new Mock <SMTP.ISmtpClient>(); mock.SetupProperty(foo => foo.EnableSsl); client = mock.Object; credentials = new NetworkCredential("username", "password"); test = SMTP.GetInstance(client, credentials, port: SMTP.SslPort); mock.VerifySet(foo => foo.EnableSsl = true); mock = new Mock <SMTP.ISmtpClient>(); mock.SetupProperty(foo => foo.EnableSsl); client = mock.Object; credentials = new NetworkCredential("username", "password"); try { test = SMTP.GetInstance(client, credentials, port: SMTP.TlsPort); Assert.Fail("should have thrown an unsupported port exception"); } catch (NotSupportedException ex) { Assert.AreEqual("TLS not supported", ex.Message); } }
/// <summary> /// The Footer App will insert a custom footer at the bottom of the text and HTML bodies. /// http://docs.sendgrid.com/documentation/apps/footer/ /// </summary> public void EnableFooterEmail() { //create a new message object var message = Mail.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body var timestamp = DateTime.Now.ToString("HH:mm:ss tt"); message.Html = "<p style='color:red';>Hello World</p>"; message.Html += "<p>Sent At : " + timestamp + "</p>"; message.Text = "Hello World plain text"; //set the message subject message.Subject = "Hello World Footer Test"; //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password)); //Enable Footer message.EnableFooter("PLAIN TEXT FOOTER", "<p color='blue'>HTML FOOTER TEXT</p>"); //send the mail transportInstance.DeliverAsync(message); }
public static void SendThread() { //create SMTP object SMTP objSMTP = new SMTP(); objSMTP.SMTPServers.Add("smtp.socketlabs.com", 25, 60, SMTPAuthMode.AuthLogin, "your_smtp_user", "your_smtp_password"); /* * this sample just sends one message per thread/connection but in the real world you should send about * 50-100 messages per connection. You will have to add your database retrieval and loop management here * * i.e. grab 50 records from db, connect, loop through and send all 50 and then disconnect * repeat as long as there are more records to process in database */ //establish connection and keep it open for all messages we send objSMTP.Connect(); EmailMessage objMessage = new EmailMessage(); objMessage.From = new Address("*****@*****.**", "Sender Name"); objMessage.Recipients.Add("*****@*****.**", "Recipient Name", RecipientType.To); objMessage.Subject = "Subject..."; objMessage.BodyParts.Add("Hi ##FIRSTNAME##, Thank you for your interest in ##PRODUCT##.", BodyPartFormat.Plain, BodyPartEncoding.QuotedPrintable); Dictionary<string, string> tokens = new Dictionary<string, string>(); tokens["##FIRSTNAME##"] = "John"; tokens["##PRODUCT##"] = "SocketLabs Email On-Demand"; objMessage.BodyParts[0].Body = BulkReplace(objMessage.BodyParts[0].Body, tokens); objSMTP.Send(objMessage); //close connection after all messages have been sent objSMTP.Disconnect(); Interlocked.Decrement(ref threadsOpen); }
public bool EnviarEmail(Email msgMail, SMTP smtpccliente) { msgMail.From = smtpccliente.SMTPEmail; var mm = new MailMessage(); mm.From = new MailAddress(msgMail.From, msgMail.DisplayNameFrom); foreach (var item in msgMail.To) { mm.To.Add(item); } if (msgMail.CC != null) { foreach (var item in msgMail.CC) { mm.CC.Add(item); } } if (msgMail.CCO != null) { foreach (var item in msgMail.CCO) { mm.Bcc.Add(item); } } mm.Subject = msgMail.Subject; mm.Body = msgMail.Body; mm.IsBodyHtml = msgMail.HtmlBody; SmtpClient smtp = new SmtpClient(smtpccliente.SMTPDominio, smtpccliente.SMTPPorta); smtp.UseDefaultCredentials = false; //verificar //smtp.UseDefaultCredentials = true; smtp.Credentials = new System.Net.NetworkCredential(smtpccliente.SMTPEmail, smtpccliente.SMTPSenha); smtp.EnableSsl = smtpccliente.SMTPSSL == 1 ? true : false; //smtp.Timeout = smtptimeout; smtp.Send(mm); if (msgMail.CC != null) { msgMail.To.AddRange(msgMail.CC); } if (msgMail.CCO != null) { msgMail.To.AddRange(msgMail.CCO); } //var destinatarios = string.Join(", ", msgMail.To); //var mensagem = $"E-mail enviado para '{destinatarios}' - Título: {msgMail.Subject}"; return(true); }
public async Task <ServiceResult> SendEmailAsync(string ip, string toEmail, string fromEmail, string subject, string body, EmailSettings settings) { if (string.IsNullOrWhiteSpace(settings.SiteDomain)) { _logger.InsertError("The email setting site domain key is not set.", "UserManager", "SendEmail"); return(ServiceResponse.Error("An error occured when sending the message. <br/>ERROR: Site Domain configuration.")); } if (string.IsNullOrWhiteSpace(settings.SiteEmail)) { _logger.InsertError("The email setting SiteEmail is not set.", "UserManager", "SendEmail"); return(ServiceResponse.Error("An error occured when sending the message.")); } string siteEmail = settings.SiteEmail; MailAddress ma = new MailAddress(siteEmail, settings.SiteDomain); MailMessage mail = new MailMessage(); mail.From = ma; mail.ReplyToList.Add(ma); mail.To.Add(toEmail); mail.Subject = subject; mail.Body = body; mail.IsBodyHtml = true; SMTP mailServer = new SMTP(this._connectionKey, settings); return(await mailServer.SendMailAsync(mail)); }
private static void SendErrorNotification(int extensionId) { try { var smtpserver = RoleEnvironment.GetConfigurationSettingValue(Constants.SmtpServer); var username = RoleEnvironment.GetConfigurationSettingValue(Constants.SmtpUsername); var password = RoleEnvironment.GetConfigurationSettingValue(Constants.SmtpPassword); var from = RoleEnvironment.GetConfigurationSettingValue(Constants.EmailFrom); var emailTo = RoleEnvironment.GetConfigurationSettingValue(Constants.EmailTo); var transportInstance = SMTP.GetInstance(new NetworkCredential(username, password), smtpserver); //create a new message object var message = SendGrid.GetInstance(); //set the message recipients message.AddTo(emailTo); //set the sender message.From = new MailAddress(from); //set the message body message.Html = string.Format("<html><p>Hello Nathan,</p><p>While processing this ({0}) package, I encountered an error!</p>" + "<p>Best regards, <br />EVS</p></html>", extensionId); //set the message subject message.Subject = "EVS has encountered an error."; //send the mail transportInstance.Deliver(message); } catch (Exception exc) { Trace.TraceError("Error while sending error notification.", exc.Message); } }
private void AddContentAndSend(SendGrid myMessage) { try { var lunches = LunchRepository.GetLunchesForThisWeek().ToList(); myMessage.From = new MailAddress("*****@*****.**", "Mittagessen Service"); myMessage.Subject = "Herzliche Einladung zum Mittagessen"; myMessage.AddAttachment(GetImageFile(lunches[0].CookedMeal.ImageName), "dienstag.jpg"); myMessage.AddAttachment(GetImageFile(lunches[1].CookedMeal.ImageName), "mittwoch.jpg"); myMessage.AddAttachment(GetImageFile(lunches[2].CookedMeal.ImageName), "donnerstag.jpg"); myMessage.Html = string.Format(MAIL_TEMPLATE, lunches[0].CookedMeal.Name, "cid:dienstag.jpg", GetImageUrl(lunches[0].CookedMeal.ImageName), lunches[1].CookedMeal.Name, "cid:mittwoch.jpg", GetImageUrl(lunches[1].CookedMeal.ImageName), lunches[2].CookedMeal.Name, "cid:donnerstag.jpg", GetImageUrl(lunches[2].CookedMeal.ImageName)); // Create credentials, specifying your user name and password. var credentials = new NetworkCredential( ConfigurationManager.AppSettings["MailLogin"], ConfigurationManager.AppSettings["MailPassword"]); // Create an SMTP transport for sending email. var transportSMTP = SMTP.GetInstance(credentials); // Send the email. transportSMTP.Deliver(myMessage); } catch (Exception e) { Logger.FatalException("Email exception occured", e); } }
public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model) { var IPAddress = Server.HtmlEncode(Request.UserHostAddress); ViewBag.IPAddress = IPAddress; var subject = "Forgot Email"; var instigator = "Login System"; var system = "Account Controller"; if (ModelState.IsValid) { var user = await UserManager.FindByNameAsync(model.Email); if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) { // Don't reveal that the user does not exist or is not confirmed return(View("ForgotPasswordConfirmation")); } // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); instigator = user.Email; await SMTP.SendNewEmail("*****@*****.**", user.Email, "Basically Prepared", "", "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + $"\">{callbackUrl}</a>.<br />You can also copy and paste the link to your URL if your email does not allow you to clink on links.", "PasswordReset"); await Logger.CreateNewLog($"Password reset request successful for {instigator} on {IPAddress}.", subject, instigator, system); return(RedirectToAction("ForgotPasswordConfirmation", "Account")); } // If we got this far, something failed, redisplay form return(View(model)); }
public void SimpleEmail(string subject, string messageToSend) { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body message.Html = messageToSend; //set the message subject message.Subject = subject; //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password)); //send the mail transportInstance.Deliver(message); }
public void ProbarCorreo(string remitente, string servidorSmtp, string contenido, string asunto, string destinatario) { EmailMessage email = new EmailMessage(destinatario, remitente, asunto, contenido, BodyPartFormat.Plain); SMTP smtpClient = new SMTP(servidorSmtp); smtpClient.Send(email); }
private void CargarVista() { try { using (db_FacturaDigital db = new db_FacturaDigital()) { SMTP value = db.SMTP.FirstOrDefault(); if (value == null) { return; } txt_host.Text = value.Url_Servidor; txt_Puerto.Text = value.Puerto.ToString(); txt_Usuario.Text = value.Usuario; txt_contrasena.Password = value.Contrasena; chk_SSL.IsChecked = value.SSL; txt_EmailDetails.Text = value.Detalle_Email; } } catch (Exception ex) { this.LogError(ex); MessageBox.Show("Error al cargar los datos del correo", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
private void SearchFpSMTP(List <string> dominios) { foreach (var domStr in dominios) { if (CheckToSkip()) { break; } var domain = Program.data.GetDomain(domStr); var existsFp = false; for (var fpI = 0; fpI < domain.fingerPrinting.Count(); fpI++) { var fp = domain.fingerPrinting[fpI]; if (fp is SMTP) { existsFp = true; } } if (existsFp) // do not redo the fingerprinting { continue; } FingerPrinting fprinting = new SMTP(domain.Domain, 25); domain.fingerPrinting.Add(fprinting); fprinting.GetVersion(); FingerPrintingEventHandler.AsociateFingerPrinting(fprinting, null); } }
private static void SendUsingSendGrid(string[] mailingList, IMessage message) { //TODO: add sending logic here // Setup the email properties. var from = new MailAddress(message.ReplyTo); var to = new MailAddress[mailingList.Length]; for (int i = 0; i < mailingList.Length; i++) { to[i] = new MailAddress(mailingList[i]); } var cc = new MailAddress[] { }; var bcc = new MailAddress[] { }; var subject = message.Subject; var html = message.Body.Replace(Environment.NewLine, "<br/>") + "<br/>" + message.Link; // Create an email, passing in the the eight properties as arguments. SendGrid myMessage = SendGrid.GetInstance(from, to, cc, bcc, subject, html, null); var username = WebConfigurationManager.AppSettings["SendGridLogin"]; var pswd = WebConfigurationManager.AppSettings["SendGridPassword"]; var credentials = new NetworkCredential(username, pswd); var transportSMTP = SMTP.GetInstance(credentials); transportSMTP.Deliver(myMessage); }
/// <summary> /// Sends the email. /// </summary> /// <param name="message">The message.</param> /// <returns><c>true</c> if email sent succesfully, <c>false</c> otherwise.</returns> public bool SendEmail(IEmailMessage message) { if (message == null) { return(false); } //Smtp settings ?? is it OK to read setting directly here from config? var smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp"); // Create the email object first, then add the properties. var eMessage = SendGrid.GetInstance(); eMessage.From = !string.IsNullOrEmpty(message.From) ? new MailAddress(message.From) : new MailAddress(smtp.From); // Add multiple addresses to the To field. eMessage.AddTo(message.To); eMessage.Subject = message.Subject; //Add the HTML and Text bodies eMessage.Html = message.Html; eMessage.Text = message.Text; //Add attachments if (message.Attachments != null && message.Attachments.Count > 0) { foreach (var attachment in message.Attachments) { try { using (var stream = new MemoryStream(attachment.Length)) { stream.Write(attachment, 0, attachment.Length); stream.Position = 0; eMessage.AddAttachment(stream, "file_" + message.Attachments.IndexOf(attachment)); } } catch { return(false); } } } // Create credentials, specifying your user name and password. var credentials = new NetworkCredential(smtp.Network.UserName, smtp.Network.Password); // Create an SMTP transport for sending email. var transportSMTP = SMTP.GetInstance(credentials, smtp.Network.Host, smtp.Network.Port); // Send the email. try { transportSMTP.Deliver(eMessage); } catch { return(false); } return(true); }
public static string SendMailBySendGrid(string Html, string Subject, string UserId, string Password, string FromName, string FromEmail, string ToEmail) { string sendMailBySendGrid = string.Empty; try { //var smtp = new SmtpClient(); //smtp.Port = 25; //smtp.Host = "smtp.sendgrid.net"; SendGrid myMessage = SendGridMail.SendGrid.GetInstance(); myMessage.AddTo(ToEmail); myMessage.From = new MailAddress(FromEmail); myMessage.Subject = Subject; //Add the HTML and Text bodies myMessage.Html = Html; //myMessage.InitializeFilters(); var credentials = new NetworkCredential(UserId, Password); var transportWeb = SMTP.GetInstance(credentials); // Send the email. transportWeb.Deliver(myMessage); sendMailBySendGrid = "success"; } catch (Exception ex) { Console.WriteLine(ex.Message); sendMailBySendGrid = "failed"; } return(sendMailBySendGrid); }
public ActionResult ChangePassword(FormCollection collection) { if (collection["UserEmail"] == null || collection["UserOldPassword"] == null || collection["UserNewPassword"] == null || collection["UserNewPasswordConfirm"] == null) { return(RedirectToAction("ChangePassword", "User")); } var userEmail = (collection["UserEmail"] != null)?collection["UserEmail"].ToString(): null; var UserOldPassword = (collection["UserOldPassword"] != null)? collection["UserOldPassword"].ToString(): null; var UserNewPassword = (collection["UserNewPassword"] != null)? collection["UserNewPassword"].ToString(): null; var UserNewPasswordConfirm = (collection["UserNewPasswordConfirm"] != null)? collection["UserNewPasswordConfirm"].ToString(): null; var user = KitBL.Instance.Users.GetByEmailPass(userEmail, UserOldPassword); if (user == null) { user = KitBL.Instance.Users.GetByEmailPass(userEmail, UserOldPassword.Replace("NewPassword", string.Empty)); } if (user != null && UserNewPassword == UserNewPasswordConfirm) { user.PasswordHashed = UserNewPassword; KitBL.Instance.Users.Update(user); SMTP.sendEmail("*****@*****.**", user.Email, "Your password was changed!", "Thank you for using knowledgeshare.ro . Your password was changed at your request, if you lose it you can generate a new one anytime."); return(RedirectToAction("Profile", "User")); } else { return(RedirectToAction("Index", "Home")); } }
public string SendMail(string from, string passsword, string to, string bcc, string cc, string subject, string body, string sendgridUserName = "", string sendgridPassword = "") { string sendMailBySendGrid = string.Empty; try { //var smtp = new SmtpClient(); //smtp.Port = 25; //smtp.Host = "smtp.sendgrid.net"; SendGrid myMessage = SendGridMail.SendGrid.GetInstance(); myMessage.AddTo(to); myMessage.From = new MailAddress(from); myMessage.Subject = subject; //Add the HTML and Text bodies myMessage.Html = body; //myMessage.InitializeFilters(); var credentials = new NetworkCredential(sendgridUserName, sendgridPassword); var transportWeb = SMTP.GetInstance(credentials); // Send the email. transportWeb.Deliver(myMessage); sendMailBySendGrid = "Success"; } catch (Exception ex) { Console.WriteLine(ex.Message); } return(sendMailBySendGrid); }
/// <summary> /// SendMailBySendGrid /// this function is used for sending mail vai SendGrid /// the main input parameter is : ///<add key="host" value="smtp.sendgrid.net" /> /// <add key="port" value="25" /> /// <add key="username" value="socioboard"/> /// <add key="fromemail" value="*****@*****.**"/> /// <add key="password" value="xyz" /> ///<add key="tomail" value="*****@*****.**" /> /// /// its return : success if mail send else return string.Empty; /// /// </summary> /// <param name="Host"></param> /// <param name="port"></param> /// <param name="from"></param> /// <param name="passsword"></param> /// <param name="to"></param> /// <param name="bcc"></param> /// <param name="cc"></param> /// <param name="subject"></param> /// <param name="body"></param> /// <param name="sendgridUserName"></param> /// <param name="sendgridPassword"></param> /// <returns></returns> public string SendMailBySendGrid(string Host, int port, string from, string passsword, string to, string bcc, string cc, string subject, string body, string sendgridUserName, string sendgridPassword) { string sendMailBySendGrid = string.Empty; try { var myMessage = SendGridMail.SendGrid.GetInstance(); myMessage.From = new System.Net.Mail.MailAddress(from); myMessage.AddTo(to); myMessage.Subject = subject; //Add the HTML and Text bodies myMessage.Html = body; //myMessage.Text = "Hello World plain text!"; var username = sendgridUserName; var pswd = sendgridPassword; var credentials = new System.Net.NetworkCredential(username, pswd); var transportWeb = SMTP.GetInstance(credentials); // Send the email. transportWeb.Deliver(myMessage); sendMailBySendGrid = "Success"; } catch (Exception ex) { Console.WriteLine(ex.Message); logger.Error(ex.Message); } return(sendMailBySendGrid); }
/// <summary> /// Enable The Gravatar Filter. /// Currently the filter generates a 1x1 pixel gravatar image. /// http://docs.sendgrid.com/documentation/apps/gravatar/ /// </summary> public void EnableGravatarEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body message.Html = "<p style='color:red';>Hello World Gravatar Email</p>"; //set the message subject message.Subject = "Hello World Gravatar Test"; //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password)); //enable gravatar message.EnableGravatar(); //send the mail transportInstance.Deliver(message); }
/// <summary> /// Point the urls to Sendgrid Servers so that the clicks can be logged before /// being directed to the appropriate link /// http://docs.sendgrid.com/documentation/apps/click-tracking/ /// </summary> public void EnableClickTrackingEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body var timestamp = DateTime.Now.ToString("HH:mm:ss tt"); message.Html = "<p style='color:red';>Hello World HTML </p> <a href='http://microsoft.com'>Checkout Microsoft!!</a>"; message.Html += "<p>Sent At : " + timestamp + "</p>"; message.Text = "hello world http://microsoft.com"; //set the message subject message.Subject = "Hello World Click Tracking Test"; //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password)); //enable clicktracking message.EnableClickTracking(false); //send the mail transportInstance.Deliver(message); }
/// <summary> /// This feature tags the message with a specific tracking category, which will have aggregated stats /// viewable from your SendGrid account page. /// </summary> public void SetCategory() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body message.Text = "Hello World"; //set the message subject message.Subject = "Testing Categories"; var category = "vipCustomers"; message.SetCategory(category); //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password)); //enable bypass list management message.EnableBypassListManagement(); //send the mail transportInstance.Deliver(message); }
/// <summary> /// Send a simple Plain Text email /// </summary> public void SimplePlaintextEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body message.Text = "Hello World Plain Text"; //set the message subject message.Subject = "Hello World Plain Text Test"; //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password)); //send the mail transportInstance.Deliver(message); }
/// <summary> /// The Footer App will insert a custom footer at the bottom of the text and HTML bodies. /// http://docs.sendgrid.com/documentation/apps/google-analytics/ /// </summary> public void EnableGoogleAnalytics() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body var timestamp = DateTime.Now.ToString("HH:mm:ss tt"); message.Html = "<p style='color:red';>Hello World</p>"; message.Html += "<p>Sent At : " + timestamp + "</p>"; message.Html += "Checkout my page at <a href=\"http://microsoft.com\">Microsoft</a>"; message.Text = "Hello World plain text"; //set the message subject message.Subject = "Hello World Footer Test"; //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password)); //enable Google Analytics message.EnableGoogleAnalytics("SendGridTest", "EMAIL", "Sendgrid", "ad-one", "My SG Campaign"); //send the mail transportInstance.Deliver(message); }
/// <summary> /// This feature wraps an HTML template around your email content. /// This can be useful for sending out newsletters and/or other HTML formatted messages. /// hhttp://docs.sendgrid.com/documentation/apps/email-templates/ /// </summary> public void EnableBypassListManagementEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body var timestamp = DateTime.Now.ToString("HH:mm:ss tt"); message.Html = "<p style='color:red';>Hello World</p>"; message.Html += "<p>Sent At : " + timestamp + "</p>"; message.Text = "Hello World plain text"; //set the message subject message.Subject = "Hello World Bypass List Management Test"; //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password)); //enable bypass list management message.EnableBypassListManagement(); //send the mail transportInstance.Deliver(message); }
/// <summary> /// The Spam Checker filter, is useful when your web application allows your end users /// to create content that is then emailed through your SendGrid account. /// http://docs.sendgrid.com/documentation/apps/spam-checker-filter/ /// </summary> public void EnableSpamCheckEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body var timestamp = DateTime.Now.ToString("HH:mm:ss tt"); message.Html = "<p style='color:red';>VIAGRA!!!!!! Viagra!!! CHECKOUT THIS VIAGRA!!!! MALE ENHANCEMENT!!! </p>"; message.Html += "<p>Sent At : " + timestamp + "</p>"; //set the message subject message.Subject = "WIN A MILLION DOLLARS TODAY! WORK FROM HOME! A NIGERIAN PRINCE WANTS YOU!"; //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password)); //enable spamcheck message.EnableSpamCheck(); //send the mail transportInstance.Deliver(message); }
/// <summary> /// Add automatic unsubscribe links to the bottom of emails. /// http://docs.sendgrid.com/documentation/apps/subscription-tracking/ /// </summary> public void EnableUnsubscribeEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body message.Html = "This is the HTML body"; message.Text = "This is the plain text body"; //set the message subject message.Subject = "Hello World Unsubscribe Test"; //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password)); //enable spamcheck //or optionally, you can specify 'replace' instead of the text and html in order to //place the link wherever you want. message.EnableUnsubscribe("Please click the following link to unsubscribe: <% %>", "Please click <% here %> to unsubscribe"); //send the mail transportInstance.Deliver(message); }
private void BTN_CheckMail_Click(object sender, EventArgs e) { try { SMTP.SendMail(TB_EMailFrom.Text, TB_EMailTo.Text, TB_SMTPServer.Text, TB_SMTPPort.Text, TB_EMailPassword.Text, DefaultSubject, DefaultBody); MessageBox.Show("Mail successfully sent, check your inbox", "Unknown Logger", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception Ex) { if (TB_SMTPServer.Text == DefaultGoogleSMTPServer) { DialogResult dialogResult = MessageBox.Show("ERROR: Bad port or credentials or in order to receive emails using SMTP you have to enable 'less secure apps'. Do you want to launch https://www.google.com/settings/security/lesssecureapps?", "Unknown Logger", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dialogResult == DialogResult.Yes) { System.Diagnostics.Process.Start(LessSecureAppsLink); } else { MessageBox.Show("Choose a different E-Mail service please", "Unknown Logger", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else { MessageBox.Show("Error: " + Ex, "Unknown Logger", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
private void butnSendMail_Click(object sender, System.EventArgs e) { butnSendMail.Enabled = false; try { Indy.Sockets.Message LMsg = new Indy.Sockets.Message(); LMsg.From.Text = textFrom.Text.Trim(); LMsg.Recipients.Add().Text = textTo.Text.Trim(); LMsg.Subject = textSubject.Text.Trim(); LMsg.Body.Text = textMsg.Text; // Attachment example // new AttachmentFile(LMsg.MessageParts, @"c:\temp\Hydroponics.txt"); SMTP LSMTP = new SMTP(); LSMTP.OnStatus += new Indy.Sockets.TIdStatusEvent(SMTPStatus); LSMTP.Host = textSMTPServer.Text.Trim(); LSMTP.Connect(); try { LSMTP.Send(LMsg); Status("Completed"); } finally { LSMTP.Disconnect(); } } finally { butnSendMail.Enabled = true; } }
public ActionResult RequestPasswordResetConfirmation(string email) { var user = UserRepository.GetUserByNameOrEmail(email); if (user != null) { var myMessage = SendGrid.GetInstance(); myMessage.AddTo(user.Email); myMessage.From = new MailAddress("*****@*****.**", "Mittagessen Service"); myMessage.Subject = "Mittagessen Passwort zurücksetzen"; var passwordResetString = PasswordResetHelper.EncryptString(user.Email); myMessage.Html = string.Format(MAIL_TEMPLATE, Url.Action("ResetPassword", "Account", null, Request.Url.Scheme), HttpUtility.UrlEncode(passwordResetString)); // Create credentials, specifying your user name and password. var credentials = new NetworkCredential( ConfigurationManager.AppSettings["MailLogin"], ConfigurationManager.AppSettings["MailPassword"]); // Create an SMTP transport for sending email. var transportSMTP = SMTP.GetInstance(credentials); // Send the email. transportSMTP.Deliver(myMessage); } return(View("RequestPasswordResetConfirmation", user)); }
public CmdSMTPCommunicatable(string commandName, SMTP.SMTPCommunicator smtpCommunicator) : base(commandName) { this.SMTPCommunicator = smtpCommunicator; }
private static void AssertEmailsAreEqual(SMTP.EMail actual, SMTP.EMail expected) { CollectionAssert.AreEqual (actual.From, expected.From); Assert.That(actual.To,Is.EqualTo(expected.To)); Assert.That(actual.Subject,Is.EqualTo(expected.Subject)); CollectionAssert.AreEquivalent (expected.Headers, actual.Headers); CollectionAssert.AreEqual (expected.Body, actual.Body); }
public Pusher() { _pushOver = new PushOver(); _smtp = new SMTP(); _pushALot = new PushALot(); }
public CmdStartTls(SMTP.SMTPCommunicator smtpCommunicator) : base("StartTls", smtpCommunicator) { base.Command.Description = "Open or close TLS connection session."; }
public CmdClose(SMTP.SMTPCommunicator smtpCommunicator) : base("Close", smtpCommunicator) { base.Command.Description = "Close the connection to a SMTP server."; }
private void OnUpdateMessage(object sender, SMTP.Commands.CommandEvent.CommandEventArgs e) { base.RaiseUpdateMessage(this, e.Message, e.Type); }
public CmdSay(SMTP.SMTPCommunicator smtpCommunicator) : base("Say", smtpCommunicator) { base.Command.Description = "Send string to SMTP server and wait for its response."; }
public CmdOpen(SMTP.SMTPCommunicator smtpCommunicator) : base("open", smtpCommunicator) { base.Command.Description = "Open a connection to a STMP server."; }
static void Main(string[] args) { Quiksoft.EasyMail.SMTP.License.Key = "Scott Griswold (Single Developer)/8008767F195514552F8DE5C145E3A7"; firstDate = DateTime.Now.ToShortDateString(); secondDate = DateTime.Now.AddDays(1).ToShortDateString(); Walden.Medical.Library.ChangeWindowState.SetConsoleWindowVisibility(false, Console.Title); Database.WaldenReminderConnection = System.Configuration .ConfigurationManager.AppSettings["walden"]; try { using (SqlConnection cn = new SqlConnection(Database.WaldenReminderConnection)) { cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandText = " SELECT count(SendID)" + " FROM [dbo].[FaxesSendServer]" + " where status ='Completed'" + " and createtime between '" + firstDate + "' and '" + secondDate + "'"; SqlDataReader dr = cm.ExecuteReader(); dr.Read(); numberOfSuccessfulfaxes = dr.GetInt32(0); } } } catch(Exception er) { string s1 = er.Message; } try { using (SqlConnection cn = new SqlConnection(Database.WaldenReminderConnection)) { cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandText = " SELECT count(SendID)" + " FROM [dbo].[FaxesSendServer]" + " where status NOT IN ('Completed')" + " and createtime between '" + firstDate + "' and '" + secondDate + "'"; SqlDataReader dr = cm.ExecuteReader(); dr.Read(); numberOfUnSuccessfulfaxes = dr.GetInt32(0); _emailTo = System.Configuration .ConfigurationManager.AppSettings["EmailTo"]; _smtpServer = System.Configuration .ConfigurationManager.AppSettings["SMTPServer"]; //Create the EmailMessage object EmailMessage _messageObject = new EmailMessage(); _messageObject.Subject = "Reminder Call Report"; //Add a normal recipient _messageObject.Recipients.Add(_emailTo); Debug.WriteLine(_emailTo); //Specify the sender _messageObject.From.Email = _emailTo; //_messageObject.From.Email = "*****@*****.**"; _messageObject.From.Name = "Daily Fax Activity"; string messagebody = "Fax Activity for " + firstDate + Environment.NewLine + " Successful faxes: " + numberOfSuccessfulfaxes.ToString() + Environment.NewLine + " Number of Unsuccessful faxes: " + numberOfUnSuccessfulfaxes.ToString(); //Set message body _messageObject.BodyParts.Add(messagebody); //Add attachment //_messageObject.Attachments.Add(_ApplicationPath + "\\Report.pdf"); //Specify the mail server and enable authentication _server.Name = _smtpServer; Debug.WriteLine(_smtpServer); // _server.Account = _smtpUID; // _server.Password = _smtpPWD; _server.AuthMode = SMTPAuthMode.None; SMTP _smtpObject = new SMTP(); try { //Add mail server _smtpObject.SMTPServers.Add(_server); //Send the message _smtpObject.Send(_messageObject); } catch (FileIOException FileIOExcep) { Console.WriteLine("File IO error: " + FileIOExcep.Message); return; } catch (SMTPAuthenticationException SMTPAuthExcep) { Console.WriteLine("SMTP Authentication error: " + SMTPAuthExcep.Message); return; } catch (SMTPConnectionException SMTPConnectExcep) { Console.WriteLine("Connection error: " + SMTPConnectExcep.Message); return; } catch (SMTPProtocolException SMTPProtocolExcep) { Console.WriteLine("SMTP protocol error: " + SMTPProtocolExcep.Message); return; } Console.WriteLine("Message sent."); } } } catch (Exception er) { string s1 = er.Message; } }
private static void AssertEmailsAreEqual(SMTP.EMail actual, MimeMessage msg) { var body = msg.GetTextBody (MimeKit.Text.TextFormat.Text); var expected = new SMTP.EMail ( string.IsNullOrEmpty (body) ? new string[0] : new[] { body }, msg.Subject, msg.From.Select (s => s.ToString ()), msg.To.Select (s => s.ToString ()), msg.Headers .Select (h => h.Field + ": " + h.Value) .Concat (msg.Body.Headers.Select (h => h.ToString ()))); AssertEmailsAreEqual (actual, expected); }