Exemplo n.º 1
0
        public async Task SendEmailAsync(Mail mail)
        {
            var sendGridClient = new SendGridClient(_sendGridOptions.APIKey);

            var sendGridMessage = new SendGridMessage();

            sendGridMessage.From = new EmailAddress(mail.From);

            sendGridMessage.AddTos(mail.To.Select(x => new EmailAddress(x)).ToList());

            if (mail.CC != null)
            {
                sendGridMessage.AddCcs(mail.CC.Select(x => new EmailAddress(x)).ToList());
            }

            if (mail.BCC != null)
            {
                sendGridMessage.AddBccs(mail.BCC.Select(x => new EmailAddress(x)).ToList());
            }

            sendGridMessage.Subject = mail.Subject;

            if (mail.IsBodyHTML)
            {
                sendGridMessage.HtmlContent = mail.Body;
            }

            else
            {
                sendGridMessage.PlainTextContent = mail.Body;
            }

            await sendGridClient.SendEmailAsync(sendGridMessage);
        }
Exemplo n.º 2
0
        private static async Task Execute()
        {
            var apiKey = "<api-key>";
            var client = new SendGridClient(apiKey);
            var msg    = new SendGridMessage();

            msg.SetFrom(new EmailAddress("*****@*****.**"));
            msg.AddTo(new EmailAddress("*****@*****.**", "Ashirwad"));

            var cc_emails = new List <EmailAddress>
            {
                new EmailAddress("*****@*****.**", "test 1"),
                new EmailAddress("*****@*****.**", "test 2")
            };

            msg.AddCcs(cc_emails);
            var bcc_emails = new List <EmailAddress> {
                new EmailAddress("*****@*****.**", "test 3"),
                new EmailAddress("*****@*****.**", "test 4")
            };

            msg.AddBccs(bcc_emails);

            msg.SetTemplateId("d-3e97f42b3efc437cb23f754664d41fca");



            var dynamicTemplateData = new ExampleTemplateData
            {
                Subject = "100DaysOfServerlessCode",
            };

            msg.SetTemplateData(dynamicTemplateData);
            var response = await client.SendEmailAsync(msg);
        }
        public static SendGridMessage ToSendGridMessage(this MailMessageDto dto)
        {
            if (dto.Sender != null)
            {
                throw new NotSupportedException("Sender header is not supported by SendGrid.");
            }
            if ((dto.ReplyTo?.Count ?? 0) > 1)
            {
                throw new NotSupportedException("Only one Reply-To header is supported by SendGrid.");
            }

            var msg = new SendGridMessage();

            // Add standard header fields
            msg.From = dto.From.ToEmailAddress();
            if (dto.To.Any())
            {
                msg.AddTos(dto.To.ToEmailAddress());
            }
            if (dto.Cc.Any())
            {
                msg.AddCcs(dto.Cc.ToEmailAddress());
            }
            if (dto.Bcc.Any())
            {
                msg.AddBccs(dto.Bcc.ToEmailAddress());
            }
            msg.ReplyTo = dto.ReplyTo.FirstOrDefault().ToEmailAddress();
            msg.Subject = dto.Subject;

            // Add custom header fields
            foreach (var item in dto.CustomHeaders)
            {
                msg.Headers.Add(item.Key, item.Value);
            }

            // Construct body
            if (!string.IsNullOrWhiteSpace(dto.BodyText))
            {
                msg.PlainTextContent = dto.BodyText;
            }
            if (!string.IsNullOrWhiteSpace(dto.BodyHtml))
            {
                msg.HtmlContent = dto.BodyHtml;
            }

            // Add attachments
            foreach (var item in dto.Attachments)
            {
                // Get stream as byte array
                var data = new byte[item.Stream.Length];
                item.Stream.Read(data, 0, (int)item.Stream.Length);

                // Base64 encode
                var encodedData = Convert.ToBase64String(data, 0, data.Length);
                msg.AddAttachment(item.Name, encodedData, item.MimeType);
            }

            return(msg);
        }
