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.º 2
0
        public async Task <SendGridFunctionResult> ExecuteEmail(IEmail Email)
        {
            try
            {
                var msg = new SendGridMessage();

                msg.SetFrom(new EmailAddress(Email.FromEmail.Email, Email.FromEmail.FullName));

                foreach (IEmailAddress emailAddress in Email.ToEmail)
                {
                    msg.AddTo(emailAddress.Email, emailAddress.FullName);
                }

                foreach (IEmailAddress emailAddress in Email.CCEmail)
                {
                    msg.AddCc(emailAddress.Email, emailAddress.FullName);
                }

                foreach (IEmailAddress emailAddress in Email.BCCEmail)
                {
                    msg.AddBcc(emailAddress.Email, emailAddress.FullName);
                }

                foreach (IEmailAttachment emailAttachment in Email.Attachments)
                {
                    msg.AddAttachment(emailAttachment.FileName, emailAttachment.Content);
                }

                msg.SetSubject(Email.Subject);
                msg.AddContent(MimeType.Html, string.Format("{0}{1}{2}", Email.Body, Environment.NewLine, Email.Footer));
                msg.AddCategory(this.Database);
                msg.AddCategory(this.Application.ToString());
                msg.SetClickTracking(true, true);
                msg.SetOpenTracking(true);

                var response = await SendGridClient.SendEmailAsync(msg);

                Dictionary <string, string> result = response.DeserializeResponseHeaders(response.Headers);

                return(new SendGridFunctionResult(response.StatusCode.ToString(), response.Body.ToString(), result["X-Message-Id"].ToString()));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 3
0
        private static async Task BuildEmail(string toAddress, Language language, IBinder binder,
                                             TemplateData templateData,
                                             string category,
                                             CancellationToken token)
        {
            var emailProvider = await binder.BindAsync <IAsyncCollector <SendGridMessage> >(new SendGridAttribute()
            {
                ApiKey = "SendgridKey",
                //From = "Spitball <no-reply @spitball.co>"
            }, token);


            var message = new SendGridMessage
            {
                Asm = new ASM {
                    GroupId = UnsubscribeGroup.Update
                },
                TemplateId = "d-91a839096c8547f9a028134744e78ecb"
            };

            if (language.Info.Equals(Language.EnglishIndia.Info))
            {
                message.TemplateId = "d-91a839096c8547f9a028134744e78ecb";
            }
            message.AddFromResource(language.Info);
            templateData.To = toAddress;
            var personalization = new Personalization
            {
                TemplateData = templateData
            };


            message.Personalizations = new List <Personalization>()
            {
                personalization
            };
            message.AddCategory(category);
            message.TrackingSettings = new TrackingSettings
            {
                Ganalytics = new Ganalytics
                {
                    UtmCampaign = category,
                    UtmSource   = "SendGrid",
                    UtmMedium   = "Email",
                    Enable      = true
                }
            };
            message.AddTo(toAddress);
            await emailProvider.AddAsync(message, token);
        }
        public async Task DoOperationAsync(StudyRoomVideoMessage msg, IBinder binder, CancellationToken token)
        {
            var emailProvider = await binder.BindAsync <IAsyncCollector <SendGridMessage> >(new SendGridAttribute()
            {
                ApiKey = "SendgridKey",
                From   = "Spitball <no-reply @spitball.co>"
            }, token);


            var message = new SendGridMessage
            {
                Asm = new ASM {
                    GroupId = UnsubscribeGroup.Update
                },
                TemplateId = msg.Info.Equals(Language.English.Info) ? "d-8cb8934b45794ab999de2b5c24d145c0" : "d-f35043e77b0d462eb7f352c40590b128"
            };

            CultureInfo.CurrentUICulture = msg.Info;

            var personalization = new Personalization
            {
                TemplateData = new
                {
                    firstName = msg.UserName,
                    tutorName = msg.TutorFirstName,
                    date      = msg.DateTime.ToString("d"),
                    link      = msg.DownloadLink,
                    to        = msg.To
                }
            };


            message.Personalizations = new List <Personalization>()
            {
                personalization
            };
            message.AddCategory("Session-Video");
            message.TrackingSettings = new TrackingSettings
            {
                Ganalytics = new Ganalytics
                {
                    UtmCampaign = "Session-Video",
                    UtmSource   = "SendGrid",
                    UtmMedium   = "Email",
                    Enable      = true
                }
            };
            message.AddTo(msg.To);
            await emailProvider.AddAsync(message, token);
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press ENTER to send test email to sendgrid mock website...");
            Console.ReadLine();

            var client  = new SendGridClient("gejrgpeojgpejrpjpejrg", "http://*****:*****@example.com", "John Doe")
            };

            message.AddTo(new EmailAddress("*****@*****.**", "Jane Doe"));
            message.Subject = "This is awesome";
            message.AddCategory("ListingReply");
            message.HtmlContent = "<h1>This is so cool</h1>";
            var task = client.SendEmailAsync(message);

            task.Wait();
            var result = task.Result;
        }
Exemplo n.º 6
0
        private static async Task ProcessEmail(IAsyncCollector <SendGridMessage> emailProvider, ILogger log,
                                               BaseEmail topicMessage, CancellationToken token)
        {
            var message         = new SendGridMessage();
            var personalization = new Personalization();


            if (topicMessage.TemplateId != null)
            {
                message.Asm = new ASM
                {
                    GroupId = topicMessage.UnsubscribeGroup
                };
                message.TemplateId = topicMessage.TemplateId;
                message.Subject    = topicMessage.Subject;
                if (topicMessage.Campaign != null)
                {
                    message.AddCategory(topicMessage.Campaign);
                    message.TrackingSettings = new TrackingSettings
                    {
                        Ganalytics = new Ganalytics
                        {
                            UtmCampaign = topicMessage.Campaign,
                            UtmSource   = "SendGrid",
                            UtmMedium   = "Email",
                            Enable      = true
                        }
                    };
                    message.TrackingSettings.Ganalytics.Enable = true;
                }

                personalization.Substitutions = new Dictionary <string, string>();
                foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(topicMessage))
                {
                    var p = prop.GetValue(topicMessage);
                    personalization.Substitutions[$"-{prop.Name}-"] = p?.ToString() ?? string.Empty;
                    //personalization.AddSubstitution($"-{prop.Name}-", p?.ToString() ?? string.Empty);
                }
                message.Personalizations = new List <Personalization>()
                {
                    personalization
                };
            }
            else
            {
                message.AddContent("text/html", topicMessage.ToString());
                message.Subject = topicMessage.Subject;
                if (topicMessage.Bcc != null)
                {
                    foreach (var bcc in topicMessage.Bcc)
                    {
                        message.AddBcc(bcc);
                    }
                }
                log.LogWarning("error with template name" + topicMessage.TemplateId);
            }

            CultureInfo.DefaultThreadCurrentCulture = topicMessage.Info;
            message.AddFromResource(topicMessage.Info);
            message.AddTo(topicMessage.To);

            await emailProvider.AddAsync(message, token);
        }
