예제 #1
0
        // Odosielanie emailu o tom, ze bola vytvorena aktivita
        private void SendActivityCreated(List <EmailAddress> mails, Activity activity, string link)
        {
            try
            {
                //Kontrola ci je mozne odoslat email
                if (string.IsNullOrEmpty(currUser.ApiKey))
                {
                    return;
                }

                EmailClient             client  = new EmailClient();
                string                  content = string.Empty;
                SendGrid.SendGridClient gridClient;
                if (!string.IsNullOrEmpty(link))
                {
                    gridClient = new SendGrid.SendGridClient(client.SetEnvironmentVar(currUser));
                    content    = $"Milí študenti, <br/> dňa {DateTime.Now.Date + DateTime.Now.TimeOfDay} Vám bola vytvorená aktivita {activity.ActivityName}," +
                                 $" <br/> ktorú je potrebné odovzdať do {activity.Deadline} <br/> {link}";
                }
                else
                {
                    gridClient = new SendGrid.SendGridClient(client.SetEnvironmentVar(currUser));
                    content    = $"Milí študenti, <br/> dňa {DateTime.Now.Date + DateTime.Now.TimeOfDay} Vám bola vytvorená aktivita {activity.ActivityName}," +
                                 $" <br/> ktorú je potrebné odovzdať do {activity.Deadline}";
                }

                EmailBody body = new EmailBody()
                {
                    HtmlContent      = content,
                    PlainTextContent = content,
                    To      = mails,
                    Subject = "Nová aktivita"
                };
                //Vytvorenie obsahu emailu, ktorym oznamujeme studentom, ze im bolo vytvorene hodnotenie a jeho nasledne odoslanie

                var msg = MailHelper.CreateSingleEmailToMultipleRecipients(MailHelper.StringToEmailAddress(currUser.Email), body.To, body.Subject, body.HtmlContent, body.HtmlContent);
                gridClient.SendEmailAsync(msg);

                Logger logger = new Logger();
                logger.LogEmail(DateTime.Now, body.To, body.Subject, body.HtmlContent, null);
            }
            catch (Exception ex)
            {
                Logger logger = new Logger();
                logger.LogError(ex);
                MessageBox.Show("Pri odosielaní emailu nastal problém.");
            }
        }
        private async void SendActivityCreated(List <EmailAddress> mails, Activity activity, string link)
        {
            EmailClient client  = new EmailClient();
            string      content = string.Empty;

            SendGrid.SendGridClient gridClient;
            if (!string.IsNullOrEmpty(link))
            {
                gridClient = new SendGrid.SendGridClient(client.SetEnvironmentVar(currUser));
                content    = $"Dobrý deň {activity.Student.Meno}, <br/> dňa {DateTime.Now.Date + DateTime.Now.TimeOfDay} Vám bola vytvorená aktivita {activity.ActivityName}," +
                             $" <br/> ktorú je potrebné odovzdať do {activity.Deadline} <br/> {link}";
            }
            else
            {
                gridClient = new SendGrid.SendGridClient(client.SetEnvironmentVar(currUser));
                content    = $"Dobrý deň {activity.Student.Meno}, <br/> dňa {DateTime.Now.Date + DateTime.Now.TimeOfDay} Vám bola vytvorená aktivita {activity.ActivityName}," +
                             $" <br/> ktorú je potrebné odovzdať do {activity.Deadline}";
            }

            EmailBody body = new EmailBody()
            {
                HtmlContent      = content,
                PlainTextContent = content,
                To      = mails,
                Subject = "Nová aktivita"
            };

            var msg = MailHelper.CreateSingleEmailToMultipleRecipients(MailHelper.StringToEmailAddress(currUser.Email), body.To, body.Subject, body.HtmlContent, body.HtmlContent);

            var response = await gridClient.SendEmailAsync(msg);

            if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                Logger logger = new Logger();
                logger.LogEmail(DateTime.Now, body.To, body.Subject, body.HtmlContent, null);
            }
        }
