public void TestCreateSingleTemplateEmailToMultipleRecipients()
        {
            var from = new EmailAddress("*****@*****.**", "FromName");
            var tos  = new List <EmailAddress>
            {
                new EmailAddress("*****@*****.**"),
                new EmailAddress("*****@*****.**")
            };

            var templateId          = "d-template2";
            var dynamicTemplateData = new Dictionary <string, object>
            {
                { "key1", "value1" }
            };

            var sendGridMessage = MailHelper.CreateSingleTemplateEmailToMultipleRecipients(
                from,
                tos,
                templateId,
                dynamicTemplateData);

            Assert.Equal(from, sendGridMessage.From);
            Assert.Equal(tos[0], sendGridMessage.Personalizations.ElementAt(0).Tos.Single());
            Assert.Equal(tos[1], sendGridMessage.Personalizations.ElementAt(1).Tos.Single());
            Assert.Equal(templateId, sendGridMessage.TemplateId);
            Assert.Equal(dynamicTemplateData, sendGridMessage.Personalizations.ElementAt(0).TemplateData);
            Assert.Equal(dynamicTemplateData, sendGridMessage.Personalizations.ElementAt(1).TemplateData);
        }
 public virtual async Task SendSingleTemplateEmailMultipleRcpts(string from, List <EmailAddress> tos, string templateID, object templateData)
 {
     Require.That(templateID != null, new ErrorCode("Sendgrid Error", 403, "Required Sengrid template ID not configured in settings"));
     {
         var fromEmail = new EmailAddress(from);
         var msg       = MailHelper.CreateSingleTemplateEmailToMultipleRecipients(fromEmail, tos, templateID, templateData);
         await _client.SendEmailAsync(msg);
     }
 }
 public async Task SendSingleTemplateEmailMultipleRcptsAttachment(string from, List <EmailAddress> tos, string templateID, object templateData, CloudAppendBlob fileReference, string fileName)
 {
     Require.That(templateID != null, new ErrorCode("Sendgrid Error", 403, "Required Sengrid template ID not configured in settings"));
     {
         var fromEmail = new EmailAddress(from);
         var msg       = MailHelper.CreateSingleTemplateEmailToMultipleRecipients(fromEmail, tos, templateID, templateData);
         using (var stream = await fileReference.OpenReadAsync())
         {
             await msg.AddAttachmentAsync(fileName, stream);
         }
         await _client.SendEmailAsync(msg);
     }
 }
        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);
        }
Exemple #5
0
        public virtual async Task SendSingleTemplateEmailMultipleRcpts(string from, List <EmailAddress> tos, string templateID, object templateData)
        {
            Require.That(templateID != null, new ErrorCode("SendgridError", 501, "Required Sengrid template ID not configured in app settings"));
            {
                var fromEmail = new EmailAddress(from);
                var msg       = MailHelper.CreateSingleTemplateEmailToMultipleRecipients(fromEmail, tos, templateID, templateData);
                var response  = await _client.SendEmailAsync(msg);

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception("Error sending sendgrid email");
                }
            }
        }
Exemple #6
0
        public static void ResetPasswordMessage(ProductionUnitOwner currentProductionUnitOwner, string to, string callbackUrl)
        {
            var client = new SendGridClient(MailSendGridAPIKey);
            var from   = new EmailAddress("*****@*****.**", "Myfood Hub Bot");

            MailTemplateObject obj = new MailTemplateObject();
            var currentTemplate    = string.Empty;

            var pioneerName = string.Format("{0} #{1}", currentProductionUnitOwner.pioneerCitizenName, currentProductionUnitOwner.pioneerCitizenNumber);

            obj.firstName     = currentProductionUnitOwner.pioneerCitizenName;
            obj.pioneerNumber = currentProductionUnitOwner.pioneerCitizenNumber.ToString();
            obj.callbackurl   = callbackUrl;

            List <EmailAddress> tos = new List <EmailAddress>
            {
                new EmailAddress(currentProductionUnitOwner.contactMail, pioneerName)
            };

            if (currentProductionUnitOwner != null && currentProductionUnitOwner.language != null)
            {
                switch (currentProductionUnitOwner.language.description)
                {
                case "fr":
                    currentTemplate = TemplatePasswordRecoveryFR;
                    break;

                case "en":
                    currentTemplate = TemplatePasswordRecoveryEN;
                    break;

                case "de":
                    currentTemplate = TemplatePasswordRecoveryDE;
                    break;

                default:
                    currentTemplate = TemplatePasswordRecoveryEN;
                    break;
                }
            }
            else
            {
                currentTemplate = TemplatePasswordRecoveryEN;
            }

            var msg = MailHelper.CreateSingleTemplateEmailToMultipleRecipients(from, tos, currentTemplate, obj);
            //msg.AddCc("*****@*****.**");
            var response = client.SendEmailAsync(msg);
        }