Exemplo n.º 7
0
        public static async Task SendEmail(
            [ActivityTrigger] UpdateUserEmailDto user,
            [SendGrid(ApiKey = "SendgridKey", From = "Spitball <*****@*****.**>")] IAsyncCollector <SendGridMessage> emailProvider,
            [Inject] IQueryBus queryBus,
            [Inject] IUrlBuilder urlBuilder,
            [Inject] IDataProtectionService dataProtectService,
            [Inject] IHostUriService hostUriService,
            CancellationToken token)
        {
            var code = dataProtectService.ProtectData(user.UserId.ToString(), DateTimeOffset.UtcNow.AddDays(3));
            var uri  = hostUriService.GetHostUri();

            var questionNvc = new NameValueCollection()
            {
                ["width"]  = "86",
                ["height"] = "96",
                ["mode"]   = "crop"
            };

            var q      = new GetUpdatesEmailByUserQuery(user.UserId, user.Since);
            var result = (await queryBus.QueryAsync(q, token)).ToList();

            if (result.Count == 0)
            {
                return;
            }
            var courses = result.GroupBy(g => g.Course).Take(3).Select(s =>
            {
                var emailUpdates = s.Take(4).ToList();
                return(new Course()
                {
                    Name = s.Key,
                    Url = urlBuilder.BuildCourseEndPoint(s.Key),
                    NeedMore = emailUpdates.Count == 4,
                    Documents = emailUpdates.OfType <DocumentUpdateEmailDto>().Select(document =>
                    {
                        var uriBuilder = new UriBuilder(uri)
                        {
                            Path = $"api/image/document/{document.Id}",
                        };
                        uriBuilder.AddQuery(questionNvc);

                        return new Document()
                        {
                            Url = urlBuilder.BuildDocumentEndPoint(document.Id, new { token = code }),
                            Name = document.Name,
                            UserName = document.UserName,
                            DocumentPreview = uriBuilder.ToString(),
                            UserImage = BuildUserImage(document.UserId, document.UserImage, document.UserName, hostUriService)
                        };
                    }),
                    Questions = emailUpdates.OfType <QuestionUpdateEmailDto>().Select(question => new Question()
                    {
                        QuestionUrl = urlBuilder.BuildQuestionEndPoint(question.QuestionId, new { token = code }),
                        QuestionText = question.QuestionText,
                        UserImage = BuildUserImage(question.UserId, question.UserImage, question.UserName, hostUriService),
                        UserName = question.UserName,
                        AnswerText = question.AnswerText
                    })
                });
            });

            var templateData = new UpdateEmail(user.UserName, user.ToEmailAddress, user.Language.TextInfo.IsRightToLeft)
            {
                DocumentCountUpdate = result.OfType <DocumentUpdateEmailDto>().Count(),
                QuestionCountUpdate = result.OfType <QuestionUpdateEmailDto>().Count(),
                Courses             = courses
            };

            var message = new SendGridMessage
            {
                Asm = new ASM {
                    GroupId = UnsubscribeGroup.Update
                },
                TemplateId = Equals(user.Language, Language.Hebrew.Info)
                    ? HebrewTemplateId : EnglishTemplateId
            };

            templateData.To = user.ToEmailAddress;
            var personalization = new Personalization
            {
                TemplateData = templateData
            };


            message.Personalizations = new List <Personalization>()
            {
                personalization
            };
            message.AddCategory("updates");
            message.TrackingSettings = new TrackingSettings
            {
                Ganalytics = new Ganalytics
                {
                    UtmCampaign = "updates",
                    UtmSource   = "SendGrid",
                    UtmMedium   = "Email",
                    Enable      = true
                }
            };
            message.AddTo(user.ToEmailAddress);
            await emailProvider.AddAsync(message, token);

            await emailProvider.FlushAsync(token);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Send an email
        /// </summary>
        /// <param name="email">contents of the email to send</param>
        /// <returns>send email task</returns>
        public async Task SendEmail(IEmail email)
        {
            // check the email addresses
            if (email.To == null || email.To.Count < 1)
            {
                this.log.LogException("got empty email address list");
            }

            foreach (string to in email.To)
            {
                if (!EmailAddressChecker.IsValidEmail(to))
                {
                    this.log.LogException("got bad email address: " + to);
                }
            }

            // create a new message
            SendGridMessage myMessage = new SendGridMessage();

            // assign the from address
            myMessage.From = new EmailAddress(email.FromAddress, email.FromName);

            // assign the recipients
            foreach (string emailAddress in email.To)
            {
                myMessage.AddTo(emailAddress);
            }

            // assign the subject
            myMessage.Subject = email.Subject;

            // assign the body of the email
            myMessage.HtmlContent      = email.HtmlBody;
            myMessage.PlainTextContent = email.TextBody;

            // assign the footer of the email
            myMessage.SetFooterSetting(true, email.HtmlFooter, email.TextFooter);

            // email reporting features
            myMessage.SetClickTracking(true, false);       // weekly stats of which links users opened in our emails
            myMessage.SetOpenTracking(true, string.Empty); // weekly stats of how many of our emails were opened

            // set email category. All e-mails must have category in place.
            string category = null;

            PropertyInfo[] properties = email.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo property in properties)
            {
                if (property.Name == "Category")
                {
                    object categoryPropObj = property.GetValue(email, null);
                    if (categoryPropObj == null)
                    {
                        this.log.LogException(new ArgumentException("Each email message must have a category. Please set one."));
                    }

                    category = categoryPropObj.ToString();
                }
            }

            if (!string.IsNullOrWhiteSpace(category))
            {
                myMessage.AddCategory(category); // email stats will be bucketed by reportingCategory
            }

            // send it
            SendGridClient client = new SendGridClient(this.sendGridKey);

            this.log.LogInformation("Sending email from:" + email.FromAddress + ", to:" + string.Join(",", email.To.ToArray()) + " subject:" + email.Subject);
            Response response = await client.SendEmailAsync(myMessage);

            if (response.StatusCode != System.Net.HttpStatusCode.Accepted && response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                this.log.LogException(new Exception("Got " + response.StatusCode.ToString() + " status code from Sendgrid"));
            }
        }