Ejemplo n.º 1
0
        public override async Task <string> SendEmailAsync()
        {
            try
            {
                var apiKey    = SendGridApiKey;
                var fromEmail = new EmailAddress(FromAddress);
                var client    = new SendGridClient(apiKey);
                var message   = new SendGridMessage();
                message.AddTos(GenerateEmailAddress(To));
                message.From = fromEmail;
                message.AddHeader("recover", "Account Recovery");
                message.Subject     = Subject;
                message.HtmlContent = Body;
                Response response = await client.SendEmailAsync(message);

                if (response.StatusCode == System.Net.HttpStatusCode.OK || response.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    return("success");
                }
            }
            catch (Exception ex)
            {
                _logger.Error("error in SendEmailAsync", ex);
            }
            return("fail");
        }
        private SendGridMessage CreateOutgoingMessage()
        {
            var msg = new SendGridMessage();

            msg.SetFrom(Settings.Station.AgentAddr.AsEmailAddress());
            var headers = ParseHeaders(Request.Form["headers"]);

            msg.AddTos(GetReplyTo(headers).AsEmailAddresses());
            msg.AddHeader("In-Reply-To", headers["Message-Id"]);
            return(msg);
        }
 /// <summary>
 /// Demonstrates declaratively defining all email properties with parameter binding
 /// to message properties.
 /// </summary>
 public static void ProcessOrder_Declarative(
     [QueueTrigger(@"samples-orders")] Order order,
     [SendGrid(
          To = "{CustomerEmail}",
          Subject = "Thanks for your order (#{OrderId})!",
          Text = "{CustomerName}, we've received your order ({OrderId}) and have begun processing it!")]
     out SendGridMessage message)
 {
     // You can set additional message properties here
     message = new SendGridMessage();
     message.AddHeader("MyHeader", "MyValue");
 }
Ejemplo n.º 4
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"]));
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 7
0
        public async Task <EmailSendResult> SendEmailAsync(
            string toEmailCsv,
            string fromEmail,
            string subject,
            string plainTextMessage,
            string htmlMessage,
            string replyToEmail   = null,
            Importance importance = Importance.Normal,
            bool isTransactional  = true,
            string fromName       = null,
            string replyToName    = null,
            string toAliasCsv     = null,
            string ccEmailCsv     = null,
            string ccAliasCsv     = null,
            string bccEmailCsv    = null,
            string bccAliasCsv    = null,
            List <EmailAttachment> attachments = null,
            string charsetBodyHtml             = null,
            string charsetBodyText             = null,
            string configLookupKey             = null
            )
        {
            var isConfigured = await IsConfigured(configLookupKey);

            if (!isConfigured)
            {
                var message = $"failed to send email with subject {subject} because sendgrid api key is empty or not configured";
                _log.LogError(message);
                return(new EmailSendResult(false, message));
            }

            if (string.IsNullOrWhiteSpace(toEmailCsv))
            {
                throw new ArgumentException("no to addresses provided");
            }

            if (string.IsNullOrWhiteSpace(fromEmail) && string.IsNullOrWhiteSpace(options.DefaultEmailFromAddress))
            {
                throw new ArgumentException("no from address provided");
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("no subject provided");
            }

            var hasPlainText = !string.IsNullOrWhiteSpace(plainTextMessage);
            var hasHtml      = !string.IsNullOrWhiteSpace(htmlMessage);

            if (!hasPlainText && !hasHtml)
            {
                throw new ArgumentException("no message provided");
            }

            var m = new SendGridMessage();

            if (!string.IsNullOrWhiteSpace(fromEmail))
            {
                m.From = new EmailAddress(fromEmail, fromName);
            }
            else
            {
                m.From = new EmailAddress(options.DefaultEmailFromAddress, options.DefaultEmailFromAlias);
            }

            if (!string.IsNullOrWhiteSpace(replyToEmail))
            {
                m.ReplyTo = new EmailAddress(replyToEmail, replyToName);
            }

            m.Subject          = subject;
            m.HtmlContent      = htmlMessage;
            m.PlainTextContent = plainTextMessage;

            if (toEmailCsv.Contains(","))
            {
                var      useToAliases = false;
                string[] adrs         = toEmailCsv.Split(',');
                string[] toAliases    = new string[0];
                if (toAliasCsv != null && toAliasCsv.Contains(","))
                {
                    toAliases = toAliasCsv.Split(',');
                    if (toAliases.Length > 0 && toAliases.Length == adrs.Length)
                    {
                        useToAliases = true;
                    }
                }
                if (useToAliases)
                {
                    for (int i = 0; i < adrs.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(adrs[i]))
                        {
                            m.AddTo(new EmailAddress(adrs[i].Trim(), toAliases[i].Trim()));
                        }
                    }
                }
                else
                {
                    foreach (string item in adrs)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            m.AddTo(new EmailAddress(item.Trim(), ""));
                        }
                    }
                }
            }
            else
            {
                //not really a csv
                m.AddTo(new EmailAddress(toEmailCsv, toAliasCsv));
            }

            if (!string.IsNullOrWhiteSpace(ccEmailCsv))
            {
                if (ccEmailCsv.Contains(","))
                {
                    var      useAliases = false;
                    string[] adrs       = ccEmailCsv.Split(',');
                    string[] aliases    = new string[0];
                    if (ccAliasCsv != null && ccAliasCsv.Contains(","))
                    {
                        aliases = ccAliasCsv.Split(',');
                        if (aliases.Length > 0 && aliases.Length == adrs.Length)
                        {
                            useAliases = true;
                        }
                    }
                    if (useAliases)
                    {
                        for (int i = 0; i < adrs.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(adrs[i]))
                            {
                                m.AddCc(new EmailAddress(adrs[i].Trim(), aliases[i].Trim()));
                            }
                        }
                    }
                    else
                    {
                        foreach (string item in adrs)
                        {
                            if (!string.IsNullOrEmpty(item))
                            {
                                m.AddCc(new EmailAddress(item.Trim(), ""));
                            }
                        }
                    }
                }
                else
                {
                    m.AddCc(new EmailAddress(ccEmailCsv, ccAliasCsv));
                }
            }

            if (!string.IsNullOrWhiteSpace(bccEmailCsv))
            {
                if (bccEmailCsv.Contains(","))
                {
                    var      useAliases = false;
                    string[] adrs       = bccEmailCsv.Split(',');
                    string[] aliases    = new string[0];
                    if (bccAliasCsv != null && bccAliasCsv.Contains(","))
                    {
                        aliases = bccAliasCsv.Split(',');
                        if (aliases.Length > 0 && aliases.Length == adrs.Length)
                        {
                            useAliases = true;
                        }
                    }
                    if (useAliases)
                    {
                        for (int i = 0; i < adrs.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(adrs[i]))
                            {
                                m.AddBcc(new EmailAddress(adrs[i].Trim(), aliases[i].Trim()));
                            }
                        }
                    }
                    else
                    {
                        foreach (string item in adrs)
                        {
                            if (!string.IsNullOrEmpty(item))
                            {
                                m.AddBcc(new EmailAddress(item.Trim(), ""));
                            }
                        }
                    }
                }
                else
                {
                    m.AddBcc(new EmailAddress(bccEmailCsv, bccAliasCsv));
                }
            }

            m.AddHeader("Importance", GetMessageImportance(importance));

            if (!isTransactional)
            {
                m.AddHeader("Precedence", "bulk");
            }

            if (attachments != null && attachments.Count > 0)
            {
                foreach (var attachment in attachments)
                {
                    using (attachment.Stream)
                    {
                        try
                        {
                            var bytes   = attachment.Stream.ToByteArray();
                            var content = Convert.ToBase64String(bytes);
                            m.AddAttachment(Path.GetFileName(attachment.FileName), content);
                        }
                        catch (Exception ex)
                        {
                            _log.LogError($"failed to add attachment with path {attachment.FileName}, error was {ex.Message} : {ex.StackTrace}");
                        }
                    }
                }
            }

            var client = new SendGridClient(options.ApiKey);

            try
            {
                var response = await client.SendEmailAsync(m);

                if (response.StatusCode != System.Net.HttpStatusCode.Accepted && response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    var message = $"did not get expected 200 status code from SendGrid, response was {response.StatusCode} {response.Body.ToString()} ";
                    _log.LogError(message);
                    return(new EmailSendResult(false, message));
                }
            }
            catch (Exception ex)
            {
                var message = $"failed to send email with subject {subject} error was {ex.Message} : {ex.StackTrace}";
                _log.LogError(message);
                return(new EmailSendResult(false, message));
            }

            return(new EmailSendResult(true));
        }
