/// <summary> /// Downloads all transaction SendGrid Email templates /// Docs: https://github.com/sendgrid/sendgrid-csharp/blob/master/USAGE.md#retrieve-all-transactional-templates /// </summary> /// <param name="loadVersions"></param> /// <returns></returns> private TemplateData GetTemplates(bool loadVersions = true) { Logg("- Getting all templates: ", postpend: pad - 7); var response = sgSrc.RequestAsync(method: SendGridClient.Method.GET, urlPath: "templates?generations=dynamic").GetAwaiter().GetResult(); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception($"Error connecting to remote server: {response.StatusCode}"); } var r = response.Body.ReadAsStringAsync().Result; var templates = JsonConvert.DeserializeObject <TemplateData>(r); Ok(); if (!loadVersions) { return(templates); } // get template markup Log(" - Loading Versions:"); templates.Templates.ForEach(t => LoadContent(t.Versions.FirstOrDefault())); return(templates); }
public List <Models.GenericElement> GetLists(string apiKey) { List <Models.GenericElement> list = new List <Models.GenericElement>(); Models.GenericElement genericElement; try { var headers = new Dictionary <string, string> { { "X-Mock", "200" } }; var sg = new SendGridClient(apiKey, apiHost, headers); var response = sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/lists").GetAwaiter().GetResult(); var deserializeBody = response.DeserializeResponseBody(response.Body); foreach (var item in deserializeBody) { var arrayJson = (JArray)JsonConvert.DeserializeObject(Convert.ToString(item.Value)); foreach (var element in arrayJson.Children()) { var itemProperties = element.Children <JProperty>(); var id = itemProperties.FirstOrDefault(x => x.Name == "id"); var name = itemProperties.FirstOrDefault(x => x.Name == "name"); genericElement = new Models.GenericElement() { Id = id.Value.ToString(), Name = name.Value.ToString() }; list.Add(genericElement); } } } catch (Exception) { } return(list); }
static async Task addToSendgrid(string emailAddress) { // create the request body that is to be sent var data = new RequestBody { list_ids = new string[1] { sendGridListId } , contacts = new Contact[] { new Contact { email = emailAddress }, } }; // convert the object to string var jsonString = JsonConvert.SerializeObject(data); // make the request to client with appropriate method // and body content var response = await client.RequestAsync( method : SendGridClient.Method.PUT, urlPath : "marketing/contacts", requestBody : jsonString ); Console.WriteLine(response.StatusCode); }
public async Task <string> SendEmailAsync(SendGridMail mail) { var response = await _sendGridClient.RequestAsync(BaseClient.Method.POST, mail.ToJson(), null, "mail/send"); return(await response.Body.ReadAsStringAsync()); }
private static async Task <TResponse> GetRequest <TResponse>(SendGridClient client, string urlPath) { var response = await client.RequestAsync(SendGridClient.Method.GET, urlPath : urlPath); var content = await response.Body.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <TResponse>(content)); }
private static async Task CleanUp(TemplatesModel model) { var apiKey = Settings.TargetAccountApiKey; var targetAccountClient = new SendGridClient(apiKey); Console.WriteLine("Cleaning Up"); foreach (var item in model.Templates) { Console.WriteLine($"\nRemoving {item.Name}: {item.Id}"); foreach (var version in item.Versions) { await targetAccountClient.RequestAsync(SendGridClient.Method.DELETE, urlPath : $"templates/{item.Id}/versions/{version.Id}"); } await targetAccountClient.RequestAsync(SendGridClient.Method.DELETE, urlPath : $"templates/{item.Id}"); } Console.WriteLine("\nClean Up Complete"); }
public async Task <string> ValidateBatchId() { var apiKey = "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"; var client = new SendGridClient(apiKey); var batch_id = GenerateBatchId(); var response = await client.RequestAsync(method : SendGridClient.Method.GET, urlPath : "mail/batch/" + batch_id); return(response.Body.ReadAsStringAsync().Result); }
public bool IsValid(string apiKey) { var headers = new Dictionary <string, string> { { "X-Mock", "200" } }; var sg = new SendGridClient(apiKey, apiHost, headers); var response = sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/lists").GetAwaiter().GetResult(); return(response.StatusCode.Equals(HttpStatusCode.OK)); }
public override async Task RunAsync(HttpContext context) { var client = new SendGridClient(Options.ApiKey); var response = await client.RequestAsync( method : SendGridClient.Method.GET, urlPath : "templates?generations=dynamic"); await WriteResponseAsync(context, response); }
/// <summary> /// Semd email /// </summary> /// <param name="subject"></param> /// <param name="toEmail"></param> /// <param name="toName"></param> /// <param name="data"></param> /// <param name="attachments"></param> /// <returns></returns> public async Task <bool> SendEmail( string subject, string toEmail, string toName, IEmail data, IEnumerable <Attachment> attachments ) { if (data == null) { throw new Exception("Please define data for email"); } if (string.IsNullOrEmpty(toEmail)) { logger.LogDebug($"Message {data.TemplateId} not delivered because email is not defined"); return(false); } logger.LogInformation($"Sending {data.TemplateId} email to {toEmail}"); if (!Name2Id.ContainsKey(data.TemplateId)) { System.Console.WriteLine($"Template not found: {data.TemplateId}: {subject} {Newtonsoft.Json.JsonConvert.SerializeObject(data)}"); return(false); } var msg = new SendGridMessage() { TemplateId = Name2Id[data.TemplateId], Personalizations = new List <Personalization>() { new Personalization() { TemplateData = data } } }; msg.AddTo(new EmailAddress(toEmail, toName)); msg.From = new EmailAddress(fromEmail, fromName); if (attachments.Any()) { msg.AddAttachments(attachments); } var serialize = msg.Serialize(); var response = await client.RequestAsync(SendGridClient.Method.POST, requestBody : serialize, urlPath : "mail/send"); if (response.StatusCode == System.Net.HttpStatusCode.Accepted) { return(true); } logger.LogError(await response.Body.ReadAsStringAsync()); logger.LogError(serialize); return(false); }
private HttpStatusCode SendCampaign(string apiKey, string idCampaignSendGrid) { var headers = new Dictionary <string, string> { { "X-Mock", "200" } }; var sg = new SendGridClient(apiKey, apiHost, headers); var response = sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "campaigns/" + idCampaignSendGrid + "/schedules/now").GetAwaiter().GetResult(); var deserializeBody = response.DeserializeResponseBody(response.Body); return(response.StatusCode); }
//General v3 Web API Usage public static async Task <string> Generalv3WebAPIUsage() { var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY"); var client = new SendGridClient(apiKey); var queryParams = @"{'limit': 100}"; var response = await client.RequestAsync(method : SendGridClient.Method.GET, urlPath : "suppression/bounces", queryParams : queryParams); return(response.StatusCode.ToString()); }
/// <summary> /// Creates a new transaction email template on SendGrid /// Docs: https://github.com/sendgrid/sendgrid-csharp/blob/master/USAGE.md#create-a-transactional-template /// </summary> /// <param name="t"></param> private void CreateTemplate(Template t) { if (t == null) { return; } if (sgDst == null) { Log("ERROR: Couldn't establish a connection to the target SendGrid account. Please provide a valid api key and retry."); return; } try { Logg($"- Creating template {t.Name}", 5, pad); var data = JsonConvert.DeserializeObject($"{{ 'name': '{t.Name }', 'generation': 'dynamic' }}").ToString(); var resp = sgDst.RequestAsync(method: SendGridClient.Method.POST, urlPath: "templates", requestBody: data).GetAwaiter().GetResult(); var r = resp.Body.ReadAsStringAsync().Result; var tResp = JsonConvert.DeserializeObject <Template>(r); Ok(); var v = t.Versions.FirstOrDefault(); if (v == null) { return; } Logg($"- Creating version ", 7); v.Template_id = tResp.Id; data = JsonConvert.SerializeObject(v); resp = sgDst.RequestAsync(method: SendGridClient.Method.POST, urlPath: $"templates/{tResp.Id}/versions", requestBody: data).GetAwaiter().GetResult(); r = resp.Body.ReadAsStringAsync().Result; var vResp = JsonConvert.DeserializeObject <Version>(r); Ok(); } catch (Exception e) { Log(e); } }
public override async Task RunAsync(HttpContext context) { var templateId = context.Request.RouteValues["id"] as string; var client = new SendGridClient(Options.ApiKey); var response = await client.RequestAsync( method : SendGridClient.Method.GET, urlPath : $"templates/{templateId}"); await WriteResponseAsync(context, response); }
public static async Task <HttpStatusCode> SendGridAsyncWithTemplate(SendGridEmailData emailData) { var apiKey = PowerDesignProEmailAPIKey; var client = new SendGridClient(apiKey); string data = JsonConvert.SerializeObject(emailData); var json = JsonConvert.DeserializeObject <Object>(data); var response = await client.RequestAsync(SendGridClient.Method.POST, json.ToString(), urlPath : "mail/send"); return(response.StatusCode); }
public async Task <Response> GenerateBatchId() { var apiKey = "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"; var client = new SendGridClient(apiKey); var response = await client.RequestAsync(method : SendGridClient.Method.POST, urlPath : "mail/batch"); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); return(response); }
public static async Task <HttpStatusCode> SendEmailWithSendGrid(EmailType emailType, SendGridEmailModel mailModel) { var client = new SendGridClient(SendGridApiKey); var personlized = new[] { new { Subject = mailModel.Subject, To = new List <Recipient> { new Recipient { Email = mailModel.RecipentEmail, } }, Substitutions = new Dictionary <string, string> { { "%first_name%", mailModel.RecipentName }, { "%owner_name%", mailModel.OwnerName }, { "%body%", mailModel.Body }, { "%button_text%", mailModel.ButtonText }, { "%button_url%", mailModel.ButtonUrl }, { "%subject%", mailModel.Subject }, { "%new_user_name%", mailModel.NewUserName }, { "%new_password%", mailModel.NewPassWord }, { "%address%", mailModel.Address }, { "%job_title%", mailModel.JobTitle }, { "%person_type%", mailModel.PersonType }, { "%tenant_name%", mailModel.TenantName }, { "%date%", mailModel.Date }, } } }.ToList(); var jsonObject = new { from = new Recipient { Email = "*****@*****.**", Name = "Property Community" }, template_id = GetSendGridTemplateId(emailType), personalizations = personlized }; var json = new JavaScriptSerializer().Serialize(jsonObject); var response = await client.RequestAsync(method : SendGridClient.Method.POST, requestBody : json.ToString(), urlPath : "mail/send"); return(response.StatusCode); }
async public Task <bool> SendEmailMessageAsync(EmailMessage message, string templateId) { try { var client = new SendGridClient(_sendGridConfig.SendGridApiKey); var sendGridMsg = new SendGridMessageRequest(); sendGridMsg.Template_id = templateId; sendGridMsg.From = new Recipient { Email = "*****@*****.**", Name = "Bit.Country" }; sendGridMsg.Personalizations = new List <Personalization> { new Personalization { Subject = message.Subject, To = new List <Recipient> { new Recipient { Email = message.Destination, Name = message.FirstName }, }, dynamic_template_data = message.PresetSubstitutions } }; sendGridMsg.Content = new List <Content>() { new Content { Value = ".", Type = "text/html" } }; var jsonString = JsonConvert.SerializeObject(sendGridMsg).ToString(); var response = await client.RequestAsync(method : SendGridClient.Method.POST, requestBody : jsonString, urlPath : "mail/send"); return(response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Accepted); } catch (Exception e) { return(false); } }
public async Task IncludeSubscribedEmailFromWebsite(string email, string firstName, string lastName) { var apiKey = WebSiteNewsLetterSendGridKey; var client = new SendGridClient(apiKey); var body = @" [{ 'email': '{email}', 'first_name': '{firstName}', 'last_name': '{lastName}' }]".Replace("{email}", email).Replace("{firstName}", firstName).Replace("{lastName}", lastName); var json = JsonConvert.DeserializeObject <Object>(body); var response = await client.RequestAsync(SendGridClient.Method.POST, json.ToString(), null, "contactdb/recipients"); }
private async Task SendEmailTemplate <T>(List <Personalization <T> > personalization, string templateId) { var per = new SendgridEmailTemplateSend <T>() { From = new From() { Email = _sendgridAdminEmail, Name = "Test", }, Template_id = templateId, Personalizations = personalization, }; var client = new SendGridClient(_sendgridKey); var response = await client.RequestAsync(SendGridClient.Method.POST, Newtonsoft.Json.JsonConvert.SerializeObject(per), urlPath : "mail/send"); }
/// <summary> /// Constructor /// </summary> public SendGridController( ILogger <SendGridController> logger, IConfiguration configuration ) { if (logger is null) { throw new ArgumentNullException(nameof(logger)); } if (configuration is null) { throw new ArgumentNullException(nameof(configuration)); } try { this.logger = logger; var config = new Model.Settings.SendGridConfiguration(); configuration.GetSection("SendGrid").Bind(config); if (string.IsNullOrEmpty(config.MailerApiKey)) { throw new Exception("Invalid SendGrid configuration"); } client = new SendGridClient(config.MailerApiKey); fromName = config.MailerFromName; fromEmail = config.MailerFromEmail; var response = client.RequestAsync( SendGridClient.Method.GET, urlPath: "/templates", queryParams: "{\"generations\": \"dynamic\"}").Result.Body.ReadAsStringAsync().Result; var list = Newtonsoft.Json.JsonConvert.DeserializeObject <SendgridTemplates>(response); if (list.Templates.Length == 0) { throw new Exception("Email templates are not set up in sendgrid"); } Name2Id = list.Templates.ToDictionary(k => k.Name, k => k.Id); logger.LogInformation($"SendGridController configured {list.Templates.Length}"); } catch (Exception exc) { logger.LogError(exc.Message, exc); } }
/// <summary> /// Given an EmailMessage object, converts it to JSON and sends it via the sendGrid API. /// </summary> /// <param name="emailMsg">A EmailMessage.</param> public async Task <HttpStatusCode> sendEmailViaPostAsync(EmailMessage emailMsg) { var client = new SendGridClient(Constants.EmailApiKey.SEND_GRID_API_KEY); try { var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(emailMsg); var response = await client.RequestAsync(method : SendGridClient.Method.POST, urlPath : "mail/send", requestBody : jsonString); return(response.StatusCode); } catch (Exception ex) { Console.WriteLine(ex.Message); return(HttpStatusCode.BadRequest); } }
// nueva funcionalidad public string SendCampaign(SendGridCampaignRequest request) { string Id = string.Empty; try { var headers = new Dictionary <string, string> { { "X-Mock", "201" } }; var sg = new SendGridClient(request.ApiKey, apiHost, headers); JsonCampaign jsonCampaign = new JsonCampaign() { categories = new List <string>(), custom_unsubscribe_url = "", html_content = "<html><head><title></title></head><body>" + request.Text + "[unsubscribe]</body></html>", list_ids = new List <int>() { Convert.ToInt32(request.ListId) }, plain_content = "", segment_ids = new List <int>(), sender_id = Convert.ToInt32(request.SenderId), subject = request.Subject, suppression_group_id = Convert.ToInt32(request.UnsubscriberGroupId), title = request.Name }; var data = JsonConvert.SerializeObject(jsonCampaign); var response = sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "campaigns", requestBody: data).GetAwaiter().GetResult(); var deserializeBody = response.DeserializeResponseBody(response.Body); if (response.StatusCode.Equals(HttpStatusCode.Created)) { Id = Convert.ToString(deserializeBody["id"]); SendCampaign(request.ApiKey, Id); } } catch (Exception ex) { var messageException = telemetria.MakeMessageException(ex, System.Reflection.MethodBase.GetCurrentMethod().Name); telemetria.Critical(messageException); } return(Id); }
private static async Task <TResponse> PostRequest <TResponse>(SendGridClient client, string urlPath, object request) { string json = null; if (request is string) { json = request as string; } else { json = JsonConvert.SerializeObject(request); } var response = await client.RequestAsync(SendGridClient.Method.POST, urlPath : urlPath, requestBody : json); EnsureSuccessStatusCode(response); var content = await response.Body.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <TResponse>(content)); }
public bool TokenIsValid(string apiKey) { bool result = false; try { var headers = new Dictionary <string, string> { { "X-Mock", "200" } }; var sg = new SendGridClient(apiKey, apiHost, headers); var response = sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/lists").GetAwaiter().GetResult(); result = response.StatusCode.Equals(HttpStatusCode.OK); } catch (Exception e) { var messageException = telemetria.MakeMessageException(e, System.Reflection.MethodBase.GetCurrentMethod().Name); telemetria.Critical(messageException); } return(result); }
public static async Task <HttpStatusCode> SendEmailSendGrid(SendGridEmailModel mailModel) { var client = new SendGridClient(SendGridApiKey); var personlized = new[] { new { Subject = mailModel.Subject, To = new List <Recipient> { new Recipient { Email = mailModel.RecipentEmail, } }, Substitutions = new Dictionary <string, string> { { "%first_name%", mailModel.RecipentName }, { "%owner%", mailModel.OwnerName }, { "%body%", mailModel.Body }, { "%button_text%", mailModel.ButtonText }, { "%button_url%", mailModel.ButtonUrl }, { "%subject%", mailModel.Subject } } } }.ToList(); var jsonObject = new { from = new Recipient { Email = "*****@*****.**", Name = "Property Community" }, template_id = SendGridActivationTemplateId, personalizations = personlized }; var json = new JavaScriptSerializer().Serialize(jsonObject); var response = await client.RequestAsync(method : SendGridClient.Method.POST, requestBody : json.ToString(), urlPath : "mail/send"); return(response.StatusCode); }
public static async Task SendMail(string CompanyID, string MailTo, string Subject, string Body, bool IsBodyHTML) { try { string apiKey = "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"; //string apiKey = "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"; // apiKey = "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"; var client = new SendGridClient(apiKey); string data = @"{ 'personalizations': [ { 'to': [ { 'email': '" + MailTo + @"' } ], 'subject': '" + Subject + @"' } ], 'from': { 'email': '" + BaseMailFrom + @"' }, 'content': [ { 'type': 'text/html', 'value': '" + Body.Replace("'", "##") + @"' } ] }"; Object json = JsonConvert.DeserializeObject <Object>(data); var response = await client.RequestAsync(SendGridClient.Method.POST, json.ToString().Replace("##", "'"), urlPath : "mail/send"); //var response = await client.RequestAsync(SendGridClient.Method.POST,data, urlPath: "mail/send"); } catch (Exception ex) { throw ex; } }
private async Task configSendGridasync(IdentityMessage message) { var apiKey = WebConfigurationManager.AppSettings["SendGridApiKey"]; var client = new SendGridClient(apiKey); var from = new EmailAddress(WebConfigurationManager.AppSettings["SendEmailsFrom"], "SendMe!"); var subject = message.Subject; var to = new EmailAddress(message.Destination, message.Destination); var plainTextContent = message.Body; var htmlContent = "<table><tr>" + "<td style=\"max-height: 200px\">" + "<a href=\"www.google.com\"><img src=\"https://cmeblogspot.files.wordpress.com/2013/11/welcome-email-header-2.png?w=600\"/></a>" + "</td></tr>" + "<tr><td>" + "<p style=\"text-align: center\"> " + message.Body + "</p>" + "</td></tr></table>"; var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent); var response = await client.RequestAsync(method : SendGridClient.Method.POST, requestBody : msg.Serialize(), urlPath : "mail/send"); }
private bool SenderIsValid(string idCampaign) { bool result = false; string sender = string.Empty; string apiKey = string.Empty; try { apiKey = GetSetting("ApiKey", idCampaign); sender = GetSetting("Sender", idCampaign); var headers = new Dictionary <string, string> { { "X-Mock", "200" } }; var sg = new SendGridClient(apiKey, apiHost, headers); var response = sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "senders").GetAwaiter().GetResult(); var deserializeBody = response.Body.ReadAsStringAsync().GetAwaiter().GetResult(); var arrayJson = (JArray)JsonConvert.DeserializeObject(Convert.ToString(deserializeBody)); foreach (var element in arrayJson.Children()) { var itemProperties = element.Children <JProperty>(); var id = itemProperties.FirstOrDefault(x => x.Name == "id"); var nickname = itemProperties.FirstOrDefault(x => x.Name == "nickname"); var verified = itemProperties.FirstOrDefault(x => x.Name == "verified"); JObject verifiedObject = JObject.Parse(verified.Value.ToString()); if (id.Value.ToString() == sender) { result = true; } } } catch (Exception e) { var messageException = telemetria.MakeMessageException(e, System.Reflection.MethodBase.GetCurrentMethod().Name); telemetria.Critical(messageException); } return(result); }
private bool ListIsValid() { bool result = false; string list = string.Empty; string apiKey = string.Empty; try { apiKey = GetSettingFromCosmos("ApiKey"); list = GetSettingFromCosmos("List"); var headers = new Dictionary <string, string> { { "X-Mock", "200" } }; var sg = new SendGridClient(apiKey, apiHost, headers); var response = sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/lists").GetAwaiter().GetResult(); var deserializeBody = response.DeserializeResponseBody(response.Body); foreach (var item in deserializeBody) { var arrayJson = (JArray)JsonConvert.DeserializeObject(Convert.ToString(item.Value)); foreach (var element in arrayJson.Children()) { var itemProperties = element.Children <JProperty>(); var id = itemProperties.FirstOrDefault(x => x.Name == "id"); var name = itemProperties.FirstOrDefault(x => x.Name == "name"); if (id.Value.ToString() == list) { result = true; } } } } catch (Exception e) { var messageException = telemetria.MakeMessageException(e, System.Reflection.MethodBase.GetCurrentMethod().Name); telemetria.Critical(messageException); } return(result); }