Пример #1
0
        public static void SendMail(string from, string to, string subject, string message)
        {
            var client = new SendGridClient(EnvironmentHelper.GetInfoFromConfig("sendGridToken"));

            var fromMail = new EmailAddress(string.IsNullOrEmpty(from) ? EnvironmentHelper.GetInfoFromConfig("defaultFromMail") : from);

            var toMails = (string.IsNullOrEmpty(to) ? EnvironmentHelper.GetInfoFromConfig("toMails") : to)
                          .Split(',')
                          .Select(s => new EmailAddress(s.Trim()));

            try
            {
                var multiMessage = MailHelper.CreateMultipleEmailsToMultipleRecipients(fromMail, toMails.ToList(), new List <string>(Enumerable.Repeat(subject, toMails.Count())), string.Empty, message.ToString(), null);

                client.SendEmailAsync(multiMessage).GetAwaiter().GetResult();
            }
            catch (Exception)
            {
                foreach (var mail in toMails)
                {
                    var msg = MailHelper.CreateSingleEmail(fromMail, mail, subject, string.Empty, message);

                    client.SendEmailAsync(msg).GetAwaiter().GetResult();
                }
            }
        }
        public async Task <HttpStatusCode> SendMultipleMailToMultipleEmail(List <string> subject, string plaintextContent, string htmlContent, List <EmailAddress> emails, List <Dictionary <string, string> > substitute)
        {
            var msg = MailHelper.CreateMultipleEmailsToMultipleRecipients(client.From, emails, subject, plaintextContent, htmlContent, substitute);
            var res = await client.GridClient.SendEmailAsync(msg);

            return(res.StatusCode);
        }
Пример #3
0
        public async Task SendGridEmailSend(string FromAdressTitle, string FromAddress, string ToAdressTitle, string ToAddress, string CcAddress, string Subject, string BodyContent)
        {
            var apiKey  = Environment.GetEnvironmentVariable("SENDGRID_KEY");
            var client  = new SendGridClient(apiKey);
            var from    = new EmailAddress(FromAddress, FromAdressTitle);
            var subject = new List <string>()
            {
                Subject, Subject
            };

            var tos = new List <EmailAddress>()
            {
                new EmailAddress(ToAddress, ToAdressTitle),
                new EmailAddress(CcAddress)
            };

            //var to = new EmailAddress(ToAddress, ToAdressTitle);
            var plainTextContent = " ";
            var htmlContent      = BodyContent;

            try
            {
                var msg = MailHelper.CreateMultipleEmailsToMultipleRecipients(from, tos, subject, plainTextContent, htmlContent, new List <Dictionary <string, string> >()
                {
                });
                var response = await client.SendEmailAsync(msg);
            }
            catch (Exception ex)
            { }
        }
Пример #4
0
        public async Task SendEmailBulkAsync(List <string> tos, List <string> subjects, string htmlMessage, List <Dictionary <string, string> > substitutions, string fromEmail = null)
        {
            string fromName = "Tellma";

            fromEmail ??= _config.DefaultFromEmail;
            string sendGridApiKey = _config.ApiKey;

            var client      = new SendGridClient(sendGridApiKey);
            var from        = new EmailAddress(fromEmail, fromName);
            var toAddresses = tos.Select(e => new EmailAddress(e)).ToList();


            var msg = MailHelper.CreateMultipleEmailsToMultipleRecipients(
                from, toAddresses, subjects, "", htmlMessage, substitutions);

            var response = await client.SendEmailAsync(msg);

            // Handle returned errors
            if (response.StatusCode == HttpStatusCode.TooManyRequests)
            {
                // SendGrid has a quota depending on your subscription, on a free account you only get 100 emails per day
                throw new InvalidOperationException("The SendGrid subscription configured in the system has reached its limit, please contact support");
            }

            if (response.StatusCode >= HttpStatusCode.BadRequest)
            {
                string responseMessage = await response.Body.ReadAsStringAsync();

                _logger.LogError($"Error sending email through SendGrid, Status Code: {response.StatusCode}, Message: {responseMessage}");

                throw new InvalidOperationException($"The SendGrid API returned an unknown error {response.StatusCode} when trying to send the email through it");
            }
        }
Пример #5
0
        private async Task SendEmailCore(int companyId, List <EmailAddress> recipients,
                                         bool useTemplate, object?templateData,
                                         List <string>?subjects, string?plainTextContent, string?htmlContent,
                                         List <Dictionary <string, string> >?substitutions,
                                         string?uniqueArgument, string?uniqueArgumentValue,
                                         DateTime?sendAt)
        {
            var sendGridAccount = await GetAccount(companyId);

            var from = new EmailAddress(sendGridAccount.FromEmail, sendGridAccount.FromEmailName);

            if (!string.IsNullOrEmpty(sendGridAccount.Bcc))
            {
                recipients.Add(new EmailAddress(sendGridAccount.Bcc));
                subjects?.Add(subjects.Last());
                substitutions?.Add(substitutions.Last());
            }

            SendGridMessage sendGridMessage;

            if (useTemplate)
            {
                sendGridMessage =
                    MailHelper.CreateSingleTemplateEmailToMultipleRecipients(from, recipients,
                                                                             sendGridAccount.TemplateId, templateData);
            }
            else
            {
                sendGridMessage = MailHelper.CreateMultipleEmailsToMultipleRecipients(from, recipients, subjects,
                                                                                      plainTextContent, htmlContent, substitutions);
            }

            if (uniqueArgument != null && uniqueArgumentValue != null)
            {
                foreach (var personalization in sendGridMessage.Personalizations)
                {
                    personalization.CustomArgs = new Dictionary <string, string>
                    {
                        { uniqueArgument, uniqueArgumentValue }
                    };
                }
            }

            if (sendAt != null)
            {
                sendGridMessage.SendAt = new DateTimeOffset(sendAt.Value).ToUnixTimeSeconds();
            }

            await Send(sendGridAccount, sendGridMessage);
        }