Ejemplo n.º 8
0
        public async Task <EmailResponse> SendAsync(EmailMessage email, CancellationToken?token = null)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Send an email {Subject}", email.Subject);
            }
            // init client
            var sendGridClient = new SendGridClient(_options.ApiKey);

            // build a message
            var mailMessage = new SendGridMessage();

            mailMessage.SetSandBoxMode(_options.SandBoxMode);
            // set FROM address
            mailMessage.SetFrom(ConvertAddress(email.FromAddress));
            // add TO addresses
            mailMessage.AddTos(email.ToAddresses.Select(ConvertAddress).ToList());

            // add CC addresses
            if (email.CcAddresses.Any())
            {
                mailMessage.AddCcs(email.CcAddresses.Select(ConvertAddress).ToList());
            }

            // add BCC addresses
            if (email.BccAddresses.Any())
            {
                mailMessage.AddBccs(email.BccAddresses.Select(ConvertAddress).ToList());
            }

            // set reply to
            if (email.ReplyToAddress != null)
            {
                mailMessage.ReplyTo = ConvertAddress(email.ReplyToAddress);
            }

            // set subject
            mailMessage.SetSubject(email.Subject);

            // set body
            if (email.IsHtml)
            {
                mailMessage.HtmlContent = email.Body;
            }
            else
            {
                mailMessage.PlainTextContent = email.Body;
            }

            // set priority
            switch (email.Priority)
            {
            case EmailPriority.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 EmailPriority.Normal:
                // Do not set anything.
                // Leave default values. It means Normal Priority.
                break;

            case EmailPriority.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;
            }

            // add attachments
            foreach (var attachment in email.Attachments)
            {
                var content = await GetAttachmentBase64String(attachment.Data);

                mailMessage.AddAttachment(
                    filename: attachment.FileName,
                    base64Content: content,
                    type: attachment.ContentType);
            }

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

            // get response
            // - success
            if (IsHttpSuccess((int)sendGridResponse.StatusCode))
            {
                return(new EmailResponse());
            }
            // - errors
            var errorList = new List <string> {
                $"{sendGridResponse.StatusCode}"
            };
            var messageBodyDictionary = await sendGridResponse.DeserializeResponseBodyAsync(sendGridResponse.Body);

            if (messageBodyDictionary.ContainsKey("errors"))
            {
                var errors = messageBodyDictionary["errors"];
                foreach (var error in errors)
                {
                    errorList.Add($"{error}");
                }
            }
            return(new EmailResponse(errorList));
        }