public ActionResult Send([ModelBinder(typeof(MailModelBinder))]MailModel model, string vendore, string redirectUrl) { var username = ConfigurationManager.AppSettings["SendGridUsername"]; var password = ConfigurationManager.AppSettings["SendGridPassword"]; var message = new SendGridMessage(); message.AddTo(ConfigurationManager.AppSettings["SupportToEmail"]); message.From = new MailAddress(model.To, model.FullName); message.Subject = model.Subject; message.Html = model.FullMailBody; var credentials = new NetworkCredential(username, password); var transportWeb = new Web(credentials); transportWeb.Deliver(message); if (!string.IsNullOrEmpty(vendore)) { try { message = new SendGridMessage(); message.AddTo(vendore.Replace("[", "@")); message.From = new MailAddress(model.To, model.FullName); message.Subject = model.Subject; message.Html = model.FullMailBody; transportWeb.Deliver(message); } catch { } } return Redirect(redirectUrl); }
public void SendEmail(MailMessage mail) { var environment = ConfigurationManager.AppSettings["environment"]; if (environment == "prod") { var accountSendGrid = ConfigurationManager.AppSettings["mailAccountSendGrid"]; var passwordSendGrid = ConfigurationManager.AppSettings["mailPasswordSenGrid"]; var credentials = new NetworkCredential(accountSendGrid, passwordSendGrid); var transportWeb = new SendGrid.Web(credentials); SendGridMessage myMessage = new SendGridMessage(); myMessage.AddTo(mail.To.ToString()); myMessage.From = new MailAddress(mail.From.ToString(), "Coordonateur de stages"); myMessage.Subject = mail.Subject.ToString(); myMessage.Text = mail.Body.ToString(); transportWeb.Deliver(myMessage); } else { var client = new SmtpClient("jenkinssmtp.cegep-ste-foy.qc.ca", 25) { DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false }; client.Send(mail); } }
public void SendEmail(string toEmail) { var Password = "******"; var SMTP_SERVER = "smtp.sendgrid.net"; var Username = "******"; var fromEmail = "*****@*****.**"; var fromName = "CMU HCI @ HackGT"; var message = "awesome test message"; var credentials = new NetworkCredential(Username, Password); // Create the email object first, then add the properties. // Create the email object first, then add the properties. SendGridMessage myMessage = new SendGridMessage(); myMessage.AddTo(toEmail); myMessage.From = new MailAddress(fromEmail, fromName); myMessage.Subject = "SafetyNet - Emergency"; myMessage.Text = message; // Create an Web transport for sending email. var transportWeb = new Web(credentials); // Send the email. // You can also use the **DeliverAsync** method, which returns an awaitable task. transportWeb.Deliver(myMessage); }
private void SendMail() { Setup(); var credentials = new NetworkCredential(mySenGridData.UserName, mySenGridData.Pswd); // Create the email object first, then add the properties. SendGridMessage myMessage = new SendGridMessage(); myMessage.AddTo(mySenGridData.To); myMessage.From = new MailAddress(mySenGridData.FromMail, mySenGridData.FromName); myMessage.Subject = string.Format("Butler Media Process {0} inctance {1}",myRequest.ProcessTypeId,myRequest.ProcessInstanceId); _MediaServiceContext = new CloudMediaContext(myRequest.MediaAccountName, myRequest.MediaAccountKey); IAsset x = _MediaServiceContext.Assets.Where(xx => xx.Id == myRequest.AssetId).FirstOrDefault(); AssetInfo ai = new AssetInfo(x); StringBuilder AssetInfoResume = ai.GetStatsTxt(); AssetInfoResume.AppendLine(""); AssetInfoResume.AppendLine("Media Butler Process LOG " + DateTime.Now.ToString()); foreach (string txt in myRequest.Log) { AssetInfoResume.AppendLine(txt); } AssetInfoResume.AppendLine("-----------------------------"); myMessage.Html = AssetInfoResume.Replace(" ", " ").Replace(Environment.NewLine, "<br />").ToString(); var transportWeb = new Web(credentials); transportWeb.Deliver(myMessage); }
public bool SendEmail(MailAddress from, MailAddress to, MailAddress replyTo, string subject, Encoding subjectEncoding, string body, Encoding bodyEncoding, bool isBodyHtml) { if (this.disposed) { throw new ApplicationException("Object is disposed!"); } // Create the email object first, then add the properties. var myMessage = new SendGridMessage(from, new MailAddress[] { to }, subject, null, body); if (replyTo != null) { myMessage.ReplyTo = new MailAddress[] { replyTo }; } // Send the email. if (transportWeb != null) { transportWeb.Deliver(myMessage); return(true); } return(false); }
private void sendEmails(Dictionary<string, string> users) { if (users.Count < 1) { return; } var credentials = new NetworkCredential("*****@*****.**", "qYzcc6C3Z1A7TB2"); var transportWeb = new Web(credentials); var myMessage = new SendGridMessage(); myMessage.From = new MailAddress("*****@*****.**", "ExpInfo team"); myMessage.Text = "Happy Birthday! Thanks for using our servises!"; foreach (var user in users) { try { myMessage.AddTo(user.Value); myMessage.Subject = string.Format("Hello, {0}!", user.Key); // Send the email. transportWeb.Deliver(myMessage); } catch (Exception) { } } }
public void Send(SendGridMessage message) { // Create network credentials to access your SendGrid account. var credentials = new NetworkCredential(_sendGridUsername, _sendGridPassword); // Create an Web transport for sending email. var transportWeb = new Web(credentials); // Disable Unsubsribe message.DisableUnsubscribe(); var email = ConfigurationManager.AppSettings["TestNotifications"]; var testMessage = new SendGridMessage { Subject = message.Subject, Html = message.Html, Attachments = message.Attachments, StreamedAttachments = message.StreamedAttachments }; testMessage.AddTo(email); testMessage.From = new MailAddress("*****@*****.**", "AquaCulture Monitor"); transportWeb.Deliver(testMessage); }
private void SendWithSendGrid(SendGridMessage message) { var unencodedPassword = Encoding.UTF8.GetString(_encryptionService.Decode(Convert.FromBase64String(_mailSettings.SendGridAccountPassword))); var credentials = new NetworkCredential(_mailSettings.SendGridAccountName, unencodedPassword); // Create an Web transport for sending email. var transportWeb = new Web(credentials); // Send the email. transportWeb.Deliver(message); }
public static bool SendCurrentIncidentInvoiceEmail(Incident incident, ApiServices Services) { IncidentInfo invoiceIncident = new IncidentInfo(incident); if (invoiceIncident.PaymentAmount < invoiceIncident.ServiceFee) { SendGridMessage invoiceMessage = new SendGridMessage(); invoiceMessage.From = SendGridHelper.GetAppFrom(); invoiceMessage.AddTo(invoiceIncident.IncidentUserInfo.Email); invoiceMessage.Html = " "; invoiceMessage.Text = " "; invoiceMessage.Subject = "StrandD Invoice - Payment for Service Due"; invoiceMessage.EnableTemplateEngine(WebConfigurationManager.AppSettings["RZ_InvoiceTemplateID"]); invoiceMessage.AddSubstitution("%invoicestub%", new List<string> { invoiceIncident.IncidentGUID.Substring(0, 5).ToUpper() }); invoiceMessage.AddSubstitution("%incidentguid%", new List<string> { invoiceIncident.IncidentGUID }); invoiceMessage.AddSubstitution("%name%", new List<string> { invoiceIncident.IncidentUserInfo.Name }); invoiceMessage.AddSubstitution("%phone%", new List<string> { invoiceIncident.IncidentUserInfo.Phone }); invoiceMessage.AddSubstitution("%email%", new List<string> { invoiceIncident.IncidentUserInfo.Email }); invoiceMessage.AddSubstitution("%jobdescription%", new List<string> { invoiceIncident.JobCode }); invoiceMessage.AddSubstitution("%servicefee%", new List<string> { (invoiceIncident.ServiceFee - invoiceIncident.PaymentAmount).ToString() }); invoiceMessage.AddSubstitution("%datesubmitted%", new List<string> { DateTime.Now.ToShortDateString() }); invoiceMessage.AddSubstitution("%datedue%", new List<string> { (DateTime.Now.AddDays(30)).ToShortTimeString() }); invoiceMessage.AddSubstitution("%servicepaymentlink%", new List<string> { (WebConfigurationManager.AppSettings["RZ_ServiceBaseURL"].ToString() + "/view/customer/incidentpayment/" + invoiceIncident.IncidentGUID) }); // Create an Web transport for sending email. var transportWeb = new Web(SendGridHelper.GetNetCreds()); // Send the email. try { transportWeb.Deliver(invoiceMessage); Services.Log.Info("Incident Invoice Email Sent to [" + invoiceIncident.IncidentUserInfo.Email + "]"); return true; } catch (InvalidApiRequestException ex) { for (int i = 0; i < ex.Errors.Length; i++) { Services.Log.Error(ex.Errors[i]); return false; } } return false; } else { return false; } }
/// <summary> /// Sends out an email from the application. Returns true if successful. /// </summary> public static bool SendGridEmail(string from, List<string> to, List<string> cc, List<string> bcc, string subj, string body, string smtpUser, string smtpUserPwd) { try { //******************** CONSTRUCT EMAIL ******************************************** // Create the email object first, then add the properties. var myMessage = new SendGridMessage(); // Add message properties. myMessage.From = new MailAddress(from); myMessage.AddTo(to); if (cc != null) { foreach (string cc1 in cc) myMessage.AddCc(cc1); } if (bcc != null) { foreach (string bcc1 in bcc) myMessage.AddBcc(bcc1); } myMessage.Subject = subj; //myMessage.Html = "<p>" + body + "</p>"; myMessage.Text = body; //********************************************************************************* //********************* SEND EMAIL ************************************************ var credentials = new NetworkCredential(smtpUser, smtpUserPwd); // Create an Web transport for sending email. var transportWeb = new Web(credentials); // Send the email. transportWeb.Deliver(myMessage); return true; } catch (Exception ex) { if (ex.InnerException != null) db_Ref.InsertT_OE_SYS_LOG("EMAIL ERR", ex.InnerException.ToString()); else if (ex.Message != null) db_Ref.InsertT_OE_SYS_LOG("EMAIL ERR", ex.Message.ToString()); else db_Ref.InsertT_OE_SYS_LOG("EMAIL ERR", "Unknown error"); return false; } }
public void Send() { GenerateMessage(); try { var credentials = new NetworkCredential("*****@*****.**", "8cbGXNV0jmXK3YN"); Message.From = new MailAddress("*****@*****.**", "Inner6"); var transportWeb = new Web(credentials); transportWeb.Deliver(Message); } catch (Exception ex) { //Logger.Error("Error sending email", new { Exception = ex }); } }
public void Send() { GenerateMessage(); try { var credentials = new NetworkCredential("*****@*****.**", "KHCLTE94rvwQ0dS"); Message.From = new MailAddress("*****@*****.**", "Admin"); var transportWeb = new Web(credentials); transportWeb.Deliver(Message); } catch (Exception ex) { //Logger.Error("Error sending email", new { Exception = ex }); } }
/// <summary> /// Sends the mail batch using the SendGrid API /// </summary> /// <param name="mail">The mail.</param> /// <param name="recipients">The recipients.</param> /// <param name="onlyTestDontSendMail">if set to <c>true</c> [only test dont send mail].</param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> public override bool SendMailBatch(MailInformation mail, IEnumerable<JobWorkItem> recipients, bool onlyTestDontSendMail) { var settings = GetSettings(); if (recipients == null || recipients.Any() == false) throw new ArgumentException("No workitems", "recipients"); if (recipients.Count() > 1000) throw new ArgumentOutOfRangeException("recipients", "SendGrid supports maximum 1000 recipients per batch send."); var msg = new SendGridMessage(); msg.From = new MailAddress(mail.From); msg.Subject = mail.Subject; msg.Html = mail.BodyHtml; msg.Text = mail.BodyText; // Add recipinets to header, to hide other recipients in to field. List<string> addresses = recipients.Select(r => r.EmailAddress).ToList(); msg.Header.SetTo(addresses); msg.AddSubstitution("%recipient%", addresses); // To send message we need to have a to address, set that to from msg.To = new MailAddress[] { msg.From }; if (mail.EnableTracking) { // true indicates that links in plain text portions of the email // should also be overwritten for link tracking purposes. msg.EnableClickTracking(true); msg.EnableOpenTracking(); } if(mail.CustomProperties.ContainsKey("SendGridCategory")) { string category = mail.CustomProperties["SendGridCategory"] as string; if (string.IsNullOrEmpty(category) == false) msg.SetCategory(category); } var credentials = new NetworkCredential(settings.Username, settings.Password); // Create an Web transport for sending email. var transportWeb = new Web(credentials); transportWeb.Deliver(msg); return true; }
public void Dispatch(Email message) { SendGridMessage sndGrdMsg = new SendGridMessage(); sndGrdMsg.From = new MailAddress(message.From); sndGrdMsg.AddTo(message.To); sndGrdMsg.Subject = message.Message.Subject; sndGrdMsg.Html = message.Message.Body; sndGrdMsg.Text = message.Message.BodyPlainText; NetworkCredential credentials = new NetworkCredential(configurationProvider.GetSetting(ConfigKeys.EmailServerUsername), configurationProvider.GetSetting(ConfigKeys.EmailServerPassword)); SendGrid.Web transportWeb = new SendGrid.Web(credentials); transportWeb.Deliver(sndGrdMsg); }
private void Send(SendGridMessage message) { // Create credentials, specifying your user name and password. var credentials = new NetworkCredential("*****@*****.**", "Lcf8K0NF1gJo7Fd"); // Create a Web transport for sending email. var transportWeb = new SendGrid.Web(credentials); // Send the email. try { transportWeb.Deliver(message); //activity log _studentActivityService.InsertActivity("Contact.Form.Sent", "ActivityLog.Contact.Form.Sent"); } catch (Exception ex) { // This is bad } }
public Task SendAsync(IdentityMessage message) { // Plug in your email service here to send an email. var settings = ConfigurationManager.GetSection("serviceCredentials") as ServiceCredentialsConfigurationSection; if (settings == null) { throw new ConfigurationErrorsException("Missing ServiceCredentials section"); } if (!string.IsNullOrWhiteSpace(settings.TwilioAccountSid) && !string.IsNullOrWhiteSpace(settings.TwilioAuthToken) && !string.IsNullOrWhiteSpace(settings.TwilioFromNumber)) { // Create the email object first, then add the properties. SendGridMessage myMessage = new SendGridMessage(); myMessage.AddTo(message.Destination); myMessage.From = new MailAddress(settings.SendGridFromEmail, settings.SendGridFromName); myMessage.Subject = message.Subject; myMessage.Text = message.Body; // Create credentials, specifying your user name and password. var credentials = new NetworkCredential(settings.SendGridUserName, settings.SendGridPassword); // Create an Web transport for sending email. var transportWeb = new SendGrid.Web(credentials); // Send the email. transportWeb.Deliver(myMessage); return(Task.FromResult(0)); } else { return(Task.FromResult(1)); } }
/// <summary> /// This feature allows you to create a message template, and specify different replacement /// strings for each specific recipient /// </summary> public void AddSubstitutionValues() { //create a new message object var message = new SendGridMessage(); //set the message recipients foreach (var recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body message.Text = "Hi %name%! Pleased to meet you!"; //set the message subject message.Subject = "Testing Substitution Values"; //This replacement key must exist in the message body var replacementKey = "%name%"; //There should be one value for each recipient in the To list var substitutionValues = new List<String> {"Mr Foo", "Mrs Raz"}; message.AddSubstitution(replacementKey, substitutionValues); //create an instance of the SMTP transport mechanism var transportInstance = new Web(new NetworkCredential(_username, _password)); //enable bypass list management message.EnableBypassListManagement(); //send the mail transportInstance.Deliver(message); }
public void SendGrid_Send_Mail_with_API() { var settings = ConfigurationManager.GetSection("serviceCredentials") as ServiceCredentialsConfigurationSection; if (settings == null) { throw new ConfigurationErrorsException("Missing ServiceCredentials section"); } if (!string.IsNullOrWhiteSpace(settings.TwilioAccountSid) && !string.IsNullOrWhiteSpace(settings.TwilioAuthToken) && !string.IsNullOrWhiteSpace(settings.TwilioFromNumber)) { // Create the email object first, then add the properties. SendGridMessage myMessage = new SendGridMessage(); myMessage.AddTo("*****@*****.**"); myMessage.From = new MailAddress(settings.SendGridFromEmail, settings.SendGridFromName); myMessage.Subject = "SendGrid Testing account setup for startlist.club"; myMessage.Text = "Hello World"; // Create credentials, specifying your user name and password. var credentials = new NetworkCredential(settings.SendGridUserName, settings.SendGridPassword); // Create an Web transport for sending email. var transportWeb = new SendGrid.Web(credentials); // Send the email. transportWeb.Deliver(myMessage); Assert.IsTrue(true); } else { Assert.Fail("Configuration not set"); } }
/// <summary> /// The Spam Checker filter, is useful when your web application allows your end users /// to create content that is then emailed through your SendGridMessage account. /// http://docs.sendgrid.com/documentation/apps/spam-checker-filter/ /// </summary> public void EnableSpamCheckEmail() { //create a new message object var message = new SendGridMessage(); //set the message recipients foreach (var 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 Web transport mechanism var transportInstance = new Web(new NetworkCredential(_username, _password)); //enable spamcheck message.EnableSpamCheck(); //send the mail transportInstance.Deliver(message); }
/// <summary> /// Enable the Open Tracking to track when emails are opened. /// http://docs.sendgrid.com/documentation/apps/open-tracking/ /// </summary> public void EnableOpenTrackingEmail() { //create a new message object var message = new SendGridMessage(); //set the message recipients foreach (var 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 Plain Text</p>"; //set the message subject message.Subject = "Hello World Open Tracking Test"; //create an instance of the Web transport mechanism var transportInstance = new Web(new NetworkCredential(_username, _password)); //enable gravatar message.EnableOpenTracking(); //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 = new SendGridMessage(); //set the message recipients foreach (var 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 Web transport mechanism var transportInstance = new Web(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 adds key value identifiers to be sent back as arguments over the event api for /// various events /// </summary> public void AddUniqueIdentifiers() { //create a new message object var message = new SendGridMessage(); //set the message recipients foreach (var 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 Unique Identifiers"; var identifiers = new Dictionary<String, String>(); identifiers["customer"] = "someone"; identifiers["location"] = "somewhere"; message.AddUniqueArgs(identifiers); //create an instance of the SMTP transport mechanism var transportInstance = new Web(new NetworkCredential(_username, _password)); //enable bypass list management message.EnableBypassListManagement(); //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 SendGridMessage account page. /// </summary> public void SetCategory() { //create a new message object var message = new SendGridMessage(); //set the message recipients foreach (var 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 = new Web(new NetworkCredential(_username, _password)); //enable bypass list management message.EnableBypassListManagement(); //send the mail transportInstance.Deliver(message); }
public static void SendEmail(List<String> recipients,string message) { var state = ConfigurationManager.AppSettings["SiteState"]; if (state == "inhouse") { var Message = new System.Net.Mail.MailMessage(); foreach (var item in recipients) { Message.To.Add(item); } Message.Subject = ConfigurationManager.AppSettings["EmailGeneralSubject"]; Message.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["EmailSender"]); Message.Body = message; var smtp = new System.Net.Mail.SmtpClient(); smtp.Send(Message); } else { // Create the email object first, then add the properties. var myMessage = new SendGridMessage(); // Add the message properties. myMessage.From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"]); foreach (var item in recipients) { myMessage.AddTo(item); } myMessage.Subject = ConfigurationManager.AppSettings["EmailGeneralSubject"]; //Add the HTML and Text bodies myMessage.Html = message; //myMessage.Text = "Hello World plain text!"; var credentials = new NetworkCredential(ConfigurationManager.AppSettings["SG_user"], ConfigurationManager.AppSettings["SG_password"]); // Create an Web transport for sending email. var transportWeb = new Web(credentials); // Send the email. // You can also use the **DeliverAsync** method, which returns an awaitable task. transportWeb.Deliver(myMessage); } }
/// <summary> /// This function will send the email via SendGrid. /// </summary> /// <param name="kMessage">MailMessage - Message object to send</param> protected void SendSendGridEmail(MailMessage kMessage) { try { StringBuilder sb = new StringBuilder(); sb.Append("Date:"); sb.AppendLine(); sb.Append(DateTime.Now.ToString()); sb.AppendLine(); // Create the email object first, then add the properties. var sgMessage = new SendGridMessage(); // Add the message properties. sgMessage.From = new MailAddress(kMessage.From.ToString()); sb.Append("From:"); sb.AppendLine(); sb.Append(sgMessage.From.Address); sb.AppendLine(); // Add multiple addresses to the To field. sb.Append("To:"); sb.AppendLine(); foreach (MailAddress address in kMessage.To) { sgMessage.AddTo(address.Address); sb.Append(address.Address + ";"); } sb.AppendLine(); sgMessage.Subject = kMessage.Subject; sb.Append("Subject:"); sb.AppendLine(); sb.Append(sgMessage.Subject); sb.AppendLine(); // HTML & plain-text if (kMessage.AlternateViews.Count > 0) { foreach (AlternateView view in kMessage.AlternateViews) { // Position must be reset first if (view.ContentStream.CanSeek) { view.ContentStream.Position = 0; } using (StreamWrapper wrappedStream = StreamWrapper.New(view.ContentStream)) { using (StreamReader reader = StreamReader.New(wrappedStream)) { if (view.ContentType.MediaType == MediaTypeNames.Text.Html) { sgMessage.Html = reader.ReadToEnd(); } else if (view.ContentType.MediaType == MediaTypeNames.Text.Plain) { sgMessage.Text = reader.ReadToEnd(); } } } } } sb.Append("Body:"); if (ValidationHelper.GetString(sgMessage.Html, "") != "") { sb.Append(sgMessage.Html); } else { sb.Append(sgMessage.Text); } sb.AppendLine(); //Handle any attachments sb.Append("Attachments:"); sb.AppendLine(); foreach (Attachment attachment in kMessage.Attachments) { sgMessage.AddAttachment(attachment.ContentStream, attachment.Name); sb.Append(attachment.Name); sb.AppendLine(); } //Enable click tracking sgMessage.EnableClickTracking(true); // Create credentials, specifying your user name and password. var credentials = new NetworkCredential("[SendGridLogin]", "[SendGridPassword]"); // Create an Web transport for sending email. var transportWeb = new Web(credentials); // Send the email. transportWeb.Deliver(sgMessage); //Log the email details to the Event Log EventLogProvider.LogInformation("SendSendGridEmail", "EMAIL SENT", ValidationHelper.GetString(sb, "")); } catch (Exception ex) { EventLogProvider.LogException("SendSendGridEmail", "EXCEPTION", ex); } }
public HttpResponseMessage RoadZenResetPassword(LoginRequest passwordRequest) { Services.Log.Info("RoadZen Password Reset Request from Phone# [" + passwordRequest.Phone + "]"); stranddContext context = new stranddContext(); Account useraccount = context.Accounts.Where(a => a.Phone == passwordRequest.Phone).SingleOrDefault(); if (useraccount != null) { if (useraccount.ProviderUserID.Substring(0, 7) != "RoadZen") { string responseText = "Phone# Registered with Google"; Services.Log.Warn(responseText); return this.Request.CreateResponse(HttpStatusCode.BadRequest, WebConfigurationManager.AppSettings["RZ_MobileClientUserWarningPrefix"] + responseText); } else { //Generate random characters from GUID string newPassword = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 8); //Encrypt new Password byte[] salt = RoadZenSecurityUtils.generateSalt(); useraccount.Salt = salt; useraccount.SaltedAndHashedPassword = RoadZenSecurityUtils.hash(newPassword, salt); Services.Log.Info("Password for Phone# [" + passwordRequest.Phone + "] Reset & Saved"); //Save Encrypted Password context.SaveChanges(); //Prepare SendGrid Mail SendGridMessage resetEmail = new SendGridMessage(); resetEmail.From = SendGridHelper.GetAppFrom(); resetEmail.AddTo(useraccount.Email); resetEmail.Subject = "StrandD Password Reset"; resetEmail.Html = "<h3>New Password</h3><p>"+ newPassword +"</p>"; resetEmail.Text = "New Password: "******"New Password Email Sent to [" + useraccount.Email + "]"; Services.Log.Info(responseText); return this.Request.CreateResponse(HttpStatusCode.OK, responseText); } } else { string responseText = "Phone Number Not Registered"; Services.Log.Warn(responseText); return this.Request.CreateResponse(HttpStatusCode.BadRequest, WebConfigurationManager.AppSettings["RZ_MobileClientUserWarningPrefix"] + responseText); } }
public static void SendIncidentSubmissionAdminEmail(Incident incident, ApiServices Services) { SendGridMessage submissionMessage = new SendGridMessage(); IncidentInfo submisionIncident = new IncidentInfo(incident); submissionMessage.From = SendGridHelper.GetAppFrom(); submissionMessage.AddTo(WebConfigurationManager.AppSettings["RZ_SysAdminEmail"]); submissionMessage.Html = " "; submissionMessage.Text = " "; submissionMessage.Subject = " [" + WebConfigurationManager.AppSettings["MS_MobileServiceName"] + "]"; submissionMessage.EnableTemplateEngine(WebConfigurationManager.AppSettings["RZ_SubmisionTemplateID"]); submissionMessage.AddSubstitution("%timestamp%", new List<string> { submisionIncident.CreatedAt.ToString() }); submissionMessage.AddSubstitution("%incidentguid%", new List<string> { submisionIncident.IncidentGUID }); submissionMessage.AddSubstitution("%vehicledetails%", new List<string> { submisionIncident.IncidentVehicleInfo.RegistrationNumber }); submissionMessage.AddSubstitution("%name%", new List<string> { submisionIncident.IncidentUserInfo.Name }); submissionMessage.AddSubstitution("%phone%", new List<string> { submisionIncident.IncidentUserInfo.Phone }); submissionMessage.AddSubstitution("%email%", new List<string> { submisionIncident.IncidentUserInfo.Email }); submissionMessage.AddSubstitution("%jobdescription%", new List<string> { submisionIncident.JobCode }); submissionMessage.AddSubstitution("%location%", new List<string> { submisionIncident.LocationObj.RGDisplay }); // Create an Web transport for sending email. var transportWeb = new Web(SendGridHelper.GetNetCreds()); // Send the email. try { transportWeb.Deliver(submissionMessage); Services.Log.Info("New Incident Submission Email Sent to [" + submisionIncident.IncidentUserInfo.Email + "]"); } catch (InvalidApiRequestException ex) { for (int i = 0; i < ex.Errors.Length; i++) { Services.Log.Error(ex.Errors[i]); } } }
/// <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. /// http://docs.sendgrid.com/documentation/apps/email-templates/ /// </summary> public void EnableTemplateEmail() { //create a new message object var message = new SendGridMessage(); //set the message recipients foreach (var 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 Template Test"; //create an instance of the Web transport mechanism var transportInstance = new Web(new NetworkCredential(_username, _password)); //enable template message.EnableTemplate("<p>My Email Template <% body %> is awesome!</p>"); //send the mail transportInstance.Deliver(message); }
private void SendMessage(SendGridMessage mailMessage) { var credentials = new NetworkCredential("username", "password"); var transportREST = new Web(credentials); transportREST.Deliver(mailMessage); }
/// <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 = new SendGridMessage(); //set the message recipients foreach (var 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 Web transport mechanism var transportInstance = new Web(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); }
public static void SendEmailViaSendGrid(string to, string from, string subject, string htmlBody, MailType type, string textBody, string[] multipleTo = null) { try { //var message = SendGrid.GenerateInstance(); var message = new SendGridMessage(); if (String.IsNullOrEmpty(to)) message.AddTo(multipleTo); else message.AddTo(to); //if (multipleTo != null) // message.AddTo(multipleTo); //else // message.AddTo(to); message.From = new System.Net.Mail.MailAddress(from); message.Subject = subject; if (type == MailType.TextOnly) message.Text = textBody.Replace(@"\r\n", Environment.NewLine); else if (type == MailType.HtmlOnly) message.Html = htmlBody; else { message.Html = htmlBody; message.Text = textBody; } //Dictionary<string, string> collection = new Dictionary<string, string>(); //collection.Add("header", "header"); //message.Headers = collection; message.EnableOpenTracking(); message.EnableClickTracking(); message.DisableUnsubscribe(); message.DisableFooter(); message.EnableBypassListManagement(); //var transportInstance = SMTP.GenerateInstance(new System.Net.NetworkCredential(SendGridUsername, SendGridPassword), SendGridSmtpHost, SendGridSmtpPort); var transportInstance = new Web(new System.Net.NetworkCredential(SendGridUsername, SendGridPassword)); transportInstance.Deliver(message); if (String.IsNullOrEmpty(to)) Console.WriteLine("SendGrid: Email was sent successfully to " + multipleTo); else Console.WriteLine("SendGrid: Email was sent successfully to " + to); } catch (Exception) { if (String.IsNullOrEmpty(to)) Console.WriteLine("SendGrid: Unable to send email to " + multipleTo); else Console.WriteLine("SendGrid: Unable to send email to " + to); throw; } }
/// <summary> /// Send a simple Plain Text email /// </summary> public void SimplePlaintextEmail() { //create a new message object var message = new SendGridMessage(); //set the message recipients foreach (var 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 Web transport mechanism var transportInstance = new Web(new NetworkCredential(_username, _password)); //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 = new SendGridMessage(); //set the message recipients foreach (var 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 Web transport mechanism var transportInstance = new Web(new NetworkCredential(_username, _password)); //enable clicktracking message.EnableClickTracking(); //send the mail transportInstance.Deliver(message); }
public static void SendIncidentPaymentReceiptEmail(Payment payment, ApiServices Services) { SendGridMessage receiptMessage = new SendGridMessage(); IncidentInfo receiptIncident = new IncidentInfo(payment.IncidentGUID); receiptMessage.From = SendGridHelper.GetAppFrom(); receiptMessage.AddTo(receiptIncident.IncidentUserInfo.Email); receiptMessage.Html = " "; receiptMessage.Text = " "; receiptMessage.Subject = " "; receiptMessage.EnableTemplateEngine(WebConfigurationManager.AppSettings["RZ_ReceiptTemplateID"]); receiptMessage.AddSubstitution("%invoicestub%", new List<string> { receiptIncident.IncidentGUID.Substring(0, 5).ToUpper() }); receiptMessage.AddSubstitution("%name%", new List<string> { receiptIncident.IncidentUserInfo.Name }); receiptMessage.AddSubstitution("%jobdescription%", new List<string> { receiptIncident.JobCode }); receiptMessage.AddSubstitution("%servicefee%", new List<string> { receiptIncident.ServiceFee.ToString() }); receiptMessage.AddSubstitution("%datesubmitted%", new List<string> { DateTime.Now.ToShortDateString() }); receiptMessage.AddSubstitution("%paymentmethod%", new List<string> { receiptIncident.PaymentMethod }); receiptMessage.AddSubstitution("%paymentamount%", new List<string> { receiptIncident.PaymentAmount.ToString() }); // Create an Web transport for sending email. var transportWeb = new Web(SendGridHelper.GetNetCreds()); // Send the email. try { transportWeb.Deliver(receiptMessage); Services.Log.Info("Payment Receipt Email Sent to [" + receiptIncident.IncidentUserInfo.Email + "]"); } catch (InvalidApiRequestException ex) { for (int i = 0; i < ex.Errors.Length; i++) { Services.Log.Error(ex.Errors[i]); } } }
public bool SendMail(string to, string subject, string body) { bool result = false; // Create the email object first, then add the properties. var myMessage = new SendGridMessage(); // Add the message properties. myMessage.From = new MailAddress("*****@*****.**"); // Add multiple addresses to the To field. List<String> recipients = new List<String> { to }; myMessage.AddTo(recipients); myMessage.Subject = subject; //Add the HTML and Text bodies myMessage.Html = body; // Create network credentials to access your SendGrid account. var username = "******"; var pswd = "EMf0tV9PVhAl4a7"; var credentials = new NetworkCredential(username, pswd); // Create an Web transport for sending email. var transportWeb = new Web(credentials); //System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(); //mail.To.Add(to); //mail.Subject = subject; //mail.SubjectEncoding = System.Text.Encoding.UTF8; //mail.Body = body; //mail.BodyEncoding = System.Text.Encoding.UTF8; //mail.IsBodyHtml = true; //mail.Priority = MailPriority.High; //SmtpClient client = new SmtpClient(); //client.EnableSsl = true; //Gmail works on Server Secured Layer try { // Send the email. transportWeb.Deliver(myMessage); result = true; } catch (Exception ex) { this.serviceLog.LogError("MailService::SendMail", ex); throw new Exception("something went wrong while sending email ", ex); } // end try return result; }
public bool Send() { // Create the email object first, then add the properties. var myMessage = new SendGridMessage {From = new MailAddress("*****@*****.**")}; // Add the message properties. // Add multiple addresses to the To field. var recipients = new List<String> { @"W Thomas <*****@*****.**>", @"Will Thomas <*****@*****.**>" }; myMessage.AddTo(recipients); myMessage.Subject = "Testing the SendGrid Library"; //Add the HTML and Text bodies myMessage.Html = "<p>Hello World!</p>"; myMessage.Text = "Hello World plain text!"; // Create an Web transport for sending email. var transportWeb = new Web(_credentials); // Send the email. // You can also use the **DeliverAsync** method, which returns an awaitable task. transportWeb.Deliver(myMessage); return true; }