Пример #6
0
        private async Task DoWork()
        {
            var userManager = UserManager;
            var users       = userManager.Users.ToList();

            var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
            var client = new SendGridClient(apiKey);

            var from    = new EmailAddress("*****@*****.**", "Ben Womble");
            var subject =
                "OutCast Weekly Reminder";
            var plainTextContent =
                "Come see if there are any new events posted this week!.\n\n\n\n{unsubscribe}";
            var htmlContent =
                "<strong>Come see if there are any new events posted this week!</strong>" +
                "<br><br><a href='{unsubscribe}'>Unsubscribe</a>";

            var substitutions =
                users.Select(x => new Dictionary <string, string>()
            {
                { "{name}", x.UserName },
                { "{email}", x.Email },
                { "{unsubscribe}", x.UnsubscribeUrl },
            })
                .ToList();

            var msg = MailHelper.CreateMultipleEmailsToMultipleRecipients(
                from,
                users.Select(x => new EmailAddress(x.UserName, x.Email)).ToList(),
                users.Select(x => subject).ToList(),
                plainTextContent,
                htmlContent,
                substitutions);
            await client.SendEmailAsync(msg);

            var result = await client.SendEmailAsync(msg);

            if (result.StatusCode != HttpStatusCode.Accepted)
            {
                throw new Exception($"Failed to send email: {result.StatusCode}");
            }

            Debug.WriteLine("Newsletter Sent");
        }
Пример #7
0
        public SendGrid.Response SendToAllSurveyMembers(int adminId, int surveyId)
        {
            var survey = _context.Surveys
                         .Include(s => s.Admin)
                         .Include(s => s.Clients)
                         .Single(s => s.Id == surveyId && s.AdminId == adminId);
            var surveyInfo  = survey.Info.ToObject();
            var surveyStart = surveyInfo.SelectToken("availability").Value <DateTime>("start");
            var surveyEnd   = surveyInfo.SelectToken("availability").Value <DateTime>("end");
            var from        = _noreplyAddr;
            var tos         = survey.Clients
                              .Select(c => {
                var name = c.Info.ToObject().Value <string>("name");
                return(new EmailAddress(c.Email, name));
            })
                              .ToList();
            var subjects = survey.Clients.Select(c =>
                                                 $"Incoming survey from " +
                                                 $"{c.Survey.Admin.Info.ToObject().Value<string>("name") ?? "Unnamed"}" +
                                                 $" @surveygorilla.com").ToList();
            var link        = $"{_Request.Scheme }://{_Request.Host}{_Request.PathBase}/#!/token";
            var htmlContent =
                $"Survey name: -surveyName-<br>" +
                $"Available from -surveyStart- to -surveyEnd-<br>" +
                $"Access the survey here:<br>" +
                $"<a href=\"-tokenLink-\">-tokenLink-</a><br>" +
                $"Your name: -clientName-";
            var substitutions = survey.Clients.Select(c => new Dictionary <string, string>
            {
                { "-surveyName-", c.Survey.Name },
                { "-surveyStart-", surveyStart.ToString() },
                { "-surveyEnd-", surveyEnd.ToString() },
                { "-tokenLink-", $"{link}/{c.Token}" },
                { "-clientName-", c.Info.ToObject().Value <string>("name") },
            }).ToList();
            var msg        = MailHelper.CreateMultipleEmailsToMultipleRecipients(from, tos, subjects, null, htmlContent, substitutions);
            var gridClient = new SendGridClient(SendGridApiKey);
            var response   = gridClient.SendEmailAsync(msg).Result;

            return(response);
        }
Пример #8
0
        public async Task <bool> SendAsync(string from, ICollection <string> to, string subject, string body, bool html)
        {
            //if (string.IsNullOrWhiteSpace(from))
            //    throw new ArgumentNullException(nameof(from));
            if (to?.Any() != true)
            {
                throw new ArgumentNullException(nameof(to));
            }

            var emailFrom = from != null ? new EmailAddress(from) : null;
            var emailTo   = to.Select(x => new EmailAddress(x)).ToList();
            var subjects  = to.Select(x => subject).ToList();
            var subs      = to.Select(x => new Dictionary <string, string>()).ToList();

            try
            {
                var msg      = MailHelper.CreateMultipleEmailsToMultipleRecipients(emailFrom, emailTo, subjects, body, html ? body : null, subs);
                var response = await _client.SendEmailAsync(msg);

                // For better response handling visit https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html
                if ((int)response.StatusCode >= 200 && ((int)response.StatusCode <= 299))
                {
                    //_logger.Debug("Email sent successfully");
                    return(true);
                }
                else
                {
                    var content = await response.Body.ReadAsStringAsync();

                    //_logger.Error($"Error sending email: \nStatusCode: {response.StatusCode}\nResponse: {content}");
                    return(false);
                }
            }
            catch (Exception)
            {
                //_logger.Error("Error sending email", exception);
                return(false);
            }
        }