Exemple #7
0
        private void GenerateMidnightPunchEmails()
        {
            try
            {
                var instant       = SystemClock.Instance.GetCurrentInstant();
                var systemZone    = DateTimeZoneProviders.Tzdb.GetSystemDefault();
                var zonedDateTime = instant.InZone(systemZone);
                var localDateTime = zonedDateTime.LocalDateTime;

                var midnight = new DateTime(localDateTime.Year, localDateTime.Month, localDateTime.Day, 0, 0, 0);

                logger.LogInformation($"{midnight.ToShortDateString()} {midnight.ToShortTimeString()}");

                var connectionString = Environment.GetEnvironmentVariable("SqlContext").ToString();

                logger.LogInformation("Connecting to database");

                using (var connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    var organizationsSql = @"
                        SELECT
                            [O].[Id]
                        FROM
                            [Organizations] AS [O];";
                    var organizations    = connection.Query <Organization>(organizationsSql);

                    foreach (var organization in organizations)
                    {
                        // Collect the recipients for this Email.
                        var recipientsSql = @"
                            SELECT
                                [U].[Id],
                                [U].[Name],
                                [U].[EmailAddress]
                            FROM
                                [Users] AS [U]
                            WHERE
                                [U].[IsDeleted] = 0 AND
                                [U].[ShouldSendMidnightPunchEmail] = 1 AND
                                [U].[OrganizationId] = @OrganizationId;";
                        var recipients    = connection.Query <User>(recipientsSql, new
                        {
                            OrganizationId = organization.Id
                        });

                        // No need to continue if no one should receive the Email.
                        if (!recipients.Any())
                        {
                            continue;
                        }

                        // Find punches that were still open through last midnight.
                        var midnightPunchesSql = @"
                            SELECT
                                [U].[Name] AS [User_Name],

                                FORMAT([P].[InAt], 'ddd, MMM dd, yyyy h:mm tt') AS [Punch_InAt],

                                CASE
                                    WHEN [P].[OutAt] IS NOT NULL THEN FORMAT([P].[OutAt], 'ddd, MMM dd, yyyy h:mm tt')
                                    WHEN [P].[OutAt] IS NULL THEN 'STILL WORKING'
                                    ELSE 'STILL WORKING'
                                END AS [Punch_OutAt],

                                [T].[Number] AS [Task_Number],
                                [T].[Name] AS [Task_Name],

                                [J].[Number] AS [Project_Number],
                                [J].[Name] AS [Project_Name],

                                [C].[Number] AS [Customer_Number],
                                [C].[Name] AS [Customer_Name]
                            FROM
                                [Punches] AS [P]
                            JOIN
                                [Users] AS [U] ON [U].[Id] = [P].[UserId]
                            JOIN
                                [Tasks] AS [T] ON [T].[Id] = [P].[TaskId]
                            JOIN
                                [Jobs] AS [J] ON [J].[Id] = [T].[JobId]
                            JOIN
                                [Customers] AS [C] ON [C].[Id] = [J].[CustomerId]
                            WHERE
                                [P].[InAt] < @Midnight AND
                                ([P].[OutAt] > @Midnight OR [P].[OutAt] IS NULL) AND
                                [U].[IsDeleted] = 0 AND
                                [U].[OrganizationId] = @OrganizationId;";

                        var midnightPunches = connection.Query <MidnightPunch>(midnightPunchesSql, new
                        {
                            Midnight       = midnight,
                            OrganizationId = organization.Id
                        });

                        logger.LogInformation($"{midnightPunches.Count()} punches through midnight");

                        // Do not continue if there are no punches.
                        if (!midnightPunches.Any())
                        {
                            continue;
                        }

                        try
                        {
                            var tos = new List <EmailAddress>();
                            foreach (var recipient in recipients)
                            {
                                tos.Add(new EmailAddress()
                                {
                                    Email = recipient.EmailAddress, Name = recipient.Name
                                });
                            }

                            var apiKey     = Environment.GetEnvironmentVariable("SendGridApiKey").ToString();
                            var templateId = Environment.GetEnvironmentVariable("SendGridMidnightPunchTemplateId").ToString();

                            var dynamicTemplateData = new DynamicTemplateData()
                            {
                                MidnightPunches = midnightPunches.ToList()
                            };

                            var client   = new SendGridClient(apiKey);
                            var from     = new EmailAddress("BRIZBEE <*****@*****.**>");
                            var msg      = MailHelper.CreateSingleTemplateEmailToMultipleRecipients(from, tos, templateId, dynamicTemplateData);
                            var response = client.SendEmailAsync(msg);
                        }
                        catch (Exception ex)
                        {
                            logger.LogError(ex.Message);
                        }
                    }

                    connection.Close();
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
            }
        }
Exemple #8
0
        public static void PioneerUnitOfflineMessage(ProductionUnit currentProductionUnit)
        {
            var dbLog = new ApplicationDbContext();

            try
            {
                var client = new SendGridClient(MailSendGridAPIKey);
                var from   = new EmailAddress("*****@*****.**", "Myfood Hub Bot");

                MailTemplateObject obj = new MailTemplateObject();
                var currentTemplate    = string.Empty;

                if (currentProductionUnit.owner == null || currentProductionUnit.owner.contactMail == null || currentProductionUnit.owner.contactMail == string.Empty)
                {
                    dbLog.Logs.Add(Log.CreateLog(String.Format("Error with Mail Notification - Mail is missing for {0}", currentProductionUnit.info), Log.LogType.Information));
                    dbLog.SaveChanges();

                    return;
                }

                var pioneerName = string.Format("{0} #{1}", currentProductionUnit.owner.pioneerCitizenName, currentProductionUnit.owner.pioneerCitizenNumber);

                obj.firstName     = currentProductionUnit.owner.pioneerCitizenName;
                obj.pioneerNumber = currentProductionUnit.owner.pioneerCitizenNumber.ToString();
                obj.info          = currentProductionUnit.info;

                if (currentProductionUnit.productionUnitType.name.ToString().Contains("Family"))
                {
                    obj.isFamily = true;
                }
                else if (currentProductionUnit.productionUnitType.name.ToString().Contains("City"))
                {
                    obj.isFamily = false;
                }
                else
                {
                    obj.isFamily = true;
                }

                List <EmailAddress> tos = new List <EmailAddress>
                {
                    new EmailAddress(currentProductionUnit.owner.contactMail, pioneerName)
                };

                var subject     = string.Empty;
                var htmlContent = string.Empty;

                if (currentProductionUnit.owner != null && currentProductionUnit.owner.language != null)
                {
                    switch (currentProductionUnit.owner.language.description)
                    {
                    case "fr":
                        currentTemplate = TemplateGreehouseOfflineFR;
                        break;

                    case "en":
                        currentTemplate = TemplateGreehouseOfflineEN;
                        break;

                    case "de":
                        currentTemplate = TemplateGreehouseOfflineDE;
                        break;

                    default:
                        currentTemplate = TemplateGreehouseOfflineEN;
                        break;
                    }
                }
                else
                {
                    currentTemplate = TemplateGreehouseOfflineEN;
                }

                var msg = MailHelper.CreateSingleTemplateEmailToMultipleRecipients(from, tos, currentTemplate, obj);
                //msg.AddCc("*****@*****.**");
                var response = client.SendEmailAsync(msg);
            }
            catch (Exception ex)
            {
                dbLog.Logs.Add(Log.CreateErrorLog(String.Format("Error with Mail Notification"), ex));
                dbLog.SaveChanges();
            }
        }
Exemple #9
0
        public static void PioneerUnitWeeklyMessage(ProductionUnit currentProductionUnit, List <RecommandationTemplaceObject> reco)
        {
            var db    = new ApplicationDbContext();
            var dbLog = new ApplicationDbContext();

            var infoEventType = db.EventTypes.Where(p => p.Id == 8).FirstOrDefault();

            try
            {
                var client = new SendGridClient(MailSendGridAPIKey);
                var from   = new EmailAddress("*****@*****.**", "Myfood Hub Bot");

                MailTemplateObject obj = new MailTemplateObject();
                var currentTemplate    = string.Empty;

                if (currentProductionUnit.owner == null || currentProductionUnit.owner.contactMail == null || currentProductionUnit.owner.contactMail == string.Empty)
                {
                    dbLog.Logs.Add(Log.CreateLog(String.Format("Error with Mail Notification - Mail is missing for {0}", currentProductionUnit.info), Log.LogType.Information));
                    dbLog.SaveChanges();

                    return;
                }

                var pioneerName = string.Format("{0} #{1}", currentProductionUnit.owner.pioneerCitizenName, currentProductionUnit.owner.pioneerCitizenNumber);

                obj.firstName     = currentProductionUnit.owner.pioneerCitizenName;
                obj.pioneerNumber = currentProductionUnit.owner.pioneerCitizenNumber.ToString();
                obj.info          = currentProductionUnit.info;

                if (currentProductionUnit.productionUnitType.name.ToString().Contains("Family"))
                {
                    obj.isFamily = true;
                }
                else
                {
                    obj.isFamily = false;
                }

                obj.recommandations = reco.OrderBy(r => r.order).ToList();

                if (obj.recommandations.Count > 0)
                {
                    obj.hasRecommandation = true;
                }
                else
                {
                    obj.hasRecommandation = false;

                    //var content = String.Format("",null);

                    //db.Events.Add(new Event() { date = DateTime.Now, description = content, isOpen = false, productionUnit = currentProductionUnit, eventType = infoEventType, createdBy = "MyFood Bot" });
                    //db.SaveChanges();
                }


                List <EmailAddress> tos = new List <EmailAddress>
                {
                    new EmailAddress(currentProductionUnit.owner.contactMail, pioneerName)
                };

                var subject     = string.Empty;
                var htmlContent = string.Empty;

                if (currentProductionUnit.owner != null && currentProductionUnit.owner.language != null)
                {
                    switch (currentProductionUnit.owner.language.description)
                    {
                    case "fr":
                        currentTemplate = TemplateWeeklyMessageFR;
                        break;

                    case "en":
                        currentTemplate = TemplateWeeklyMessageEN;
                        break;

                    case "de":
                        currentTemplate = TemplateWeeklyMessageDE;
                        break;

                    default:
                        currentTemplate = TemplateWeeklyMessageEN;
                        break;
                    }
                }
                else
                {
                    currentTemplate = TemplateGreehouseOfflineEN;
                }

                var msg = MailHelper.CreateSingleTemplateEmailToMultipleRecipients(from, tos, currentTemplate, obj);
                //msg.AddCc("*****@*****.**");
                var response = client.SendEmailAsync(msg);
            }
            catch (Exception ex)
            {
                dbLog.Logs.Add(Log.CreateErrorLog(String.Format("Error with Mail Notification"), ex));
                dbLog.SaveChanges();
            }
        }