예제 #3
0
        private async Task <Response> SendEmails(EmailTemplate emailTemplate, int numberOfDays, List <EmailAddress> emailAddresses, User user, DateTime date)
        {
            try
            {
                EmailClient    eClient = new EmailClient();
                SendGridClient client  = new SendGridClient(eClient.SetEnvironmentVar(user));
                List <SendGrid.Helpers.Mail.Attachment> attachmentList = new List <SendGrid.Helpers.Mail.Attachment>();
                EmailAttachments emailAttachments = new EmailAttachments();
                EmailBody        body             = new EmailBody()
                {
                    /// HtmlContent je celkovo obsah emailu, <br/> je nutne pridat kvoli tomu, aby email obsahoval nove riadky. Na konci je priadnie
                    /// emailoveho podpisu.
                    HtmlContent = emailTemplate.EmailContent.Replace("\u00A0", "<br/>") + "<br/> <br/> " + user.Signature.Replace("\u00A0", "<br/>"),
                    Subject     = emailTemplate.EmailSubject,
                    To          = emailAddresses
                };

                using (StudentDBDataContext con = new StudentDBDataContext(conn_str))
                {
                    var attachments = con.GetTable <Attachment>().Where(x => x.IdUser == user.Id && x.IdEmailTemplate == emailTemplate.Id);

                    foreach (var files in attachments)
                    {
                        /// Zistovanie, ci subor, ktoreho cestu budeme brat z DB vobec existuje
                        if (File.Exists(files.FilePath))
                        {
                            var bytes = File.ReadAllBytes(files.FilePath);
                            var file  = Convert.ToBase64String(bytes);
                            // Ziskanie typu suboru, aby mohol byt uploadnuty
                            var type = emailAttachments.GetMIMEType(files.FilePath);

                            /// Pridanie prilohy,
                            SendGrid.Helpers.Mail.Attachment attachment = new SendGrid.Helpers.Mail.Attachment()
                            {
                                Content  = file,
                                Filename = (string)files.FileName,
                                Type     = type
                            };
                            attachmentList.Add(attachment);
                        }
                        else
                        {
                            continue;
                        }
                    }
                }

                /// Vytvorenie emailu pre viacero prijemcov
                var msg = MailHelper.CreateSingleEmailToMultipleRecipients(MailHelper.StringToEmailAddress(user.Email), body.To, body.Subject, body.HtmlContent, body.HtmlContent);

                // Dates je premenna, ktora urcuje o kolko dni skor ma byt odoslana sprava
                var dates = date.AddDays(-numberOfDays);
                // Prevod z datumu do Unix sekund ( Sendgrid takto akceptuje parameter SendAt
                var unixDate = new DateTimeOffset(dates.Year, dates.Month, dates.Day, dates.Hour, dates.Minute, dates.Second, TimeSpan.Zero).ToUnixTimeSeconds();
                /// Minus jedna hodina kvoli casovemu posunu Web API
                msg.SetSendAt((int)unixDate - 3600);
                if (attachmentList.Count >= 1)
                {
                    // Pridanie priloh do tela emailu
                    msg.AddAttachments(attachmentList);
                }
                Logger newLog = new Logger();

                newLog.LogEmail(date, body.To, body.Subject, body.HtmlContent, attachmentList);
                // asynchronne odoslanie poziadavky na web api
                var result = await client.SendEmailAsync(msg);

                attachmentList.Clear();
                emailAddresses.Clear();
                return(result);
            }
            catch (Exception ex)
            {
                Logger newLog = new Logger();
                newLog.LogError(ex);
                MessageBox.Show(ex.ToString());
                return(null);
            }
        }
        private async void OdoslatBtnSendForm_Click(object sender, EventArgs e)
        {
            try
            {
                Logger      logger  = new Logger();
                EmailClient eClient = new EmailClient();
                if (string.IsNullOrEmpty(currentUser.ApiKey))
                {
                    MessageBox.Show("ApiKey nemôže byť prázdny.");
                    return;
                }
                SendGridClient client = new SendGridClient(eClient.SetEnvironmentVar(currentUser));
                EmailBody      body   = new EmailBody()
                {
                    HtmlContent      = richTextBox1.Text.Replace("\u00A0", "<br/>") + "<br/> <br/> " + currentUser.Signature.Replace("\u00A0", "<br/>"),
                    PlainTextContent = richTextBox1.Text,
                    Subject          = subjectTextBox.Text,
                    To = emailAddList
                };

                if (body.Subject != string.Empty && body.PlainTextContent != string.Empty && emailAddList != null)
                {
                    if (SelectAllBtnPrimaryEmail.Checked == true && SelectAllSecondaryEmail.Checked == false && GroupCheckBtn.Checked == false)
                    {
                        using (StudentDBDataContext con = new StudentDBDataContext(conn_str))
                        {
                            emailAddList.Clear();
                            var students = con.GetTable <Student>();
                            var skup     = from student in students where student.ID_stud_skupina == currentGroup.Id select student.Email;

                            foreach (var mail in skup)
                            {
                                emailAddList.Add(MailHelper.StringToEmailAddress(RWS(mail)));
                            }
                        }
                    }
                    else if (SelectAllBtnPrimaryEmail.Checked == false && SelectAllSecondaryEmail.Checked == true && GroupCheckBtn.Checked == false)
                    {
                        using (StudentDBDataContext con = new StudentDBDataContext(conn_str))
                        {
                            emailAddList.Clear();
                            var students = con.GetTable <Student>();
                            var skup     = from student in students where student.ID_stud_skupina == currentGroup.Id select student.Email_UCM;

                            foreach (var mail in skup)
                            {
                                emailAddList.Add(MailHelper.StringToEmailAddress(RWS(mail)));
                            }
                        }
                    }
                    else if (SelectAllBtnPrimaryEmail.Checked == false && SelectAllSecondaryEmail.Checked == false && GroupCheckBtn.Checked == true)
                    {
                        using (StudentDBDataContext con = new StudentDBDataContext(conn_str))
                        {
                            emailAddList.Clear();
                            var students = con.GetTable <Student>();
                            var skup     = from student in students
                                           where student.ID_stud_skupina == currentGroup.Id && student.ID_Kruzok == GroupComboEmail.Text
                                           select student.Email;

                            foreach (var mail in skup)
                            {/// Nastavene na osobny email
                                emailAddList.Add(MailHelper.StringToEmailAddress(RWS(mail)));
                            }
                        }
                    }
                    else
                    {
                        emailAddList.Clear();
                        ToTextBox.Text.Replace(" ", string.Empty);
                        var splitted = ToTextBox.Text.Split(',');
                        splitted.ToList();


                        foreach (var mail in splitted)
                        {
                            emailAddList.Add(MailHelper.StringToEmailAddress(RWS(mail)));
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Niektorá časť nie je vyplnená. Prosím skontrolujte správu, ktorú chcete odoslať a uistite sa subjekt alebo správa nie sú prázdne", "Prázdne polia");
                    return;
                }
                var msg = MailHelper.CreateSingleEmailToMultipleRecipients(MailHelper.StringToEmailAddress(currentUser.Email), body.To, body.Subject, body.HtmlContent, body.HtmlContent);
                if (attachmentList.Count >= 1)
                {
                    msg.AddAttachments(attachmentList);
                }
                var result = await client.SendEmailAsync(msg);

                if (result.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    logger.LogEmail(DateTime.Now, body.To, body.Subject, body.HtmlContent, attachmentList);
                    attachmentList.Clear();
                    MessageBox.Show("Email bol úspešne prijatý", "Status");
                }
                else
                {
                    MessageBox.Show("Email nebol úspešne odoslaný\n " + "Status emailu: " + result.StatusCode.ToString(), "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }


                ToTextBox.Text             = "";
                subjectTextBox.Text        = "";
                richTextBox1.Text          = "";
                AttachmentsGrid.DataSource = null;
                emailAddList.Clear();
            }
            catch (Exception ex)
            {
                Logger newLog = new Logger();
                newLog.LogError(ex);
                MessageBox.Show(ex.Message);
            }
        }