Exemplo n.º 4
0
        public async Task SendEmailAsync(MailMessage message)
        {
            var sendGridMessage = new SendGridMessage
            {
                Subject          = message.Subject,
                From             = new EmailAddress(_globalSettings.Mail.ReplyToEmail, _globalSettings.SiteName),
                HtmlContent      = message.HtmlContent,
                PlainTextContent = message.TextContent
            };

            sendGridMessage.SetClickTracking(true, false);
            sendGridMessage.SetOpenTracking(true, null);
            sendGridMessage.AddTos(message.ToEmails.Select(e => new EmailAddress(e)).ToList());
            if (message.BccEmails?.Any() ?? false)
            {
                sendGridMessage.AddBccs(message.BccEmails.Select(e => new EmailAddress(e)).ToList());
            }

            if (message.MetaData?.ContainsKey("SendGridTemplateId") ?? false)
            {
                sendGridMessage.HtmlContent      = " ";
                sendGridMessage.PlainTextContent = " ";
                sendGridMessage.TemplateId       = message.MetaData["SendGridTemplateId"].ToString();
            }

            if (message.MetaData?.ContainsKey("SendGridSubstitutions") ?? false)
            {
                var subs = message.MetaData["SendGridSubstitutions"] as Dictionary <string, string>;
                sendGridMessage.AddSubstitutions(subs);
            }

            var cats = new List <string> {
                "ByteGarden Server"
            };

            if (!string.IsNullOrWhiteSpace(message.Category))
            {
                cats.Add(message.Category);
            }
            sendGridMessage.AddCategories(cats);

            if (message.MetaData?.ContainsKey("SendGridBypassListManagement") ?? false)
            {
                var bypass = message.MetaData["SendGridBypassListManagement"] as bool?;
                sendGridMessage.SetBypassListManagement(bypass.GetValueOrDefault(false));
            }

            try
            {
                await SendAsync(sendGridMessage, false);
            }
            catch (HttpRequestException)
            {
                await SendAsync(sendGridMessage, true);
            }
            catch (WebException)
            {
                await SendAsync(sendGridMessage, true);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Sends out an email to multiple recipients, with a list of copies and blind copies within a non-blocking context
        /// </summary>
        /// <param name="sender">Sender alias</param>
        /// <param name="recipients">Primary email recipients</param>
        /// <param name="ccs">Copy emails</param>
        /// <param name="bccs">Blind copy emails</param>
        /// <param name="subject">Email subject</param>
        /// <param name="body">Email content</param>
        /// <returns>A callback handle providing access to the status code indicating the result of the operation</returns>
        public async Task <IStatus> SendEmailAsync(string sender, IList <string> recipients, IList <string> ccs, IList <string> bccs, string subject, string body)
        {
            byte[] encryptedCredentials = File.ReadAllBytes(Config.GetValue(ConfigConstants.SEND_GRID_ENCRYPTED));
            byte[] symmKey = KeyStoreService.GetKey(Config.GetValue(ConfigConstants.SYMMETRIC_KEY_INDEX));
            string apiKey  = Encoding.UTF8.GetString(SecurityService.Decrypt(encryptedCredentials, symmKey));

            List <EmailAddress> receivers = (from r in recipients select new EmailAddress(r)).ToList();

            List <EmailAddress> copies = (ccs == null ? new List <EmailAddress>() :
                                          (from c in ccs select new EmailAddress(c)).ToList());
            List <EmailAddress> blindCopies = (bccs == null ? new List <EmailAddress>() :
                                               (from b in bccs select new EmailAddress(b)).ToList());

            EmailAddress senderAddress = new EmailAddress(sender);

            SendGridMessage message = new SendGridMessage();

            message.Subject = subject;
            message.SetFrom(senderAddress);
            message.AddTos(receivers);
            message.AddCcs(copies);
            message.AddBccs(blindCopies);
            message.AddContent(MimeType.Html, body);

            SendGridClient client = new SendGridClient(apiKey);
            await client.SendEmailAsync(message);

            return(new Status()
            {
                IsSuccess = true, StatusMessage = "Sent"
            });
        }
Exemplo n.º 6
0
        private async Task SendEmail(string toemail, List <string> additionalToEmails, List <string> ccEmails, List <string> bccEmails, string body, string plainTextMessage)
        {
            try
            {
                var msg = new SendGridMessage()
                {
                    From             = new EmailAddress(_fromEmail, _fromEmailName),
                    Subject          = _subject,
                    HtmlContent      = body,
                    PlainTextContent = plainTextMessage
                };

                var toEmailsList = additionalToEmails.Select(toEmail => new EmailAddress(toEmail)).ToList();
                toEmailsList.Add(new EmailAddress(toemail));
                msg.AddTos(toEmailsList);

                var ccEmailsList = ccEmails.Select(x => new EmailAddress(x)).ToList();
                msg.AddCcs(ccEmailsList);

                var bccEmailsList = bccEmails.Select(x => new EmailAddress(x)).ToList();
                msg.AddBccs(bccEmailsList);

                var response = await _client.SendEmailAsync(msg);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
            }
        }
Exemplo n.º 7
0
        public async Task <Response> SendMail(string messageBody, string email)
        {
            var client = new SendGridClient(config.SendGridApiKey);
            var msg    = new SendGridMessage();

            msg.SetFrom(new EmailAddress(config.SendGridSender, "Prime 365 Travel Expenses"));

            var recipients = new List <EmailAddress>
            {
                new EmailAddress(email)
            };

            msg.AddTos(recipients);

            var ccn = new List <EmailAddress>
            {
                new EmailAddress(config.SendGridSender)
            };

            msg.AddBccs(ccn);

            msg.SetSubject("Prime 365 Travel Expenses");

            msg.AddContent(MimeType.Html, messageBody);
            var response = await client.SendEmailAsync(msg);

            return(response);
        }
Exemplo n.º 8
0
        public static async Task <(bool success, string errorMsg)> SendEmailAsync(IEnumerable <EmailAddress> recipients, string subject, string content, bool isHtml, bool addBccs = false)
        {
            var client = new SendGridClient(Configuration.ApiKey);

            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress(Configuration.NotificationsEmail, Configuration.NotificationsName));
            msg.AddTos(recipients.ToList());
            if (addBccs)
            {
                var bccList = new List <EmailAddress> {
                    new EmailAddress {
                        Email = Configuration.AdminEmail,
                        Name  = Configuration.AdminName
                    }
                };
                msg.AddBccs(bccList);
            }
            msg.SetSubject(subject);
            //TODO: Check if not isHtml send switch to plain text
            msg.AddContent(MimeType.Html, content);

            var response = await client.SendEmailAsync(msg);

            return(new ValueTuple <bool, string>(response.StatusCode == HttpStatusCode.Accepted, await response.Body.ReadAsStringAsync()));
        }
Exemplo n.º 9
0
        private async Task <Response> Execute(ICollection <string> sendTo, string subject,
                                              string messageBody, ICollection <string> bccTo, ICollection <string> ccTo)
        {
            if (_options.Value.ApiKey == null)
            {
                _logger.LogError($"Attempt to send email while 'appsettings.json' doesn't have 'SendGrid' directive.");
                return(null);
            }

            var mailFrom = new EmailAddress(_options.Value.SenderEmail, _options.Value.SenderName);

            var client = new SendGridClient(_options.Value.ApiKey);

            var mail = new SendGridMessage
            {
                From             = mailFrom,
                Subject          = subject,
                PlainTextContent = messageBody,
                HtmlContent      = messageBody
            };

            mail.AddTos(sendTo.Select(x => new EmailAddress {
                Email = x
            }).ToList());

            if (ccTo != null)
            {
                mail.AddCcs(ccTo.Select(x => new EmailAddress {
                    Email = x
                }).ToList());
            }

            if (bccTo != null)
            {
                mail.AddBccs(bccTo.Select(x => new EmailAddress {
                    Email = x
                }).ToList());
            }

            var result = await client.SendEmailAsync(mail);

            string logString = $@"
                    Sent From: '{mailFrom.Email}'
                    Message Subject: '{subject}'.
                    {(sendTo != null ? "To: " + string.Join(",", sendTo) : String.Empty)}
                    {(ccTo != null ? " CC: " + ccTo : String.Empty)}
                    {(bccTo != null ? " BCC: " + bccTo : String.Empty)}";

            if (result.StatusCode != HttpStatusCode.Accepted)
            {
                _logger.LogError($"Unable to send email. Status code '{result.StatusCode}'. {logString}");
            }
            else if (result.StatusCode == HttpStatusCode.Accepted)
            {
                _logger.LogInformation($"Mail has been submitted. {logString}");
            }

            return(result);
        }
Exemplo n.º 10
0
    /// <summary>
    /// Add Bcc emails recipients
    /// </summary>
    /// <param name="bcc"></param>
    public IEmailRepository Bcc(ICollection <string> bcc)
    {
        if (bcc?.Count > 0)
        {
            Message.AddBccs(bcc.Select(x => new EmailAddress(x)).ToList());
        }

        return(this);
    }
Exemplo n.º 11
0
        public async Task <string> ScheduleAsync(EmailMessage message, CancellationToken cancellationToken)
        {
            using var httpClient = CreateClient();
            var sendGrid = new SendGridClient(httpClient, ClientOptions);
            var m        = new SendGridMessage();

            m.SetFrom(message.From.ToSendGridAddress());
            m.SetSubject(message.Subject);
            if (message.To.Count > 0)
            {
                m.AddTos(message.To.Select(SendGridExtensions.ToSendGridAddress).ToList());
            }
            if (message.Cc.Count > 0)
            {
                m.AddCcs(message.Cc.Select(SendGridExtensions.ToSendGridAddress).ToList());
            }
            if (message.Bcc.Count > 0)
            {
                m.AddBccs(message.Bcc.Select(SendGridExtensions.ToSendGridAddress).ToList());
            }
            foreach (var content in message.Contents)
            {
                m.AddContent(content.MediaType, content.Content);
            }
            foreach (var attachment in message.Attachments)
            {
                m.AddAttachment(attachment.Filename, Convert.ToBase64String(attachment.Data), attachment.MediaType, attachment.Disposition.ToSendGridDisposition(), attachment.ContentId);
            }
            var response = await sendGrid.SendEmailAsync(m, cancellationToken);

            if (response.StatusCode == HttpStatusCode.Accepted)
            {
                return(string.Empty);
            }
            if (response.StatusCode == HttpStatusCode.Created)
            {
                return(string.Empty);
            }
            using var stream = await response.Body.ReadAsStreamAsync();

            var errorResponse = await JsonSerializer.DeserializeAsync <SendGridErrorResponse>(stream);

            if (errorResponse.Errors.Count == 0)
            {
                Logger.LogError("Sending mail has failed without an error.");
                return(string.Empty); // no retry
            }
            foreach (var error in errorResponse.Errors)
            {
                Logger.LogError($"SendGrid delivery error: [{error.Field} {error.ErrorId}] {error.Message}");
            }
            return(string.Empty);
        }
Exemplo n.º 12
0
        public async Task <Response> SendEmail(SendGridRequest sendGridRequest)
        {
            var msg = new SendGridMessage();

            msg.SetFrom(_options.Value.FromEmailAddress, _options.Value.FromAlias);

            msg.AddTos(sendGridRequest.To.ToList());

            if (sendGridRequest.Cc?.Length > 0)
            {
                msg.AddCcs(sendGridRequest.Cc.ToList());
            }

            if (sendGridRequest.Bcc?.Length > 0)
            {
                msg.AddBccs(sendGridRequest.Bcc.ToList());
            }

            if (_options.Value.ReplyToEmailAddress != null)
            {
                msg.ReplyTo = new EmailAddress(_options.Value.ReplyToEmailAddress);
            }

            sendGridRequest.DynamicTemplateData.BaseUrl = _options.Value.BaseUrl;

            var dynamicTemplateDataObject = sendGridRequest.DynamicTemplateData;

            msg.SetTemplateData(dynamicTemplateDataObject);

            switch (sendGridRequest.Template)
            {
            case Enumerations.SendGridTemplateEnum.AddedToTickAddedToTicketTemplate:
                msg.SetTemplateId(_options.Value.AddedToTicketTemplate);
                break;

            case Enumerations.SendGridTemplateEnum.TicketUpdatedTemplate:
                msg.SetTemplateId(_options.Value.TicketUpdatedTemplate);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            try
            {
                return(await _client.SendEmailAsync(msg));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 13
0
        public async Task <Guid> SendEmailAsync(EmailMessage emailMessage)
        {
            var client  = new SendGridClient(_smtpSettings.SendgridApiKey);
            var message = new SendGridMessage();

            message.SetFrom(emailMessage.From.ToSendGridEmailAddress());
            message.AddTos(emailMessage.Tos.Select(x => x.ToSendGridEmailAddress()).ToList());
            if (emailMessage.Ccs.Any())
            {
                message.AddCcs(emailMessage.Ccs.Select(x => x.ToSendGridEmailAddress()).ToList());
            }
            if (emailMessage.Bccs.Any())
            {
                message.AddBccs(emailMessage.Bccs.Select(x => x.ToSendGridEmailAddress()).ToList());
            }

            message.Subject          = emailMessage.Subject;
            message.PlainTextContent = emailMessage.Text;
            message.HtmlContent      = emailMessage.Html;

            if (!emailMessage.Headers.ContainsKey("arragro-id"))
            {
                var arragroId = Guid.NewGuid();
                emailMessage.Headers.Add("arragro-id", arragroId.ToString());
            }

            foreach (var key in emailMessage.Headers.Keys)
            {
                message.AddHeader(key, emailMessage.Headers[key]);
            }

            foreach (var fileName in emailMessage.Attachments.Keys)
            {
                var    emailAttachment = emailMessage.Attachments[fileName];
                var    fileBytes       = emailAttachment.Stream.ToArray();
                string base64Content   = Convert.ToBase64String(fileBytes);
                message.AddAttachment(fileName, base64Content);
            }


            var response = await client.SendEmailAsync(message);

            if (response.StatusCode != System.Net.HttpStatusCode.Accepted)
            {
                var body = await response.Body.ReadAsStringAsync();

                throw new Exception($"SendGrid responded with a {response.StatusCode} and the following message:\r\n\r\n{body}");
            }

            return(Guid.Parse(emailMessage.Headers["arragro-id"]));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Sends asynchronously.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns>
        /// A task returning a boolean indicating
        /// whether or not the send was successful.
        /// </returns>
        public async Task SendAsync(EmailMessage message)
        {
            _logger.LogDebug($"Sending email: {JsonConvert.SerializeObject(message)}");

            var to  = message.To.Split(';', StringSplitOptions.RemoveEmptyEntries);
            var cc  = string.IsNullOrWhiteSpace(message.CC) ? new List <string>() : message.CC.Split(';', StringSplitOptions.RemoveEmptyEntries).Except(to, StringComparer.OrdinalIgnoreCase).ToList();
            var bcc = string.IsNullOrWhiteSpace(message.BCC) ? new List <string>() : message.BCC.Split(';', StringSplitOptions.RemoveEmptyEntries).Except(to, StringComparer.OrdinalIgnoreCase).ToList();

            var sendGridMessage = new SendGridMessage();

            sendGridMessage.SetFrom(string.IsNullOrWhiteSpace(message.From) ? _emailConfiguration.SupportEmail : message.From);
            sendGridMessage.AddTos(to.Select(t => new EmailAddress(t)).ToList());

            if (cc.Count > 0)
            {
                sendGridMessage.AddCcs(cc.Select(t => new EmailAddress(t)).ToList());
            }
            if (bcc.Count > 0)
            {
                sendGridMessage.AddBccs(bcc.Select(t => new EmailAddress(t)).ToList());
            }

            if (message.Attachments != null && message.Attachments.Count > 0)
            {
                sendGridMessage.AddAttachments(message.Attachments.Select(attachment => new Attachment()
                {
                    Filename = attachment.Key, Content = attachment.Value.ToBase64()
                }).ToList());
            }

            if (message is TemplateEmailMessage templateEmailMessage)
            {
                sendGridMessage.SetTemplateId(templateEmailMessage.TemplateId);
                sendGridMessage.SetTemplateData(templateEmailMessage.TemplateData);
            }
            else if (message is HtmlEmailMessage htmlEmailMessage)
            {
                sendGridMessage.SetSubject(htmlEmailMessage.Subject);
                sendGridMessage.AddContent(MimeType.Html, htmlEmailMessage.Body);
            }

            var response = await _sendGridClient.SendEmailAsync(sendGridMessage);

            _logger.LogDebug($"Sendgrid response: {await response.Body?.ReadAsStringAsync()}");

            if (response.StatusCode < HttpStatusCode.OK || response.StatusCode >= HttpStatusCode.Ambiguous)
            {
                throw new PasswordlessException($"Unable to send email : {await response.Body?.ReadAsStringAsync()}");
            }
        }
Exemplo n.º 15
0
        public async Task <bool> SendEmail(string ToEmail, string subject, string bodyHtml, string ccEmail, string bccEmail)
        {
            try
            {
                var message = new SendGridMessage();

                message.SetFrom(new EmailAddress(this._sendGridSettings.Value.SenderEmail, this._sendGridSettings.Value.fromName));
                var lstRecipients = new List <EmailAddress>();
                if (!string.IsNullOrEmpty(ccEmail))
                {
                    var lstCC = ccEmail.Trim(new char[] { ' ', '.', ',' }).Split(',').ToList();
                    foreach (var item in lstCC)
                    {
                        lstRecipients.Add(new EmailAddress()
                        {
                            Email = item
                        });
                    }
                    message.AddCcs(lstRecipients);
                }

                lstRecipients = new List <EmailAddress>();
                if (!string.IsNullOrEmpty(bccEmail))
                {
                    var lstBCC = bccEmail.Trim(new char[] { ' ', '.', ',' }).Split(',').ToList();
                    foreach (var item in lstBCC)
                    {
                        lstRecipients.Add(new EmailAddress()
                        {
                            Email = item
                        });
                    }
                    message.AddBccs(lstRecipients);
                }

                message.SetSubject(subject);
                message.AddTo(new EmailAddress(ToEmail));
                message.HtmlContent = bodyHtml;

                await SendMailDispatch(message);

                return(true);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 16
0
        public async Task SendEmailAsync(MailMessage message)
        {
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress(_replyToEmail, _globalSettings.SiteName));
            msg.AddTos(message.ToEmails.Select(e => new EmailAddress(CoreHelpers.PunyEncode(e))).ToList());
            if (message.BccEmails?.Any() ?? false)
            {
                msg.AddBccs(message.BccEmails.Select(e => new EmailAddress(CoreHelpers.PunyEncode(e))).ToList());
            }

            msg.SetSubject(message.Subject);
            msg.AddContent(MimeType.Text, message.TextContent);
            msg.AddContent(MimeType.Html, message.HtmlContent);

            msg.AddCategory($"type:{message.Category}");
            msg.AddCategory($"env:{_hostingEnvironment.EnvironmentName}");
            msg.AddCategory($"sender:{_senderTag}");

            msg.SetClickTracking(false, false);
            msg.SetOpenTracking(false);

            if (message.MetaData != null &&
                message.MetaData.ContainsKey("SendGridBypassListManagement") &&
                Convert.ToBoolean(message.MetaData["SendGridBypassListManagement"]))
            {
                msg.SetBypassListManagement(true);
            }

            try
            {
                var success = await SendAsync(msg, false);

                if (!success)
                {
                    _logger.LogWarning("Failed to send email. Retrying...");
                    await SendAsync(msg, true);
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "Failed to send email (with exception). Retrying...");
                await SendAsync(msg, true);

                throw;
            }
        }
Exemplo n.º 17
0
        protected override async Task SendEmailInternalAsync(EmailModel emailModel)
        {
            var msg = new SendGridMessage
            {
                From = emailModel.From != null
                ? new EmailAddress(emailModel.From.Email, emailModel.From.Name)
                : new EmailAddress(_config.EmailAddress, _config.Name),
                Subject          = emailModel.Subject,
                HtmlContent      = emailModel.HtmlBody,
                PlainTextContent = emailModel.TextBody // TODO: convert html to plain text?
            };

            msg.AddTos(emailModel.Recipients.Select(a => new EmailAddress(a.Email, a.Name)).ToList());

            if (emailModel.Cc?.Any() == true)
            {
                msg.AddCcs(emailModel.Cc.Select(a => new EmailAddress(a.Email, a.Name)).ToList());
            }

            if (emailModel.Bcc?.Any() == true)
            {
                msg.AddBccs(emailModel.Bcc.Select(a => new EmailAddress(a.Email, a.Name)).ToList());
            }

            if (emailModel.Attachments?.Any() == true)
            {
                msg.AddAttachments(emailModel.Attachments.Select(a => new global::SendGrid.Helpers.Mail.Attachment
                {
                    Filename    = a.Filename,
                    Content     = Convert.ToBase64String(a.Bytes),
                    Type        = a.ContentType,
                    Disposition = a.ContentDisposition,
                    ContentId   = a.ContentId
                }));
            }

            var client   = new SendGridClient(_config.Key);
            var response = await client.SendEmailAsync(msg);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                var responseBody = await response.Body.ReadAsStringAsync();

                throw new EmailSenderException($"SendGrid returned {response.StatusCode} status code ({responseBody})");
            }
        }
Exemplo n.º 18
0
        //public async Task<Response> SendEmail(Email email)
        //{
        //    try
        //    {
        //        var client = new SendGridClient(_sendGridApiKey);   
        //        var msg = MailHelper.CreateSingleEmail(
        //            email.From, email.To, email.Subject, email.PlainTextContent, email.HtmlContent);
        //        var response = await client.SendEmailAsync(msg);
        //        return response;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw;
        //    }
        //}

        public async Task<Response> SendTestEmail(List<string> recipients, List<string> Bcclist, List<string> Cclist, string subject, string bodyHtml, string sender)
        {
            try
            {
                var client = new SendGridClient(_sendGridApiKey);
                var from = MailHelper.StringToEmailAddress(sender);
                var msg = new SendGridMessage();
                var tos = recipients.Select(x => MailHelper.StringToEmailAddress(x)).ToList();
                msg.SetFrom(from);
                msg.SetGlobalSubject(subject);
                //use htmlcontent only if you are sending only HTML
                if (!string.IsNullOrEmpty(bodyHtml))
                {
                    msg.AddContent(MimeType.Html, bodyHtml);
                }

                //The AddTos method below accepts List<EmailAddress> to add multiple recipients with Personalization

                msg.AddTos(tos);
                if (Cclist != null)
                {
                    if (Cclist.Count > 0)
                    {
                        var Ccs = Cclist.Select(x => MailHelper.StringToEmailAddress(x)).ToList();
                        msg.AddCcs(Ccs);
                    }
                }
                if (Bcclist != null)
                {
                    if (Bcclist.Count > 0)
                    {
                        var Bccs = Bcclist.Select(x => MailHelper.StringToEmailAddress(x)).ToList();
                        msg.AddBccs(Bccs);
                    }
                }

                return await client.SendEmailAsync(msg);
            }
            catch (Exception ex)
            {
                throw;
            }
            
        }
        public async Task <ResponseMessage> SendAsync(EmailMessage message)
        {
            // Message
            var msg = new SendGridMessage();

            msg.Subject          = message.Subject;
            msg.From             = new EmailAddress(message.From);
            msg.PlainTextContent = message.Body;
            msg.AddTos(message.To.Select(s => new EmailAddress(s)).ToList());

            if (message.CC.Count > 0)
            {
                msg.AddCcs(message.CC.Select(s => new EmailAddress(s)).ToList());
            }

            if (message.BCC.Count > 0)
            {
                msg.AddBccs(message.BCC.Select(s => new EmailAddress(s)).ToList());
            }

            if (message.Attachments != null && message.Attachments.Any())
            {
                foreach (var attachment in message.Attachments.Where(x => x != null && x.Length > 0))
                {
                    using (var ms = new MemoryStream())
                    {
                        attachment.CopyTo(ms);
                        var fileBytes = ms.ToArray();
                        msg.AddAttachment(new Attachment
                        {
                            Filename = attachment.FileName,
                            Content  = Convert.ToBase64String(fileBytes)
                        });
                    }
                }
            }

            // Send
            var client   = new SendGridClient(this.settings.ApiKey);
            var response = await client.SendEmailAsync(msg);

            // Return
            return(new ResponseMessage(response.StatusCode.ToString()));
        }
Exemplo n.º 20
0
        public Task SendAsync(MailMessageDTO message)
        {
            var web = new SendGridClient(apiKey);

            var msg = new SendGridMessage()
            {
                From    = ConvertMailAddress(message.From),
                ReplyTo = message.ReplyTo.Select(ConvertMailAddress).FirstOrDefault(),
                Subject = message.Subject
            };

            msg.AddTos(message.To.Select(ConvertMailAddress).ToList());

            if (message.Cc.Count > 0)
            {
                msg.AddCcs(message.Cc.Select(ConvertMailAddress).ToList());
            }

            if (message.Bcc.Count > 0)
            {
                msg.AddBccs(message.Bcc.Select(ConvertMailAddress).ToList());
            }

            if (message.Attachments.Count > 0)
            {
                msg.AddAttachments(message.Attachments.Select(ConvertAttachment).ToList());
            }

            if (string.IsNullOrWhiteSpace(message.BodyHtml))
            {
                msg.PlainTextContent = message.BodyText;
            }
            else
            {
                msg.HtmlContent = message.BodyHtml;
            }

            ProcessTemplate(msg, message.MailingTemplate);

            OnMessageSending(msg);
            return(web.SendEmailAsync(msg));
        }
Exemplo n.º 21
0
        private SendGridMessage Message(IEmailContent email)
        {
            SendGridMessage msg = MailHelper.CreateSingleEmailToMultipleRecipients(
                @from: new EmailAddress(email.From),
                tos: email.Recipients.Select(x => new EmailAddress(x)).ToList(),
                subject: email.Subject,
                plainTextContent: string.Empty,
                htmlContent: email.Body);

            if (email.Cc.Any())
            {
                msg.AddCcs(email.Cc.Select(x => new EmailAddress(x)).ToList());
            }

            if (email.HiddenCc.Any())
            {
                msg.AddBccs(email.HiddenCc.Select(x => new EmailAddress(x)).ToList());
            }

            return(msg);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            [SendGrid(ApiKey = "SendGridAPIKey")] IAsyncCollector <SendGridMessage> messageCollector
            )
        {
            string        requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            List <Emails> emails      = JsonConvert.DeserializeObject <List <Emails> >(requestBody);

            foreach (var email in emails)
            {
                var emailSubscribers = email.EmailTo.Select(x => new EmailAddress(x)).ToList();
                var message          = new SendGridMessage();
                message.AddTo(email.EmailFrom, email.Name);
                message.AddBccs(emailSubscribers);
                message.SetFrom(email.EmailFrom, email.Name);
                message.AddContent("text/html", email.EmailBody);
                message.SetSubject(email.EmailSubject);
                await messageCollector.AddAsync(message);
            }
            return(new OkObjectResult("OK"));
        }
Exemplo n.º 23
0
        private SendGridMessage Map(EmailMessage message)
        {
            var msg = new SendGridMessage();

            msg.SetFrom(new SendGridEmailAddress(message.From.Address, message.From.DisplayName));
            msg.AddTos(message.Tos.Select(x => new SendGridEmailAddress(x)).ToList());
            if (message.Ccs != null && message.Ccs.Any())
            {
                msg.AddCcs(message.Ccs.Select(x => new SendGridEmailAddress(x)).ToList());
            }

            if (message.Bccs != null && message.Ccs.Any())
            {
                msg.AddBccs(message.Bccs.Select(x => new SendGridEmailAddress(x)).ToList());
            }

            msg.SetSubject(message.Subject);
            msg.HtmlContent = message.Body;

            return(msg);
        }
        public async Task <ResponseMessage> SendAsync(EmailMessage message)
        {
            // Message
            var msg = new SendGridMessage();

            msg.Subject          = message.Subject;
            msg.From             = new EmailAddress(message.From);
            msg.PlainTextContent = message.Body;
            msg.AddTos(message.To.Select(s => new EmailAddress(s)).ToList());

            if (message.CC.Count > 0)
            {
                msg.AddCcs(message.CC.Select(s => new EmailAddress(s)).ToList());
            }

            if (message.BCC.Count > 0)
            {
                msg.AddBccs(message.BCC.Select(s => new EmailAddress(s)).ToList());
            }

            if (message.Attachments.Count > 0)
            {
                msg.AddAttachments(message.Attachments.Select(s => new Attachment
                {
                    Filename = s,
                    Content  = Convert.ToBase64String(System.IO.File.ReadAllBytes(s))
                }).ToList());
            }

            // Send
            var client   = new SendGridClient(this.settings.ApiKey);
            var response = await client.SendEmailAsync(msg);

            // Return
            return(new ResponseMessage(response.StatusCode.ToString()));
        }
Exemplo n.º 25
0
        public async Task <SendResponse> SendAsync(IFluentEmail email, CancellationToken?token = null)
        {
            var sendGridClient = new SendGridClient(_apiKey);

            var mailMessage = new SendGridMessage();

            mailMessage.SetSandBoxMode(_sandBoxMode);

            mailMessage.SetFrom(ConvertAddress(email.Data.FromAddress));

            if (email.Data.ToAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddTos(email.Data.ToAddresses.Select(ConvertAddress).ToList());
            }

            if (email.Data.CcAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddCcs(email.Data.CcAddresses.Select(ConvertAddress).ToList());
            }

            if (email.Data.BccAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddBccs(email.Data.BccAddresses.Select(ConvertAddress).ToList());
            }

            mailMessage.SetSubject(email.Data.Subject);

            if (email.Data.IsHtml)
            {
                mailMessage.HtmlContent = email.Data.Body;
            }
            else
            {
                mailMessage.PlainTextContent = email.Data.Body;
            }

            if (!string.IsNullOrEmpty(email.Data.PlaintextAlternativeBody))
            {
                mailMessage.PlainTextContent = email.Data.PlaintextAlternativeBody;
            }

            if (email.Data.Attachments.Any())
            {
                foreach (var attachment in email.Data.Attachments)
                {
                    var sendGridAttachment = await ConvertAttachment(attachment);

                    mailMessage.AddAttachment(sendGridAttachment.Filename, sendGridAttachment.Content,
                                              sendGridAttachment.Type, sendGridAttachment.Disposition, sendGridAttachment.ContentId);
                }
            }

            var sendGridResponse = await sendGridClient.SendEmailAsync(mailMessage, token.GetValueOrDefault());

            var sendResponse = new SendResponse();

            if (IsHttpSuccess((int)sendGridResponse.StatusCode))
            {
                return(sendResponse);
            }

            sendResponse.ErrorMessages.Add($"{sendGridResponse.StatusCode}");
            var messageBodyDictionary = await sendGridResponse.DeserializeResponseBodyAsync(sendGridResponse.Body);

            if (messageBodyDictionary.ContainsKey("errors"))
            {
                var errors = messageBodyDictionary["errors"];

                foreach (var error in errors)
                {
                    sendResponse.ErrorMessages.Add($"{error}");
                }
            }

            return(sendResponse);
        }
Exemplo n.º 26
0
        private SendGridMessage GetSendGridMessageFromRockEmailMessage(RockEmailMessage rockEmailMessage)
        {
            var sendGridMessage = new SendGridMessage();

            // To
            rockEmailMessage.GetRecipients().ForEach(r => sendGridMessage.AddTo(r.To, r.Name));

            if (rockEmailMessage.ReplyToEmail.IsNotNullOrWhiteSpace())
            {
                sendGridMessage.ReplyTo = new EmailAddress(rockEmailMessage.ReplyToEmail);
            }

            sendGridMessage.From = new EmailAddress(rockEmailMessage.FromEmail, rockEmailMessage.FromName);

            // CC
            var ccEmailAddresses = rockEmailMessage
                                   .CCEmails
                                   .Where(e => e != string.Empty)
                                   .Select(cc => new EmailAddress {
                Email = cc
            })
                                   .ToList();

            if (ccEmailAddresses.Count > 0)
            {
                sendGridMessage.AddCcs(ccEmailAddresses);
            }

            // BCC
            var bccEmailAddresses = rockEmailMessage
                                    .BCCEmails
                                    .Where(e => e != string.Empty)
                                    .Select(cc => new EmailAddress {
                Email = cc
            })
                                    .ToList();

            if (bccEmailAddresses.Count > 0)
            {
                sendGridMessage.AddBccs(bccEmailAddresses);
            }

            // Subject
            sendGridMessage.Subject = rockEmailMessage.Subject;

            // Body (plain text)
            sendGridMessage.PlainTextContent = rockEmailMessage.PlainTextMessage;

            // Body (html)
            sendGridMessage.HtmlContent = rockEmailMessage.Message;

            // Communication record for tracking opens & clicks
            sendGridMessage.CustomArgs = rockEmailMessage.MessageMetaData;

            if (CanTrackOpens)
            {
                sendGridMessage.TrackingSettings = new TrackingSettings
                {
                    ClickTracking = new ClickTracking {
                        Enable = true
                    },
                    OpenTracking = new OpenTracking {
                        Enable = true
                    }
                };
            }

            // Attachments
            if (rockEmailMessage.Attachments.Any())
            {
                foreach (var attachment in rockEmailMessage.Attachments)
                {
                    if (attachment != null)
                    {
                        MemoryStream ms = new MemoryStream();
                        attachment.ContentStream.CopyTo(ms);
                        sendGridMessage.AddAttachment(attachment.FileName, Convert.ToBase64String(ms.ToArray()));
                    }
                }
            }

            return(sendGridMessage);
        }
Exemplo n.º 27
0
        private async Task <SendGridMessage> BuildSendGridMessage(IFluentEmail email)
        {
            var mailMessage = new SendGridMessage();

            mailMessage.SetSandBoxMode(_sandBoxMode);

            mailMessage.SetFrom(ConvertAddress(email.Data.FromAddress));

            if (email.Data.ToAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddTos(email.Data.ToAddresses.Select(ConvertAddress).ToList());
            }

            if (email.Data.CcAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddCcs(email.Data.CcAddresses.Select(ConvertAddress).ToList());
            }

            if (email.Data.BccAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddBccs(email.Data.BccAddresses.Select(ConvertAddress).ToList());
            }

            if (email.Data.ReplyToAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                // SendGrid does not support multiple ReplyTo addresses
                mailMessage.SetReplyTo(email.Data.ReplyToAddresses.Select(ConvertAddress).First());
            }

            mailMessage.SetSubject(email.Data.Subject);

            if (email.Data.Headers.Any())
            {
                mailMessage.AddHeaders(email.Data.Headers.ToDictionary(kvp => kvp.Key, kvp => kvp.Value));
            }

            if (email.Data.Tags != null && email.Data.Tags.Any())
            {
                mailMessage.Categories = email.Data.Tags.ToList();
            }

            if (email.Data.IsHtml)
            {
                mailMessage.HtmlContent = email.Data.Body;
            }
            else
            {
                mailMessage.PlainTextContent = email.Data.Body;
            }

            switch (email.Data.Priority)
            {
            case Priority.High:
                // https://stackoverflow.com/questions/23230250/set-email-priority-with-sendgrid-api
                mailMessage.AddHeader("Priority", "Urgent");
                mailMessage.AddHeader("Importance", "High");
                // https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmail/2bb19f1b-b35e-4966-b1cb-1afd044e83ab
                mailMessage.AddHeader("X-Priority", "1");
                mailMessage.AddHeader("X-MSMail-Priority", "High");
                break;

            case Priority.Normal:
                // Do not set anything.
                // Leave default values. It means Normal Priority.
                break;

            case Priority.Low:
                // https://stackoverflow.com/questions/23230250/set-email-priority-with-sendgrid-api
                mailMessage.AddHeader("Priority", "Non-Urgent");
                mailMessage.AddHeader("Importance", "Low");
                // https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmail/2bb19f1b-b35e-4966-b1cb-1afd044e83ab
                mailMessage.AddHeader("X-Priority", "5");
                mailMessage.AddHeader("X-MSMail-Priority", "Low");
                break;
            }

            if (email.Data.Attachments.Any())
            {
                foreach (var attachment in email.Data.Attachments)
                {
                    var sendGridAttachment = await ConvertAttachment(attachment);

                    mailMessage.AddAttachment(sendGridAttachment.Filename, sendGridAttachment.Content,
                                              sendGridAttachment.Type, sendGridAttachment.Disposition, sendGridAttachment.ContentId);
                }
            }

            return(mailMessage);
        }
Exemplo n.º 28
0
        private async Task <Response> Send(SendGridMessage message, Models.Patrol patrol, params User[] to)
        {
            SendGridClient client = new SendGridClient(new SendGridClientOptions()
            {
                ApiKey = _apiKey
            });

            message.From = new EmailAddress(_fromEmail, patrol != null ? patrol.Name + " @ " + _fromName : _fromName);

            //remove anybody that doesn't want notifications,dedup the to list
            to = to.Where(x => x.AllowEmailNotifications).GroupBy(x => x.Email).Select(x => x.First()).ToArray();

            bool hasTo = false;

            if (!string.IsNullOrEmpty(_overrideTo))
            {
                if (to.Any(x => x.AllowEmailNotifications))
                {
                    if (_overrideTo != "nobody")
                    {
                        message.AddTo(new EmailAddress(_overrideTo, "Test User"));
                        hasTo = true;
                    }
                }
            }
            else
            {
                var filteredTo = new List <EmailAddress>();
                foreach (var email in to)
                {
                    if (email.Email.Contains("@"))
                    {
                        var domain = email.Email.Substring(email.Email.IndexOf("@") + 1);
                        if (!_urlRoot.Contains(domain))
                        {
                            filteredTo.Add(email.ToEmailAddress());
                        }
                    }
                }

                if (filteredTo.Count > 0)
                {
                    hasTo = true;
                    //remove any that have the same host as this app, since these are test users
                    if (filteredTo.Count > 1)
                    {
                        message.AddBccs(filteredTo.ToList());
                    }
                    else
                    {
                        message.AddTos(filteredTo.ToList());
                    }
                }
            }

            if (hasTo)
            {
                AttachEmbeddedImages(message);

                var response = await client.SendEmailAsync(message);

                if (response.StatusCode != System.Net.HttpStatusCode.Accepted)
                {
                    throw new SendGridEmailException()
                          {
                              Body       = await response.Body.ReadAsStringAsync(),
                              StatusCode = response.StatusCode
                          };
                }

                return(response);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 29
0
        public async Task <TResult> SendEmailMessageAsync <TResult>(
            string templateName,
            string toAddress, string toName,
            string fromAddress, string fromName,
            string subject,
            IDictionary <string, string> substitutionsSingle,
            IDictionary <string, IDictionary <string, string>[]> substitutionsMultiple,
            Func <string, TResult> onSuccess,
            Func <TResult> onServiceUnavailable,
            Func <string, TResult> onFailure)
        {
            var message = new SendGridMessage();

            message.From    = new EmailAddress(fromAddress, fromName);
            message.Subject = subject;
            message.SetClickTracking(false, true);
            //message.TemplateId = templateName;

            var emailMute      = false;
            var toAddressEmail = EastFive.Web.Configuration.Settings.GetString(AppSettings.MuteEmailToAddress,
                                                                               (emailMuteString) =>
            {
                if (emailMuteString.IsNullOrWhiteSpace())
                {
                    return(new EmailAddress(toAddress, toName));
                }
                emailMute = true;
                return(new EmailAddress(emailMuteString, $"MUTED[{toAddress}:{toName}]"));
            },
                                                                               (why) => new EmailAddress(toAddress, toName));

            message.AddTo(toAddressEmail);
            // message.SetClickTracking(false, false);

            var bccAddressesAdded = Web.Configuration.Settings.GetString(AppSettings.BccAllAddresses,
                                                                         copyEmail =>
            {
                var bccAddresses = (copyEmail.IsNullOrWhiteSpace() ? "" : copyEmail)
                                   .Split(',')
                                   .Where(s => !String.IsNullOrWhiteSpace(s))
                                   .Select((bccAddress) => new EmailAddress(bccAddress))
                                   .ToList();
                if (bccAddresses.Any())
                {
                    message.AddBccs(bccAddresses);
                }
                return(true);
            },
                                                                         (why) => false);


            var subsitutionsSingleDictionary = substitutionsSingle
                                               .Select(kvp => new KeyValuePair <string, string>($"--{kvp.Key}--", kvp.Value))
                                               .ToDictionary();

            message.AddSubstitutions(subsitutionsSingleDictionary);
            var client = new global::SendGrid.SendGridClient(apiKey);

            var responseTemplates = await client.RequestAsync(global::SendGrid.SendGridClient.Method.GET, urlPath : $"/templates/{templateName}");

            if (responseTemplates.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                return(onFailure($"The specified template [{templateName}] does not exist."));
            }
            var templateInfo = await responseTemplates.Body.ReadAsStringAsync();

            if (!responseTemplates.StatusCode.IsSuccess())
            {
                return(onFailure($"Failed to aquire template:{templateInfo}"));
            }

            var     converter = new Newtonsoft.Json.Converters.ExpandoObjectConverter();
            dynamic obj       = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(templateInfo, converter);
            string  html      = obj.versions[0].html_content;
            var     htmlDoc   = new HtmlAgilityPack.HtmlDocument();

            htmlDoc.LoadHtml(html);
            if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
            {
                return(onFailure($"Template has parse errors:{htmlDoc.ParseErrors.Select(pe => pe.Reason).Join(";")}"));
            }

            var substitutionsMultipleExpanded = substitutionsMultiple
                                                .NullToEmpty()
                                                .SelectMany(
                (substitutionMultiple) =>
            {
                var matchingNodes = htmlDoc.DocumentNode.SelectNodes($"//*[@data-repeat='--{substitutionMultiple.Key}--']");
                if (!matchingNodes.NullToEmpty().Any())
                {
                    return new HtmlAgilityPack.HtmlNode[] { }
                }
                ;

                var substituations = matchingNodes
                                     .Select(
                    matchingNode =>
                {
                    var parentNode = substitutionMultiple.Value
                                     .Where(
                        subValues =>
                    {
                        if (!matchingNode.Attributes.Contains("data-repeat-selector-key"))
                        {
                            return(true);
                        }
                        if (!matchingNode.Attributes.Contains("data-repeat-selector-value"))
                        {
                            return(true);
                        }
                        var key = matchingNode.Attributes["data-repeat-selector-key"].Value;
                        if (!subValues.ContainsKey(key))
                        {
                            return(false);
                        }
                        var value = matchingNode.Attributes["data-repeat-selector-value"].Value;
                        return(subValues[key] == value);
                    })
                                     .Aggregate(matchingNode.ParentNode,
                                                (parentNodeAggr, subValues) =>
                    {
                        var newChildHtml = subValues
                                           .Aggregate(
                            matchingNode.OuterHtml,
                            (subTextAggr, sub) =>
                        {
                            subTextAggr = subTextAggr.Replace($"--{sub.Key}--", sub.Value);
                            return(subTextAggr);
                        });

                        var childNode = HtmlAgilityPack.HtmlNode.CreateNode(newChildHtml);
                        parentNodeAggr.AppendChild(childNode);
                        return(parentNodeAggr);
                    });

                    parentNode.RemoveChild(matchingNode);
                    //return new KeyValuePair<string, string>(matchingNode.OuterHtml, subText);
                    return(matchingNode);
                })
                                     .ToArray();
                return(substituations);
            })
                                                .ToArray();

            // message.AddSubstitutions(substitutionsMultipleExpanded);
            //message.HtmlContent = htmlDoc.DocumentNode.OuterHtml;
            message.PlainTextContent = htmlDoc.DocumentNode.InnerText;

            message.HtmlContent = subsitutionsSingleDictionary.Aggregate(
                htmlDoc.DocumentNode.OuterHtml,
                (outerHtml, substitutionSingle) =>
            {
                return(outerHtml.Replace($"--{substitutionSingle.Key}--", substitutionSingle.Value));
            });

            // Send the email, which returns an awaitable task.
            try
            {
                var response = await client.SendEmailAsync(message);

                var body = await response.Body.ReadAsStringAsync();

                if (!response.StatusCode.IsSuccess())
                {
                    return(onFailure(body));
                }

                var messageIdHeaders = response.Headers
                                       .Where(header => header.Key == "X-Message-Id");
                if (!messageIdHeaders.Any())
                {
                    return(onSuccess(body));
                }

                var messageIds = messageIdHeaders.First().Value;
                if (!messageIds.Any())
                {
                    return(onSuccess(body));
                }

                var messageId = messageIds.First();
                return(onSuccess(messageId));
            }
            catch (Exception ex)
            {
                //var details = new StringBuilder();

                //details.Append("ResponseStatusCode: " + ex.ResponseStatusCode + ".   ");
                //for (int i = 0; i < ex.Errors.Count(); i++)
                //{
                //    details.Append(" -- Error #" + i.ToString() + " : " + ex.Errors[i]);
                //}

                return(onFailure(ex.ToString()));
            }
        }
Exemplo n.º 30
0
        public async Task <SendResponse> SendAsync(IFluentEmail email, CancellationToken?token = null)
        {
            var sendGridClient = new SendGridClient(_apiKey);

            var mailMessage = new SendGridMessage();

            mailMessage.SetSandBoxMode(_sandBoxMode);

            mailMessage.SetFrom(ConvertAddress(email.Data.FromAddress));

            if (email.Data.ToAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddTos(email.Data.ToAddresses.Select(ConvertAddress).ToList());
            }

            if (email.Data.CcAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddCcs(email.Data.CcAddresses.Select(ConvertAddress).ToList());
            }

            if (email.Data.BccAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddBccs(email.Data.BccAddresses.Select(ConvertAddress).ToList());
            }

            mailMessage.SetSubject(email.Data.Subject);

            if (email.Data.Headers.Any())
            {
                mailMessage.AddHeaders(email.Data.Headers);
            }

            if (email.Data.IsHtml)
            {
                mailMessage.HtmlContent = email.Data.Body;
            }
            else
            {
                mailMessage.PlainTextContent = email.Data.Body;
            }

            switch (email.Data.Priority)
            {
            case Priority.High:
                // https://stackoverflow.com/questions/23230250/set-email-priority-with-sendgrid-api
                mailMessage.AddHeader("Priority", "Urgent");
                mailMessage.AddHeader("Importance", "High");
                // https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmail/2bb19f1b-b35e-4966-b1cb-1afd044e83ab
                mailMessage.AddHeader("X-Priority", "1");
                mailMessage.AddHeader("X-MSMail-Priority", "High");
                break;

            case Priority.Normal:
                // Do not set anything.
                // Leave default values. It means Normal Priority.
                break;

            case Priority.Low:
                // https://stackoverflow.com/questions/23230250/set-email-priority-with-sendgrid-api
                mailMessage.AddHeader("Priority", "Non-Urgent");
                mailMessage.AddHeader("Importance", "Low");
                // https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmail/2bb19f1b-b35e-4966-b1cb-1afd044e83ab
                mailMessage.AddHeader("X-Priority", "5");
                mailMessage.AddHeader("X-MSMail-Priority", "Low");
                break;
            }

            if (!string.IsNullOrEmpty(email.Data.PlaintextAlternativeBody))
            {
                mailMessage.PlainTextContent = email.Data.PlaintextAlternativeBody;
            }

            if (email.Data.Attachments.Any())
            {
                foreach (var attachment in email.Data.Attachments)
                {
                    var sendGridAttachment = await ConvertAttachment(attachment);

                    mailMessage.AddAttachment(sendGridAttachment.Filename, sendGridAttachment.Content,
                                              sendGridAttachment.Type, sendGridAttachment.Disposition, sendGridAttachment.ContentId);
                }
            }

            var sendGridResponse = await sendGridClient.SendEmailAsync(mailMessage, token.GetValueOrDefault());

            var sendResponse = new SendResponse();

            if (IsHttpSuccess((int)sendGridResponse.StatusCode))
            {
                return(sendResponse);
            }

            sendResponse.ErrorMessages.Add($"{sendGridResponse.StatusCode}");
            var messageBodyDictionary = await sendGridResponse.DeserializeResponseBodyAsync(sendGridResponse.Body);

            if (messageBodyDictionary.ContainsKey("errors"))
            {
                var errors = messageBodyDictionary["errors"];

                foreach (var error in errors)
                {
                    sendResponse.ErrorMessages.Add($"{error}");
                }
            }

            return(sendResponse);
        }