internal static Mail AddAttachments(Mail message, string[] attachments) { if(attachments != null) { foreach(string file in attachments) { if(!string.IsNullOrWhiteSpace(file)) { if(File.Exists(file)) { using(var stream = new FileStream(file, FileMode.Open)) { using (var reader = new StreamReader(stream)) { string fileName = new FileInfo(file).Name; var attachment = new Attachment { Filename = fileName, Content = reader.ReadToEnd(), Type = MimeMapping.GetMimeMapping(file), Disposition = "attachment", ContentId = fileName }; message.AddAttachment(attachment); } } } } } } return message; }
public static async void SendGridEmailWithAttachment(string recipientEmail, string subject, string message, string filename, byte[] pdf) { logger.LogDebug("Send Grid Mail"); try { var apiKey = ConfigVars.NewInstance.sendgridapi; var client = new SendGridClient(apiKey); var from = new EmailAddress("*****@*****.**", "OneDirect Trex Team"); var lsubject = subject; var to = new EmailAddress(recipientEmail); var plainTextContent = ""; var htmlContent = message; var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent); msg.Subject = subject; SendGrid.Helpers.Mail.Attachment attachment = new SendGrid.Helpers.Mail.Attachment(); var file = Convert.ToBase64String(pdf); msg.AddAttachment(filename, file); var response = await client.SendEmailAsync(msg); } catch (Exception ex) { logger.LogDebug("MAIL-ERROR:" + ex.Message, ex); } }
public override void AgregarAdjunto(byte[] fileBytes, string nombreArchivo) { var _adj = new SendGrid.Helpers.Mail.Attachment { Content = Convert.ToBase64String(fileBytes), Filename = nombreArchivo }; _adjuntos.Add(_adj); }
private void materialFlatButton1_Click_1(object sender, EventArgs e) { try { EmailAttachments emailAttachments = new EmailAttachments(); var attach = emailAttachments.BrowseForFile(); var notAddedList = new List <string>(); if (attach != (null, null)) { foreach (var files in attach.Item1.Zip(attach.Item2, (paths, names) => (paths, names))) { var bytes = File.ReadAllBytes(files.paths); var file = Convert.ToBase64String(bytes); var type = emailAttachments.GetMIMEType(files.paths); if (type == null) { notAddedList.Add(files.names); continue; } SendGrid.Helpers.Mail.Attachment attachment = new SendGrid.Helpers.Mail.Attachment() { Content = file, Filename = files.names, Type = type }; attachmentList.Add(attachment); } if (attachmentList.Count >= 1) { AttachmentsGrid.DataSource = null; AttachmentsGrid.DataSource = attachmentList; AttachmentsGrid.Columns["Content"].Visible = false; AttachmentsGrid.Columns["Type"].Visible = false; AttachmentsGrid.Columns["ContentId"].Visible = false; AttachmentsGrid.Columns["Disposition"].Visible = false; } if (notAddedList.Count >= 1) { string list = null; foreach (var x in notAddedList) { list += x + " "; } var msg = $"Súbor/y {list} nebol pridaný, lebo tento typ súboru nie je možné odoslať emailom. Pre informácie o tom, ktoré " + "súbory nie je možné odoslať otvorte BlockedExtensions.txt"; MessageBox.Show(msg); } AttachmentsGrid.ClearSelection(); } else { return; } }
public async Task SendMailAsync(SendMailParams sendMailParams) { var client = new SendGridClient(_sendGridAPIKey); var from = new EmailAddress(_deliveryAccountEmail, _deliveryAccountDescription); var subject = sendMailParams.Subject; var tos = new List <EmailAddress>(); sendMailParams.SendMailAddresses.ForEach(p => { tos.Add(new EmailAddress(p.Email, p.Name)); }); var plainTextContent = sendMailParams.PlainContentText; var htmlContent = sendMailParams.HTMLContent; var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, plainTextContent, htmlContent); if (sendMailParams.SendMailAttachments.Any()) { msg.Attachments = new List <Attachment>(); //Example attachment sendMailParams.SendMailAttachments.ForEach(sendMailAttachment => { var typeOfAttachment = String.Empty; if (sendMailAttachment.TypeAttachment == TypeAttachment.PDF) { typeOfAttachment = System.Net.Mime.MediaTypeNames.Application.Pdf; } else if (sendMailAttachment.TypeAttachment == TypeAttachment.XML) { typeOfAttachment = System.Net.Mime.MediaTypeNames.Application.Xml; } else if (sendMailAttachment.TypeAttachment == TypeAttachment.TXT) { typeOfAttachment = TXT_TYPE_ATTACHMENT; } var attachment = new SendGrid.Helpers.Mail.Attachment { Content = Convert.ToBase64String(sendMailAttachment.Attachment), Filename = sendMailAttachment.Filename, Type = typeOfAttachment, Disposition = DISPOSITION }; msg.Attachments.Add(attachment); }); } var response = await client.SendEmailAsync(msg); if (response.StatusCode != System.Net.HttpStatusCode.Accepted) { throw new CotorraException(9101, "9101", SENDMAIL_GENERIC_EXCEPTION, null); } }
public static async Task <Boolean> SendMeetingInvite(string title, DateTime startTime, DateTime endTime) { var client = new SendGridClient(ConfigurationManager.AppSettings["sendGridKey"]); try { var msg = new SendGridMessage() { From = new EmailAddress(fromMailId, "JHBot"), Subject = title }; StringBuilder htmlBody = new StringBuilder(); //htmlBody.AppendLine("<br>Hello",<br>"); htmlBody.AppendLine("<br>You have received a meeting invite from JHBot. Please open the attached ICS file to save the meeting to your Outlook calendar<br>"); msg.HtmlContent = htmlBody.ToString(); msg.AddTos(Constants.EMAILS); string CalendarContent = MeetingRequestString("JHBot", Constants.EMAILS.Select(s => s.Email).ToList(), title, title, "Conference room", startTime, endTime); byte[] calendarBytes = Encoding.UTF8.GetBytes(CalendarContent.ToString()); SendGrid.Helpers.Mail.Attachment calendarAttachment = new SendGrid.Helpers.Mail.Attachment(); calendarAttachment.Filename = "invite.ics"; //the Base64 encoded content of the attachment. calendarAttachment.Content = Convert.ToBase64String(calendarBytes); calendarAttachment.Type = "text/calendar"; msg.Attachments = new List <SendGrid.Helpers.Mail.Attachment>() { calendarAttachment }; await client.SendEmailAsync(msg); return(true); } catch (Exception) { throw; } finally { client = null; } }
public async Task SendRoomBookingCalenderInvite(string recipientMail, string recipientName, string roomLocation, DateTime start, DateTime end) { string datetime = start.Day + "/" + start.Month + "/" + start.Year + " " + start.ToString("HH:mm") + ":" + end.ToString("HH:mm"); var templateManager = new TemplateManager(); var html = await templateManager.GetBookingConfirmTemplate(Host); html = html.Replace("{{name}}", recipientName); html = html.Replace("{{date}}", datetime); html = html.Replace("{{room}}", roomLocation); var msg = new SendGridMessage() { From = new EmailAddress("*****@*****.**", "Resideo India Operation"), Subject = "Meeting Room Booking Confirmation", HtmlContent = html }; var recipients = new List <EmailAddress> { new EmailAddress(recipientMail, recipientName) }; msg.AddTos(recipients); string CalendarContent = MeetingRequestString("*****@*****.**", new List <string>() { recipientMail }, "Meeting room booking confirmation", "Meeting Room Booked", roomLocation, start, end); byte[] calendarBytes = Encoding.UTF8.GetBytes(CalendarContent.ToString()); SendGrid.Helpers.Mail.Attachment calendarAttachment = new SendGrid.Helpers.Mail.Attachment(); calendarAttachment.Filename = roomLocation + datetime + ".ics"; //the Base64 encoded content of the attachment. calendarAttachment.Content = Convert.ToBase64String(calendarBytes); calendarAttachment.Type = "text/calendar"; msg.Attachments = new List <SendGrid.Helpers.Mail.Attachment>() { calendarAttachment }; var response = await _sendGridClient.SendEmailAsync(msg); }
private async Task SendGridMail(string to, string name) { string apiKey = System.Web.Configuration.WebConfigurationManager.AppSettings["emailsenderkey"]; var client = new SendGridClient(apiKey); var myMessage = new SendGridMessage(); string img = System.IO.Path.GetFullPath(Server.MapPath("~\\Images\\Header.png")); SendGrid.Helpers.Mail.Attachment attachment = new SendGrid.Helpers.Mail.Attachment(); attachment.Filename = img; string contentid = "Header"; attachment.ContentId = contentid; myMessage.AddTo(to); myMessage.SetFrom(new EmailAddress("*****@*****.**", "Peak Performance")); myMessage.SetSubject("New Peak Performance Workout Available"); //myMessage.AddContent(MimeType.Text, message.Body); myMessage.AddContent(MimeType.Html, "<hmtl><head/><body><div><img src=\"cid:" + contentid + "\"></div><div><h2> Hello " + name + ",</h2><h3> You have a new workout available for view at www.peakperformancedev.azurewebsites.net </h3></div></body></html>"); var response = await client.SendEmailAsync(myMessage); }
public async Task <IActionResult> Post([FromBody] object value) { if (!ModelState.IsValid) { return(BadRequest("Penalty data was invalid")); } var jPenlt = value as JObject; if (jPenlt == null) { return(BadRequest("Penalty data was of the wrong type")); } var penalty = ExtractPenalty(jPenlt); // Save the permit var penaltyId = await _penaltyRepository.AddOrUpdateAsync(penalty); if (penaltyId == ObjectId.Empty) { return(BadRequest("Could not save penalty data")); } penalty.id = penaltyId; // Save the parties foreach (var party in penalty.parties) { var partyId = await _partyRepository.AddOrUpdateAsync(party); if (partyId != ObjectId.Empty) { party.id = partyId; } } var oMem = BuildPenaltyPDF(penalty); var apiKey = _appCodes.SendGridApiKey; dynamic sg = new SendGridAPIClient(apiKey); var from = new Email("*****@*****.**"); var subject = "Test message from " + Constants.CisAbbr; var to = new Email("*****@*****.**"); Email[] cc = { to, new Email("*****@*****.**"), new Email("*****@*****.**"), new Email("*****@*****.**"), new Email("*****@*****.**") }; var doco = new Attachment { Filename = "Penalty.pdf", Type = "application/pdf", Content = Convert.ToBase64String(oMem.ToArray()) }; var failedRecipients = new List <Email>(); foreach (var email in cc) { try { Content content; if (email.Address == to.Address && email.Name == to.Name) { content = new Content("text/html", "<p>Dear Applicant,</p><p>This is the data you submitted via the " + Constants.UnaAbbr + " website.</p><p>Regards</p><p>UNA Support Team</p><pre>" + jPenlt.ToString(Formatting.Indented) + "</pre>"); } else { content = new Content("text/html", "<p>This is the data the applicant submitted via the " + Constants.UnaAbbr + " website.</p><p>Regards</p><p>UNA Support Team</p><pre>" + jPenlt.ToString(Formatting.Indented) + "</pre>"); } var mail = new Mail(from, subject, email, content) { Attachments = new List <Attachment> { doco } }; dynamic response = sg.client.mail.send.post(requestBody: mail.Get()); var respCode = response.StatusCode as HttpStatusCode?; if (!respCode.HasValue) { failedRecipients.Add(email); } switch (respCode.Value) { case HttpStatusCode.Accepted: break; default: failedRecipients.Add(email); break; } } catch (Exception) { failedRecipients.Add(email); } } //if (failedRecipients.Any()) //{ // var errorResult = "There were some issues sending emails to the intended recipients"; // return BadRequest(); // + failedRecipients.Select(f => f.Address)); //} return(Ok(penaltyId)); }
private static async Task KitchenSink() { String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); dynamic sg = new SendGrid.SendGridAPIClient(apiKey, "https://api.sendgrid.com"); Mail mail = new Mail(); Email email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; mail.From = email; mail.Subject = "Hello World from the SendGrid CSharp Library"; Personalization personalization = new Personalization(); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddTo(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddCc(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddCc(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddBcc(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddBcc(email); personalization.Subject = "Thank you for signing up, %name%"; personalization.AddHeader("X-Test", "True"); personalization.AddHeader("X-Mock", "True"); personalization.AddSubstitution("%name%", "Example User"); personalization.AddSubstitution("%city%", "Denver"); personalization.AddCustomArgs("marketing", "false"); personalization.AddCustomArgs("transactional", "true"); personalization.SendAt = 1461775051; mail.AddPersonalization(personalization); personalization = new Personalization(); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddTo(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddCc(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddCc(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddBcc(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddBcc(email); personalization.Subject = "Thank you for signing up, %name%"; personalization.AddHeader("X-Test", "True"); personalization.AddHeader("X-Mock", "True"); personalization.AddSubstitution("%name%", "Example User"); personalization.AddSubstitution("%city%", "Denver"); personalization.AddCustomArgs("marketing", "false"); personalization.AddCustomArgs("transactional", "true"); personalization.SendAt = 1461775051; mail.AddPersonalization(personalization); Content content = new Content(); content.Type = "text/plain"; content.Value = "Textual content"; mail.AddContent(content); content = new Content(); content.Type = "text/html"; content.Value = "<html><body>HTML content</body></html>"; mail.AddContent(content); content = new Content(); content.Type = "text/calendar"; content.Value = "Party Time!!"; mail.AddContent(content); Attachment attachment = new Attachment(); attachment.Content = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12"; attachment.Type = "application/pdf"; attachment.Filename = "balance_001.pdf"; attachment.Disposition = "attachment"; attachment.ContentId = "Balance Sheet"; mail.AddAttachment(attachment); attachment = new Attachment(); attachment.Content = "BwdW"; attachment.Type = "image/png"; attachment.Filename = "banner.png"; attachment.Disposition = "inline"; attachment.ContentId = "Banner"; mail.AddAttachment(attachment); mail.TemplateId = "13b8f94f-bcae-4ec6-b752-70d6cb59f932"; mail.AddHeader("X-Day", "Monday"); mail.AddHeader("X-Month", "January"); mail.AddSection("%section1", "Substitution for Section 1 Tag"); mail.AddSection("%section2", "Substitution for Section 2 Tag"); mail.AddCategory("customer"); mail.AddCategory("vip"); mail.AddCustomArgs("campaign", "welcome"); mail.AddCustomArgs("sequence", "2"); ASM asm = new ASM(); asm.GroupId = 3; List<int> groups_to_display = new List<int>() { 1, 4, 5 }; asm.GroupsToDisplay = groups_to_display; mail.Asm = asm; mail.SendAt = 1461775051; mail.SetIpPoolId = "23"; // This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) // mail.BatchId = "some_batch_id"; MailSettings mailSettings = new MailSettings(); BCCSettings bccSettings = new BCCSettings(); bccSettings.Enable = true; bccSettings.Email = "*****@*****.**"; mailSettings.BccSettings = bccSettings; BypassListManagement bypassListManagement = new BypassListManagement(); bypassListManagement.Enable = true; mailSettings.BypassListManagement = bypassListManagement; FooterSettings footerSettings = new FooterSettings(); footerSettings.Enable = true; footerSettings.Text = "Some Footer Text"; footerSettings.Html = "<bold>Some HTML Here</bold>"; mailSettings.FooterSettings = footerSettings; SandboxMode sandboxMode = new SandboxMode(); sandboxMode.Enable = true; mailSettings.SandboxMode = sandboxMode; SpamCheck spamCheck = new SpamCheck(); spamCheck.Enable = true; spamCheck.Threshold = 1; spamCheck.PostToUrl = "https://gotchya.example.com"; mailSettings.SpamCheck = spamCheck; mail.MailSettings = mailSettings; TrackingSettings trackingSettings = new TrackingSettings(); ClickTracking clickTracking = new ClickTracking(); clickTracking.Enable = true; clickTracking.EnableText = false; trackingSettings.ClickTracking = clickTracking; OpenTracking openTracking = new OpenTracking(); openTracking.Enable = true; openTracking.SubstitutionTag = "Optional tag to replace with the open image in the body of the message"; trackingSettings.OpenTracking = openTracking; SubscriptionTracking subscriptionTracking = new SubscriptionTracking(); subscriptionTracking.Enable = true; subscriptionTracking.Text = "text to insert into the text/plain portion of the message"; subscriptionTracking.Html = "<bold>HTML to insert into the text/html portion of the message</bold>"; subscriptionTracking.SubstitutionTag = "text to insert into the text/plain portion of the message"; trackingSettings.SubscriptionTracking = subscriptionTracking; Ganalytics ganalytics = new Ganalytics(); ganalytics.Enable = true; ganalytics.UtmCampaign = "some campaign"; ganalytics.UtmContent = "some content"; ganalytics.UtmMedium = "some medium"; ganalytics.UtmSource = "some source"; ganalytics.UtmTerm = "some term"; trackingSettings.Ganalytics = ganalytics; mail.TrackingSettings = trackingSettings; email = new Email(); email.Address = "*****@*****.**"; mail.ReplyTo = email; dynamic response = await sg.client.mail.send.post(requestBody: mail.Get()); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.WriteLine(mail.Get()); Console.ReadLine(); }
public void TestKitchenSink() { Mail mail = new Mail(); Email email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; mail.From = email; mail.Subject = "Hello World from the SendGrid CSharp Library"; Personalization personalization = new Personalization(); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddTo(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddCc(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddCc(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddBcc(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddBcc(email); personalization.Subject = "Thank you for signing up, %name%"; personalization.AddHeader("X-Test", "True"); personalization.AddHeader("X-Mock", "True"); personalization.AddSubstitution("%name%", "Example User"); personalization.AddSubstitution("%city%", "Denver"); personalization.AddCustomArgs("marketing", "false"); personalization.AddCustomArgs("transactional", "true"); personalization.SendAt = 1461775051; mail.AddPersonalization(personalization); personalization = new Personalization(); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddTo(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddCc(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddCc(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddBcc(email); email = new Email(); email.Name = "Example User"; email.Address = "*****@*****.**"; personalization.AddBcc(email); personalization.Subject = "Thank you for signing up, %name%"; personalization.AddHeader("X-Test", "True"); personalization.AddHeader("X-Mock", "True"); personalization.AddSubstitution("%name%", "Example User"); personalization.AddSubstitution("%city%", "Denver"); personalization.AddCustomArgs("marketing", "false"); personalization.AddCustomArgs("transactional", "true"); personalization.SendAt = 1461775051; mail.AddPersonalization(personalization); Content content = new Content(); content.Type = "text/plain"; content.Value = "Textual content"; mail.AddContent(content); content = new Content(); content.Type = "text/html"; content.Value = "<html><body>HTML content</body></html>"; mail.AddContent(content); content = new Content(); content.Type = "text/calendar"; content.Value = "Party Time!!"; mail.AddContent(content); Attachment attachment = new Attachment(); attachment.Content = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12"; attachment.Type = "application/pdf"; attachment.Filename = "balance_001.pdf"; attachment.Disposition = "attachment"; attachment.ContentId = "Balance Sheet"; mail.AddAttachment(attachment); attachment = new Attachment(); attachment.Content = "BwdW"; attachment.Type = "image/png"; attachment.Filename = "banner.png"; attachment.Disposition = "inline"; attachment.ContentId = "Banner"; mail.AddAttachment(attachment); mail.TemplateId = "13b8f94f-bcae-4ec6-b752-70d6cb59f932"; mail.AddHeader("X-Day", "Monday"); mail.AddHeader("X-Month", "January"); mail.AddSection("%section1", "Substitution for Section 1 Tag"); mail.AddSection("%section2", "Substitution for Section 2 Tag"); mail.AddCategory("customer"); mail.AddCategory("vip"); mail.AddCustomArgs("campaign", "welcome"); mail.AddCustomArgs("sequence", "2"); ASM asm = new ASM(); asm.GroupId = 3; List<int> groups_to_display = new List<int>() { 1, 4, 5 }; asm.GroupsToDisplay = groups_to_display; mail.Asm = asm; mail.SendAt = 1461775051; mail.SetIpPoolId = "23"; // This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) // mail.BatchId = "some_batch_id"; MailSettings mailSettings = new MailSettings(); BCCSettings bccSettings = new BCCSettings(); bccSettings.Enable = true; bccSettings.Email = "*****@*****.**"; mailSettings.BccSettings = bccSettings; BypassListManagement bypassListManagement = new BypassListManagement(); bypassListManagement.Enable = true; mailSettings.BypassListManagement = bypassListManagement; FooterSettings footerSettings = new FooterSettings(); footerSettings.Enable = true; footerSettings.Text = "Some Footer Text"; footerSettings.Html = "<bold>Some HTML Here</bold>"; mailSettings.FooterSettings = footerSettings; SandboxMode sandboxMode = new SandboxMode(); sandboxMode.Enable = true; mailSettings.SandboxMode = sandboxMode; SpamCheck spamCheck = new SpamCheck(); spamCheck.Enable = true; spamCheck.Threshold = 1; spamCheck.PostToUrl = "https://gotchya.example.com"; mailSettings.SpamCheck = spamCheck; mail.MailSettings = mailSettings; TrackingSettings trackingSettings = new TrackingSettings(); ClickTracking clickTracking = new ClickTracking(); clickTracking.Enable = true; clickTracking.EnableText = false; trackingSettings.ClickTracking = clickTracking; OpenTracking openTracking = new OpenTracking(); openTracking.Enable = true; openTracking.SubstitutionTag = "Optional tag to replace with the open image in the body of the message"; trackingSettings.OpenTracking = openTracking; SubscriptionTracking subscriptionTracking = new SubscriptionTracking(); subscriptionTracking.Enable = true; subscriptionTracking.Text = "text to insert into the text/plain portion of the message"; subscriptionTracking.Html = "<bold>HTML to insert into the text/html portion of the message</bold>"; subscriptionTracking.SubstitutionTag = "text to insert into the text/plain portion of the message"; trackingSettings.SubscriptionTracking = subscriptionTracking; Ganalytics ganalytics = new Ganalytics(); ganalytics.Enable = true; ganalytics.UtmCampaign = "some campaign"; ganalytics.UtmContent = "some content"; ganalytics.UtmMedium = "some medium"; ganalytics.UtmSource = "some source"; ganalytics.UtmTerm = "some term"; trackingSettings.Ganalytics = ganalytics; mail.TrackingSettings = trackingSettings; email = new Email(); email.Address = "*****@*****.**"; mail.ReplyTo = email; String ret = mail.Get(); String final = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(ret), Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Include }); Assert.AreEqual(final, "{\"from\":{\"name\":\"Example User\",\"email\":\"[email protected]\"},\"subject\":\"Hello World from the SendGrid CSharp Library\",\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"[email protected]\"}],\"cc\":[{\"name\":\"Example User\",\"email\":\"[email protected]\"},{\"name\":\"Example User\",\"email\":\"[email protected]\"}],\"bcc\":[{\"name\":\"Example User\",\"email\":\"[email protected]\"},{\"name\":\"Example User\",\"email\":\"[email protected]\"}],\"subject\":\"Thank you for signing up, %name%\",\"headers\":{\"X-Test\":\"True\",\"X-Mock\":\"True\"},\"substitutions\":{\"%name%\":\"Example User\",\"%city%\":\"Denver\"},\"custom_args\":{\"marketing\":\"false\",\"transactional\":\"true\"},\"send_at\":1461775051},{\"to\":[{\"name\":\"Example User\",\"email\":\"[email protected]\"}],\"cc\":[{\"name\":\"Example User\",\"email\":\"[email protected]\"},{\"name\":\"Example User\",\"email\":\"[email protected]\"}],\"bcc\":[{\"name\":\"Example User\",\"email\":\"[email protected]\"},{\"name\":\"Example User\",\"email\":\"[email protected]\"}],\"subject\":\"Thank you for signing up, %name%\",\"headers\":{\"X-Test\":\"True\",\"X-Mock\":\"True\"},\"substitutions\":{\"%name%\":\"Example User\",\"%city%\":\"Denver\"},\"custom_args\":{\"marketing\":\"false\",\"transactional\":\"true\"},\"send_at\":1461775051}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Textual content\"},{\"type\":\"text/html\",\"value\":\"<html><body>HTML content</body></html>\"},{\"type\":\"text/calendar\",\"value\":\"Party Time!!\"}],\"attachments\":[{\"content\":\"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12\",\"type\":\"application/pdf\",\"filename\":\"balance_001.pdf\",\"disposition\":\"attachment\",\"content_id\":\"Balance Sheet\"},{\"content\":\"BwdW\",\"type\":\"image/png\",\"filename\":\"banner.png\",\"disposition\":\"inline\",\"content_id\":\"Banner\"}],\"template_id\":\"13b8f94f-bcae-4ec6-b752-70d6cb59f932\",\"headers\":{\"X-Day\":\"Monday\",\"X-Month\":\"January\"},\"sections\":{\"%section1\":\"Substitution for Section 1 Tag\",\"%section2\":\"Substitution for Section 2 Tag\"},\"categories\":[\"customer\",\"vip\"],\"custom_args\":{\"campaign\":\"welcome\",\"sequence\":\"2\"},\"send_at\":1461775051,\"asm\":{\"group_id\":3,\"groups_to_display\":[1,4,5]},\"ip_pool_name\":\"23\",\"mail_settings\":{\"bcc\":{\"enable\":true,\"email\":\"[email protected]\"},\"bypass_list_management\":{\"enable\":true},\"footer\":{\"enable\":true,\"text\":\"Some Footer Text\",\"html\":\"<bold>Some HTML Here</bold>\"},\"sandbox_mode\":{\"enable\":true},\"spam_check\":{\"enable\":true,\"threshold\":1,\"post_to_url\":\"https://gotchya.example.com\"}},\"tracking_settings\":{\"click_tracking\":{\"enable\":true,\"enable_text\":false},\"open_tracking\":{\"enable\":true,\"substitution_tag\":\"Optional tag to replace with the open image in the body of the message\"},\"subscription_tracking\":{\"enable\":true,\"text\":\"text to insert into the text/plain portion of the message\",\"html\":\"<bold>HTML to insert into the text/html portion of the message</bold>\",\"substitution_tag\":\"text to insert into the text/plain portion of the message\"},\"ganalytics\":{\"enable\":true,\"utm_source\":\"some source\",\"utm_medium\":\"some medium\",\"utm_term\":\"some term\",\"utm_content\":\"some content\",\"utm_campaign\":\"some campaign\"}},\"reply_to\":{\"email\":\"[email protected]\"}}"); }
public async Task <Response> SendEmail(EmailInfo Email) { try { string apikey2 = _appSettings.SendGridAPI.apiKey; string apikey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY"); var client = new SendGridClient(apikey2, _appSettings.SendGridAPI.clientURL); var msg = new SendGridMessage(); msg.SetFrom(new EmailAddress(Email.FromAddress, (!String.IsNullOrEmpty(Email.FromDisplayName)) ? Email.FromDisplayName : null)); msg.AddTo(new EmailAddress(Email.ToAddress)); msg.Subject = Email.Subject; msg.SetTemplateId(_appSettings.SendGridAPI.serviceproviderauthorisationTemplate); var dynamicTemplateData = new MessageCenterTemplate { message_text = Email.Body, reply_link = Email.emailReplyLink, subject = Email.Subject }; msg.SetTemplateData(dynamicTemplateData); if (Email.emailType == "INYT_WelcomeCustomerEmail") { msg.SetTemplateId("d-2c3fef273b5546d5b0166f4184f86b92"); dynamicTemplateData = new MessageCenterTemplate { firstName = Email.FromDisplayFirstName, lastName = Email.FromDisplayLastName, companyName = Email.FromDisplayCompanyName, job_position = Email.FromDisplayJobPosition, message_count = 1, message_text = Email.Body, reply_link = Email.emailReplyLink, subject = Email.Subject }; msg.SetTemplateData(dynamicTemplateData); } //else //{ // msg.SetTemplateId("d-33203bde393c4a1bad54ccb476fab339"); // var dynamicTemplateData = new MessageCenterTemplate // { // message_text = Email.Body, // reply_link = Email.emailReplyLink, // subject = Email.Subject // }; // msg.SetTemplateData(dynamicTemplateData); //} if (!string.IsNullOrEmpty(Email.calendarToAttach)) { var calendarBytes = Encoding.UTF8.GetBytes(Email.calendarToAttach.ToString()); MemoryStream ms = new MemoryStream(calendarBytes); SendGrid.Helpers.Mail.Attachment calendarAttachment = new SendGrid.Helpers.Mail.Attachment(); calendarAttachment.Content = Convert.ToBase64String(calendarBytes); calendarAttachment.Type = "text/calendar"; calendarAttachment.Filename = "calendar.ics"; msg.Attachments = new List <SendGrid.Helpers.Mail.Attachment>() { calendarAttachment }; } var response = await client.SendEmailAsync(msg); return(response); } catch (Exception ex) { throw new Exception(ex.Message); } }
/// <summary> /// Send mail using sendgrid server /// </summary> /// <param name="request">request object</param> /// <returns>true or false</returns> private static bool SendMailUsingSendgrid(EmailSendRequestDTO request) { try { string htmlContent = string.Empty; string plainTextContent = string.Empty; // Set apikey var apiKey = ConfigReader.Read(CommonEnums.ConfigKeys.SendgridApiKey); // Initialize sendgrid client. var client = new SendGridClient(apiKey); // From address var from = new EmailAddress(request.FromAddress, request.FromDisplayName); // Subject var subject = request.Subject; // Send mail to multiple recepients. var recepientList = new List <EmailAddress>(); if (!string.IsNullOrEmpty(request.ToAddresses)) { foreach (var toAddress in request.ToAddresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)) { recepientList.Add(new EmailAddress(toAddress)); } } // If content in html format if (request.IsHtmlFormat) { htmlContent = request.Body; } else { plainTextContent = request.Body; } // Creat object to send mail message. var mailMessage = MailHelper.CreateSingleEmailToMultipleRecipients(from, recepientList, subject, plainTextContent, htmlContent); // add multiple cc. var ccList = new List <EmailAddress>(); if (!string.IsNullOrEmpty(request.CCAddresses)) { foreach (var ccAddress in request.CCAddresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)) { ccList.Add(new EmailAddress(ccAddress)); } } // add multiple bcc. var bccList = new List <EmailAddress>(); if (!string.IsNullOrEmpty(request.BCCAddresses)) { foreach (var bccAddress in request.BCCAddresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)) { bccList.Add(new EmailAddress(bccAddress)); } } // Attachments if (!string.IsNullOrEmpty(request.AttachmentFile)) { foreach (var attachmentFile in request.AttachmentFile.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)) { SendGrid.Helpers.Mail.Attachment messageAttachment = new SendGrid.Helpers.Mail.Attachment(); mailMessage.Attachments.Add(messageAttachment); } } var response = client.SendEmailAsync(mailMessage).Result; return(true); } catch (Exception) { return(false); } }
public async static Task <string> Execute(string apiKey, string subject, string EmailBody, string EmailFrom, string emailto, bool?isBooked = false, SessionBookingData?data = null) { try { apiKey = "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"; var client = new SendGridClient(apiKey); //var from = new EmailAddress("*****@*****.**", "Example User"); //var Subject = "Sending with SendGrid is Fun"; var to = new System.Net.Mail.MailAddress(emailto); //var plainTextContent = "and easy to do anywhere, even with C#"; //var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>"; //var msg = MailHelper.CreateSingleEmail(from, to, Subject, plainTextContent, htmlContent); //var response = client.SendEmailAsync(msg); SendGrid.Helpers.Mail.Attachment attachment = new SendGrid.Helpers.Mail.Attachment(); var file = ""; if (isBooked == true && data != null) { var calendar = new Ical.Net.Calendar(); var vEvent = new CalendarEvent { Class = "PUBLIC", Summary = data.SessionTitle, Created = new CalDateTime(DateTime.Now), Description = data.SessionShotDescription, Start = new CalDateTime(data.SessionDate.Value), //End = new CalDateTime(Convert.ToDateTime(res.EndDate)), Sequence = 0, Uid = data.SessionGuid.ToString(), // Location = res.Location, }; calendar.Events.Add(vEvent); var serializer = new CalendarSerializer(new SerializationContext()); var serializedCalendar = serializer.SerializeToString(calendar); var bytesCalendar = Encoding.UTF8.GetBytes(serializedCalendar); MemoryStream ms = new MemoryStream(bytesCalendar); //attachment = new System.Net.Mail.Attachment(ms, "event.ics", "text/calendar"); file = Convert.ToBase64String(bytesCalendar); } //var apiKey = _configuration.GetSection("SENDGRID_API_KEY").Value; //var client = new SendGridClient(apiKey); var from = new System.Net.Mail.MailAddress("*****@*****.**"); var sendEmail = MailHelper.CreateSingleEmail(new EmailAddress(from.Address), new EmailAddress(to.Address), subject, "", EmailBody); sendEmail.SetSpamCheck(false); if (isBooked == true && data != null) { sendEmail.AddAttachment("session.ics", file, "text/calendar", "attachment"); } var response = await client.SendEmailAsync(sendEmail); return(""); //return response; } catch (Exception ex) { throw; } }
public void AddAttachment(Attachment attachment) { if (Attachments == null) { Attachments = new List<Attachment>(); } Attachments.Add(attachment); }
private async Task <Response> SendEmails(EmailTemplate emailTemplate, int numberOfDays, List <EmailAddress> emailAddresses, User user, DateTime date) { try { EmailClient eClient = new EmailClient(); SendGridClient client = new SendGridClient(eClient.SetEnvironmentVar(user)); List <SendGrid.Helpers.Mail.Attachment> attachmentList = new List <SendGrid.Helpers.Mail.Attachment>(); EmailAttachments emailAttachments = new EmailAttachments(); EmailBody body = new EmailBody() { /// HtmlContent je celkovo obsah emailu, <br/> je nutne pridat kvoli tomu, aby email obsahoval nove riadky. Na konci je priadnie /// emailoveho podpisu. HtmlContent = emailTemplate.EmailContent.Replace("\u00A0", "<br/>") + "<br/> <br/> " + user.Signature.Replace("\u00A0", "<br/>"), Subject = emailTemplate.EmailSubject, To = emailAddresses }; using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { var attachments = con.GetTable <Attachment>().Where(x => x.IdUser == user.Id && x.IdEmailTemplate == emailTemplate.Id); foreach (var files in attachments) { /// Zistovanie, ci subor, ktoreho cestu budeme brat z DB vobec existuje if (File.Exists(files.FilePath)) { var bytes = File.ReadAllBytes(files.FilePath); var file = Convert.ToBase64String(bytes); // Ziskanie typu suboru, aby mohol byt uploadnuty var type = emailAttachments.GetMIMEType(files.FilePath); /// Pridanie prilohy, SendGrid.Helpers.Mail.Attachment attachment = new SendGrid.Helpers.Mail.Attachment() { Content = file, Filename = (string)files.FileName, Type = type }; attachmentList.Add(attachment); } else { continue; } } } /// Vytvorenie emailu pre viacero prijemcov var msg = MailHelper.CreateSingleEmailToMultipleRecipients(MailHelper.StringToEmailAddress(user.Email), body.To, body.Subject, body.HtmlContent, body.HtmlContent); // Dates je premenna, ktora urcuje o kolko dni skor ma byt odoslana sprava var dates = date.AddDays(-numberOfDays); // Prevod z datumu do Unix sekund ( Sendgrid takto akceptuje parameter SendAt var unixDate = new DateTimeOffset(dates.Year, dates.Month, dates.Day, dates.Hour, dates.Minute, dates.Second, TimeSpan.Zero).ToUnixTimeSeconds(); /// Minus jedna hodina kvoli casovemu posunu Web API msg.SetSendAt((int)unixDate - 3600); if (attachmentList.Count >= 1) { // Pridanie priloh do tela emailu msg.AddAttachments(attachmentList); } Logger newLog = new Logger(); newLog.LogEmail(date, body.To, body.Subject, body.HtmlContent, attachmentList); // asynchronne odoslanie poziadavky na web api var result = await client.SendEmailAsync(msg); attachmentList.Clear(); emailAddresses.Clear(); return(result); } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show(ex.ToString()); return(null); } }