private void SetEmailFields(EmailTemplate emailTemplate, SendGridMessage sendGridMessage)
        {
            if (emailTemplate.ListRecipients == null)
            {
                Log.Warn($"{this.GetCallingClassAndMethod()} List of email recipients was null - this suggests that something is not working as it should.");
            }
            else
            {
                foreach (var recipient in emailTemplate.ListRecipients)
                {
                    sendGridMessage.AddTo(recipient.Trim());
                }
            }

            if (emailTemplate.ListCopyRecipients != null)
            {
                foreach (var copyRecipient in emailTemplate.ListCopyRecipients)
                {
                    sendGridMessage.AddCc(copyRecipient.Trim());
                }
            }

            if (emailTemplate.ListBlindCopyRecipients != null)
            {
                foreach (var blindCopyRecipient in emailTemplate.ListBlindCopyRecipients)
                {
                    sendGridMessage.AddCc(blindCopyRecipient.Trim());
                }
            }

            sendGridMessage.Subject     = emailTemplate.EmailSubject.Trim();
            sendGridMessage.HtmlContent = emailTemplate.EmailHtmlBody;
        }
Exemplo n.º 2
0
        public async Task SendApplicationConfirmAsync(ApplicationView application)
        {
            var client = new SendGridClient(AlternateSendgridApiKey);

            List <string> occurrenceStrings = application.OccurrenceViews
                                              .Select(o => ToOccurrenceTimeString().Invoke(o))
                                              .ToList();

            var content = $"<p>Received application: {application.GetEmailMessage()}</p>" +
                          $"<p>{application.OpportunityDescription}</p>" +
                          $"<p><b>Address: {application.OpportunityAddress}</b></p>" +
                          $"<p><b>Times: <p>{string.Join("</p><p>", occurrenceStrings)}</p></b></p>" +
                          $"";
            SendGridMessage sendGridMessage = new SendGridMessage()
            {
                From             = new EmailAddress(FromEmail, "Volly Team"),
                Subject          = "Application For: " + application.OpportunityName,
                HtmlContent      = content,
                PlainTextContent = content
            };

            sendGridMessage.AddTo(new EmailAddress(application.Email, application.Name));
            sendGridMessage.AddCc(new EmailAddress(VollyConstants.AliceEmail, "Alice"));
            sendGridMessage.AddCc(new EmailAddress(VollyConstants.VollyAdminEmail, "VollyAdmin"));

            await client.SendEmailAsync(sendGridMessage);
        }
Exemplo n.º 3
0
        public async Task SendEmailWithAttachmentsAsync(List <string> to, string subject,
                                                        string body, List <EmailAttachment> attachments, string bcc = null, string cc = null)
        {
            SendGridMessage myMessage = new SendGridMessage();

            foreach (var toMail in to)
            {
                myMessage.AddTo(new EmailAddress(toMail));
            }
            if (!string.IsNullOrEmpty(bcc))
            {
                myMessage.AddCc(new EmailAddress(bcc));
            }
            if (!string.IsNullOrEmpty(cc))
            {
                myMessage.AddCc(new EmailAddress(cc));
            }

            myMessage.From        = new EmailAddress(_sendGridConfigure.FromEmail, _sendGridConfigure.FromName);
            myMessage.Subject     = subject;
            myMessage.HtmlContent = body;
            foreach (var attachment in attachments)
            {
                var bytes = await ReadFully(attachment.Attachment);

                myMessage.AddAttachment(attachment.FileName, Convert.ToBase64String(bytes));
            }
            var client = new SendGridClient(_sendGridConfigure.ApiKey);
            // Create a Web transport, using API Key
            await client.SendEmailAsync(myMessage);
        }
Exemplo n.º 4
0
        public async Task <string> SendMI4DEmail(MyEmails email)
        {
            SendGridClient client = new SendGridClient(_connectionStrings.Value.SendGrid);

            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress("*****@*****.**", "Suporte MI3D Plus"));
            msg.SetSubject(email.Subject);
            msg.AddContent(MimeType.Html, email.Body);
            msg.AddTo(new EmailAddress(email.To.First().Address, email.To.First().DisplayName));

            if (email.To.First().Address != "*****@*****.**")
            {
                msg.AddCc(new EmailAddress("*****@*****.**", "Carlos de Souza"));
            }

            if (email.To.First().Address != "*****@*****.**")
            {
                msg.AddCc(new EmailAddress("*****@*****.**", "Ricardo Gaefke"));
            }

            var response = await client.SendEmailAsync(msg);

            return(response.Headers.GetValues("x-message-id").FirstOrDefault());
        }
Exemplo n.º 5
0
        public Task SendEmailWithAttachmentsAsync(List <string> to, string bcc, string cc, string subject, string body, List <AttachmentModel> attachments)
        {
            SendGridMessage myMessage = new SendGridMessage();

            myMessage.AddTo(to);
            if (!string.IsNullOrEmpty(bcc))
            {
                myMessage.AddCc(bcc);
            }
            if (!string.IsNullOrEmpty(cc))
            {
                myMessage.AddCc(cc);
            }

            myMessage.From    = new MailAddress(FromEmail, FromName);
            myMessage.Subject = (Environment != null? $"{Environment}_{subject}":subject);
            myMessage.Html    = body;
            foreach (var attachment in attachments)
            {
                if (string.IsNullOrEmpty(Environment))
                {
                    myMessage.AddAttachment(attachment.Stream, attachment.Name);
                }
                else
                {
                    myMessage.AddAttachment(attachment.Stream, $"{Environment}_{attachment.Name}");
                }
            }
            // Create a Web transport, using API Key
            var transportWeb = new Web(ApiKey);

            // Send the email.
            return(transportWeb.DeliverAsync(myMessage));
        }
        public static void SendEmail()
        {
            try
            {
                count++;


                var apiKey = "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";

                var client = new SendGridClient(apiKey);
                var msg    = new SendGridMessage()
                {
                    From             = new EmailAddress("*****@*****.**", "Email Count '" + count.ToString() + "' Congratulation for job interview"),
                    Subject          = "Email Count '" + count.ToString() + "' Congratulation for job interview. Modified for autodeployment from GitHub",
                    PlainTextContent = "Hello, Email!",
                    HtmlContent      = "Hello Sir,<br/>You are selected for final round of interview. Please be present at 11:00AM with original documents. </br><br/>Thanks</br>HR- Allscript"
                };

                msg.AddCc(new EmailAddress("*****@*****.**", "Devendra Choudhary"));
                //msg.AddBcc(new EmailAddress("*****@*****.**", "Shyam Vin"));
                msg.AddCc(new EmailAddress("*****@*****.**", "Jenit Vagashiya"));
                //msg.AddTo(new EmailAddress("*****@*****.**", "Test User2"));

                /*
                 * Byte[] bytes = System.IO.File.ReadAllBytes(@"wwwroot\DataFiles\Emploment 2.jpg");
                 * String content = Convert.ToBase64String(bytes);
                 * msg.AddAttachment("Emploment 2.jpg", content, "image/jpg", "inline", "Banner 2");
                 *
                 * bytes = null;
                 * bytes = System.IO.File.ReadAllBytes(@"wwwroot\DataFiles\Leadership Training.docx");
                 * if (bytes != null)
                 * {
                 *  String content1 = Convert.ToBase64String(bytes);
                 *  msg.AddAttachment("Leadership Training.docx", content1, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "inline", "Leadership Training");
                 * }
                 */

                client.SendEmailAsync(msg).Wait();


                Console.WriteLine("Email sent successfully");
                System.Threading.Thread.Sleep(30000);
                SendEmail();
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }
Exemplo n.º 7
0
        public static void Send(string sender, string[] tolist, string[] ccList, string[] bccList, string subject, string body, bool iSJob = false)
        {
            try
            {
                var message = new SendGridMessage
                {
                    From = new MailAddress(Utils.GetSetting(MAIL_SENDER, ""), Utils.GetSetting(MAIL_USER, ""), Encoding.UTF8)
                };

                message.AddTo(tolist);
                message.AddCc(ccList);
                message.AddBcc(bccList);
                message.Subject = subject;
                message.Html    = body;

                //var credentials = new NetworkCredential("ssp_system_admin", "Asdcvnmmvb");
                var credentials = new NetworkCredential(Utils.GetSetting(MAIL_USER, "ssp_system_admin"), Utils.GetSetting(MAIL_PASSWORD, "Asdcvnmmvb"));
                // Create a Web transport for sending email.
                var transportWeb = new SendGrid.Web(credentials);
                if (iSJob)
                {
                    transportWeb.DeliverAsync(message).Wait();
                }
                else
                {
                    transportWeb.DeliverAsync(message);
                }
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 8
0
        public async Task <Response> Send(EmailMessageInfo messageInfo)
        {
            // Prepare the SendGrid email message
            var sendgridMessage = new SendGridMessage
            {
                From        = new EmailAddress(messageInfo.FromEmailAddress),
                Subject     = messageInfo.EmailSubject,
                HtmlContent = messageInfo.EmailBody
            };

            // Add the "To" email address to the message
            sendgridMessage.AddTo(new EmailAddress(messageInfo.ToEmailAddress));

            // Check if any Cc email address was specified
            if (!string.IsNullOrWhiteSpace(messageInfo.CcEmailAddress))
            {
                // Add the email address for Cc to the message
                sendgridMessage.AddCc(new EmailAddress(messageInfo.CcEmailAddress));
            }

            // Check if any Bcc email address was specified
            if (!string.IsNullOrWhiteSpace(messageInfo.BccEmailAddress))
            {
                // Add the email address for Bcc to the message
                sendgridMessage.AddBcc(new EmailAddress(messageInfo.BccEmailAddress));
            }

            // Send the message to SendGrid, and save the API response
            var response = await _client.SendEmailAsync(sendgridMessage);

            // Return the SendGrid response
            return(response);
        }
Exemplo n.º 9
0
        public static void SkickaFaktura(string message, string hostAddress, string link, FakturaVM fakturaVm)
        {
            try
            {
                message = message.Replace("href=\"/", string.Format("href=\"{0}", hostAddress));
                message = message.Replace("src=\"/", string.Format("src=\"{0}", hostAddress));
                message = message.Replace("<html>", string.Format("<html>Ser meddelandet konstigt ut? Öppna följande adress i en webbläsare: {0}<br/><br/>", link));

                var arrEpost = new MailAddress(fakturaVm.Arrangor.Epost, fakturaVm.Arrangor.Namn);
                // Create the email object first, then add the properties.
                SendGridMessage myMessage = new SendGridMessage();
                myMessage.AddTo(fakturaVm.Registrering.Epost);
                myMessage.AddCc(arrEpost);
                myMessage.From    = arrEpost;
                myMessage.Subject = string.Format("Faktura för anmälan till " + fakturaVm.Evenemangsnamn);
                myMessage.Html    = message;
                myMessage.Text    = "Följ länken för faktura på din anmälan: " + link;

                // Create credentials, specifying your user name and password.
                var credentials = new NetworkCredential(ConfigurationManager.AppSettings["SendGridUser"], ConfigurationManager.AppSettings["SendGridPwd"]);

                // Create an Web transport for sending email.
                var transportWeb = new Web(credentials);

                // Send the email.
                // You can also use the **DeliverAsync** method, which returns an awaitable task.
                transportWeb.DeliverAsync(myMessage);
            }
            catch (Exception exc)
            {
                ILog log = LogManager.GetLogger("SendMail");
                log.Error("Fel vid skickande av mail.", exc);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        ///  Sends out an email from the application. Returns true if successful.
        /// </summary>
        public static bool SendGridEmail(string from, List <string> to, List <string> cc, List <string> bcc, string subj, string body, string smtpUser, string smtpUserPwd)
        {
            try
            {
                //******************** CONSTRUCT EMAIL ********************************************
                // Create the email object first, then add the properties.
                var myMessage = new SendGridMessage();

                // Add message properties.
                myMessage.From = new MailAddress(from);
                myMessage.AddTo(to);
                if (cc != null)
                {
                    foreach (string cc1 in cc)
                    {
                        myMessage.AddCc(cc1);
                    }
                }
                if (bcc != null)
                {
                    foreach (string bcc1 in bcc)
                    {
                        myMessage.AddBcc(bcc1);
                    }
                }

                myMessage.Subject = subj;
                //myMessage.Html = "<p>" + body + "</p>";
                myMessage.Text = body;
                //*********************************************************************************


                //********************* SEND EMAIL ************************************************
                var credentials = new NetworkCredential(smtpUser, smtpUserPwd);
                // Create an Web transport for sending email.
                var transportWeb = new Web(credentials);

                // Send the email.
                transportWeb.Deliver(myMessage);

                return(true);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    db_Ref.InsertT_OE_SYS_LOG("EMAIL ERR", ex.InnerException.ToString());
                }
                else if (ex.Message != null)
                {
                    db_Ref.InsertT_OE_SYS_LOG("EMAIL ERR", ex.Message.ToString());
                }
                else
                {
                    db_Ref.InsertT_OE_SYS_LOG("EMAIL ERR", "Unknown error");
                }

                return(false);
            }
        }
        /// <summary>
        /// Sends out an email using SendGrid.
        /// Note: Updated to work with SendGrid version 9.8
        /// </summary>
        /// <returns>true if successful</returns>
        public async Task <bool> SendEmailUsingSendGrid(string from, string to, List <string> cc, List <string> bcc, string subj, string body, string apiKey)
        {
            try
            {
                var client = new SendGridClient(apiKey);

                //******************** CONSTRUCT EMAIL ********************************************
                var msg = new SendGridMessage()
                {
                    From    = new EmailAddress(from),
                    Subject = subj
                };

                msg.AddContent(MimeType.Html, body);
                msg.AddTo(new EmailAddress(to));

                foreach (string cc1 in cc ?? Enumerable.Empty <string>())
                {
                    msg.AddCc(cc1);
                }

                foreach (string bcc1 in bcc ?? Enumerable.Empty <string>())
                {
                    msg.AddBcc(bcc1);
                }


                // Disable click tracking. See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
                msg.TrackingSettings = new TrackingSettings
                {
                    ClickTracking = new ClickTracking {
                        Enable = false
                    }
                };

                //******************** SEND EMAIL ****************************************************
                var response = await client.SendEmailAsync(msg).ConfigureAwait(false);


                //******************** RETURN RESPONSE ***********************************************
                if (response.StatusCode == HttpStatusCode.Accepted)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
                //************************************************************************************
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    _log.LogEFException(ex);
                }

                return(false);
            }
        }
Exemplo n.º 12
0
        public static SendGridMessage ToSendGridMessage(this IMessage message)
        {
            var sgMessage = new SendGridMessage
            {
                From    = new EmailAddress(message.From.PrettyEmail(message.FromName)),
                Subject = message.Subject,
            };

            foreach (var address in message.ToAddress)
            {
                sgMessage.AddTo(address);
            }

            foreach (var address in message.Cc)
            {
                sgMessage.AddCc(address);
            }

            foreach (var address in message.Bcc)
            {
                sgMessage.AddBcc(address);
            }

            if (!string.IsNullOrEmpty(message.Html))
            {
                sgMessage.HtmlContent = message.Html;
            }

            if (!string.IsNullOrEmpty(message.Text))
            {
                sgMessage.PlainTextContent = message.Text;
            }

            return(sgMessage);
        }
 public void Send(Context context)
 {
     Task.Run(() =>
     {
         try
         {
             var sendGridMessage  = new SendGridMessage();
             sendGridMessage.From = new EmailAddress(Addresses.From(From).Address, Addresses.From(From).DisplayName);
             Addresses.GetEnumerable(
                 context: context,
                 addresses: To)
             .ForEach(to => sendGridMessage.AddTo(to));
             Addresses.GetEnumerable(
                 context: context,
                 addresses: Cc)
             .ForEach(cc => sendGridMessage.AddCc(cc));
             Addresses.GetEnumerable(
                 context: context,
                 addresses: Bcc)
             .ForEach(bcc => sendGridMessage.AddBcc(bcc));
             sendGridMessage.Subject          = Subject;
             sendGridMessage.PlainTextContent = Body;
             var client   = new SendGridClient(Parameters.Mail.ApiKey);
             var response = client.SendEmailAsync(sendGridMessage);
             response.Wait();
         }
         catch (Exception e)
         {
             new SysLogModel(Context, e);
         }
     });
 }
        public SentStatus Send(string to, string subject, string message, string[] cc, string[] bcc, byte[] attachment, string attachmentname, string replyto)
        {
            bool   status;
            string responseMesage = string.Empty;

            try
            {
                SendGridMessage msg = new SendGridMessage
                {
                    From             = new EmailAddress(Config.EmailAddress, Config.Name),
                    Subject          = subject,
                    PlainTextContent = message,
                    ReplyTo          = new EmailAddress(replyto)
                };
                msg.AddTo(new EmailAddress(to, "User"));
                foreach (string i in cc)
                {
                    msg.AddBcc(new EmailAddress(i));
                }
                foreach (string i in bcc)
                {
                    msg.AddCc(new EmailAddress(i));
                }
                if (attachment != null)
                {
                    var file = Convert.ToBase64String(attachment);
                    msg.AddAttachment(attachmentname, file);
                }
                Client.SendEmailAsync(msg);
                responseMesage = "SendGrid Send success";
                status         = true;
            }
            catch (Exception e)
            {
                responseMesage = "SendGrid Send Exception" + e.Message + e.StackTrace;
                status         = false;
            }
            var        plainTextBytes = Encoding.UTF8.GetBytes(message);
            string     message64      = Convert.ToBase64String(plainTextBytes);
            SentStatus SentStatus     = new SentStatus
            {
                Status     = status.ToString(),
                To         = to,
                From       = Config.EmailAddress,
                Body       = message64,
                ConId      = Config.Id,
                Result     = responseMesage,
                Recepients = new EmailRecepients
                {
                    To      = to,
                    Cc      = (cc == null) ? "" : string.Join(",", cc),
                    Bcc     = (bcc == null) ? "" : string.Join(",", bcc),
                    Replyto = (replyto == null) ? "" : replyto,
                },
                Subject        = subject,
                AttachmentName = attachmentname
            };

            return(SentStatus);
        }
Exemplo n.º 15
0
        public static SendGridMessage CreateMessage(string subject, string body, string from, string fromName, string to, string cc)
        {
            if (string.IsNullOrWhiteSpace(to))
            {
                throw new ArgumentException($"Invalid argument: {nameof(to)}");
            }
            if (string.IsNullOrWhiteSpace(from))
            {
                throw new ArgumentException($"Invalid argument: {nameof(from)}");
            }
            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException($"Invalid argument: {nameof(subject)}");
            }
            if (string.IsNullOrWhiteSpace(body))
            {
                throw new ArgumentException($"Invalid argument: {nameof(body)}");
            }

            var message = new SendGridMessage();

            message.Subject = subject;
            message.Html    = body;
            message.From    = new MailAddress(from, fromName);
            message.AddTo(to.Trim().Trim(',').Replace(';', ',').Split(',').Distinct().Where(e => !string.IsNullOrWhiteSpace(e)));
            if (!string.IsNullOrWhiteSpace(cc))
            {
                message.AddCc(cc);
            }

            logger.Info($"SendGrid Email: Email From: {fromName}<{from}> To:{to} Subject:{subject}");
            return(message);
        }
Exemplo n.º 16
0
        public async Task <Response> Execute(string apiKey, string subject, string message, List <string> to, List <string> cc)
        {
            apiKey = Environment.GetEnvironmentVariable("SENDEMAILDEMO_ENVIRONMENT_SENDGRID_KEY");
            var client = new SendGridClient(apiKey);
            var msg    = new SendGridMessage()
            {
                From             = new EmailAddress("*****@*****.**", "Benignus Okorie"),
                Subject          = subject,
                PlainTextContent = message,
                HtmlContent      = message
            };

            foreach (var t in to)
            {
                msg.AddTo(new EmailAddress(t));
            }

            foreach (var c in cc)
            {
                msg.AddCc(new EmailAddress(c));
            }

            var response = await client.SendEmailAsync(msg);

            return(response);
        }
        private static SendGridMessage ConvertToSendGridMessage(MailMessage message)
        {
            var sgMessage =
                new SendGridMessage {
                From = new EmailAddress(message.From.Address, message.From.DisplayName)
            };

            foreach (var addressTo in message.To)
            {
                sgMessage.AddTo(new EmailAddress(addressTo.Address));
            }

            foreach (var addressCc in message.CC)
            {
                sgMessage.AddCc(new EmailAddress(addressCc.Address));
            }

            foreach (var addressBcc in message.Bcc)
            {
                sgMessage.AddBcc(new EmailAddress(addressBcc.Address));
            }

            sgMessage.Subject = message.Subject;

            if (message.AlternateViews.Count > 0)
            {
                foreach (var view in message.AlternateViews)
                {
                    if (view.ContentStream.CanSeek)
                    {
                        view.ContentStream.Position = 0;
                    }

                    var reader = new StreamReader(view.ContentStream);

                    switch (view.ContentType.MediaType)
                    {
                    case MediaTypeNames.Text.Html:
                        sgMessage.HtmlContent = reader.ReadToEnd();
                        break;

                    case MediaTypeNames.Text.Plain:
                        sgMessage.PlainTextContent = reader.ReadToEnd();
                        break;
                    }
                }
            }

            foreach (var attachment in message.Attachments)
            {
                sgMessage.AddAttachment(attachment.Name, ConvertToBase64(attachment.ContentStream),
                                        attachment.ContentType.MediaType);
            }

            return(sgMessage);
        }
Exemplo n.º 18
0
        public async Task SendEmailAsync(MailAddress[] toEmail, string subject, string htmlBody, MailAddress fromEmailAsCc = null, string attachmentName = null, MemoryStream attachmentStream = null)
        {
            var mail = new SendGridMessage();

            mail.From = new EmailAddress(DefaultFromEmail);

            if (toEmail == null || toEmail.Length < 1)
            {
                throw new Exception("At least one to email is required.");
            }
            mail.AddTo(new EmailAddress(toEmail[0].Address));
            if (toEmail.Length > 1)
            {
                for (int i = 1; i < toEmail.Length; i++)
                {
                    mail.AddCc(new EmailAddress(toEmail[i].Address));
                }
            }
            if (fromEmailAsCc != null && !toEmail.Where(e => fromEmailAsCc.Address.Equals(e.Address, StringComparison.InvariantCultureIgnoreCase)).Any())
            {
                mail.AddCc(new EmailAddress(fromEmailAsCc.Address));
            }

            mail.Subject = subject;
            mail.AddContent("text/html", htmlBody);

            if (!string.IsNullOrEmpty(attachmentName) && attachmentStream != null)
            {
                mail.AddAttachment(attachmentName, Convert.ToBase64String(attachmentStream.ToArray()), "application/pdf");
            }

            var client   = new SendGridClient(ApiKey);
            var response = await client.SendEmailAsync(mail);

            MessageSendtAudit($"Email Send [Status: {response.StatusCode}]. [{subject}] e-mail to addresses [{string.Join(", ", toEmail.Select(a => a.Address).ToArray())}].");

            if (response.StatusCode != HttpStatusCode.Accepted)
            {
                throw new Exception($"Send email error. Status: {response.StatusCode}, to:[{string.Join(", ", toEmail.Select(a => a.Address).ToArray())}].");
            }
        }
        public virtual async Task SendNotificationAsync(NotificationMessage message)
        {
            if (!CanSend(message))
            {
                throw new ArgumentNullException(nameof(message));
            }

            var emailNotificationMessage = message as EmailNotificationMessage;

            var fromAddress = new EmailAddress(emailNotificationMessage.From);
            var toAddress   = new EmailAddress(emailNotificationMessage.To);

            try
            {
                var client  = new SendGridClient(_emailSendingOptions.ApiKey);
                var mailMsg = new SendGridMessage
                {
                    From        = fromAddress,
                    Subject     = emailNotificationMessage.Subject,
                    HtmlContent = emailNotificationMessage.Body,
                };

                mailMsg.AddTo(toAddress);

                if (!emailNotificationMessage.CC.IsNullOrEmpty())
                {
                    foreach (var ccEmail in emailNotificationMessage.CC)
                    {
                        mailMsg.AddCc(ccEmail);
                    }
                }
                if (!emailNotificationMessage.BCC.IsNullOrEmpty())
                {
                    foreach (var bccEmail in emailNotificationMessage.BCC)
                    {
                        mailMsg.AddBcc(bccEmail);
                    }
                }

                var response = await client.SendEmailAsync(mailMsg);

                if (response.StatusCode != HttpStatusCode.Accepted)
                {
                    var errorBody = await response.Body.ReadAsStringAsync();

                    throw new SentNotificationException(errorBody);
                }
            }
            catch (SmtpException ex)
            {
                throw new SentNotificationException(ex);
            }
        }
Exemplo n.º 20
0
        private SendGridMessage CreateEmail(Employee e, Occasions occassion)
        {
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress(ConfigurationSettings.AppSettings["FromAddress"], "EAS Fun Team"));

            msg.AddTo($"{e.Alias}@microsoft.com");
            //List<string> EmailsForBCC = new List<string>(_alias);
            //EmailsForBCC.Remove(e.Alias);

            //List<EmailAddress> EmailAddressForBCC = new List<EmailAddress>();
            //foreach (string email in EmailsForBCC)
            //{
            //    EmailAddress emailAddress = new EmailAddress(email);
            //    EmailAddressForBCC.Add(emailAddress);
            //}
            msg.AddCc(ConfigurationSettings.AppSettings["CCAddress"]);
            //if (EmailAddressForBCC.Count != 0)
            //{
            //    msg.AddBccs(EmailAddressForBCC);
            //}

            string HTMLcontent;

            if (occassion == Occasions.Birthday)
            {
                string image = BirthdayImages();
                HTMLcontent = "<h3>Hi " + e.Name.Split(' ')[0] + ", <h3><h3> Wish you a very Happy Birthday!! May this day bring special moments to your life and make it much more wonderful.</h3><img src='" + image + "'";
                msg.SetSubject("Happy Birthday " + e.Name + " !!");
                msg.AddContent(MimeType.Html, HTMLcontent);
            }
            if (occassion == Occasions.Anniversary)
            {
                string year;
                string image       = AnniImages();
                var    PresentYear = DateTime.Now.Year;
                var    AnniYear    = e.DateOfJoining.Year;
                var    TotalYears  = PresentYear - AnniYear;
                if (TotalYears == 1)
                {
                    year = "year";
                }
                else
                {
                    year = "years";
                }
                HTMLcontent = "<h4> Hi " + e.Name.Split(' ')[0] + ", </h4><h4>Happy Work Anniversary!!! Congratulations on completing " + TotalYears + " " + year + " in Microsoft !!! Wishing you many more successful and happy years ahead. </h4> <img src='" + image + "'";
                msg.SetSubject("Congratulations " + e.Name + " on completing " + TotalYears + " " + year + " in Microsoft");
                msg.AddContent(MimeType.Html, HTMLcontent);
            }

            return(msg);
        }
Exemplo n.º 21
0
        public static async void ProcessQueueMessage([QueueTrigger("email")] string message, ILogger logger)
        {
            try
            {
                var configuration = new ConfigurationBuilder()
                                    .SetBasePath(Directory.GetCurrentDirectory())
                                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                    .AddEnvironmentVariables()
                                    .Build()
                ;

                Secrets.ConnectionStrings myConnStr = new Secrets.ConnectionStrings();
                configuration.GetSection("ConnectionStrings").Bind(myConnStr);

                var apiKey = myConnStr.SendGrid;
                var client = new SendGridClient(apiKey);
                // ok

                MyEmails email = JsonConvert.DeserializeObject <MyEmails>(message);

                var msg = new SendGridMessage();
                msg.SetFrom(new EmailAddress("*****@*****.**", "Suporte MI3D Plus"));
                msg.SetSubject(email.Subject);
                msg.AddContent(MimeType.Html, email.Body);
                msg.AddTo(new EmailAddress(email.To.First().Address, email.To.First().DisplayName));
                msg.AddCc(new EmailAddress("*****@*****.**", "Carlos de Souza"));

                var response = await client.SendEmailAsync(msg);

                string mId = response.Headers.GetValues("x-message-id").FirstOrDefault();

                logger.LogInformation(mId);
            }
            catch (System.Exception ex)
            {
                logger.LogError(ex.Message);
            }

            // RegisterServices();

            // List<MyApp.Domain.Address> myAdd = new List<MyApp.Domain.Address>();
            // MyApp.Domain.Address MyNewAdd = new MyApp.Domain.Address("Ricardo Teste Gaefke", "*****@*****.**");
            // myAdd.Add(MyNewAdd);

            // MyApp.Domain.Emails myEm = new MyApp.Domain.Emails(email.Subject, myAdd, email.Body);

            // var myEmail = _serviceProvider.GetService<IMyEmail>();
            // string mymId = await myEmail.SendMailMI3D(myEm);

            // logger.LogInformation(mymId);

            // DisposeServices();
        }
Exemplo n.º 22
0
        public void TestFetchFormParamsHelper(Web webApi, bool credentials)
        {
            // Test Variables
            const string toAddress   = "*****@*****.**";
            const string ccAddress   = "*****@*****.**";
            const string bcc1Address = "*****@*****.**";
            const string bcc2Address = "*****@*****.**";

            MailAddress[] bccAddresses = { new MailAddress(bcc1Address), new MailAddress(bcc2Address) };
            const string  fromAddress  = "*****@*****.**";
            const string  subject      = "Test Subject";
            const string  textBody     = "Test Text Body";
            const string  htmlBody     = "<p>Test HTML Body</p>";
            const string  headerKey    = "headerkey";
            var           testHeader   = new Dictionary <string, string> {
                { headerKey, "headervalue" }
            };
            const string categoryName = "Example Category";

            var message = new SendGridMessage();

            message.AddTo(toAddress);
            message.AddCc(ccAddress);
            message.Bcc     = bccAddresses;
            message.From    = new MailAddress(fromAddress);
            message.Subject = subject;
            message.Text    = textBody;
            message.Html    = htmlBody;
            message.AddHeaders(testHeader);
            message.Header.SetCategory(categoryName);

            var result = webApi.FetchFormParams(message);

            if (credentials)
            {
                Assert.True(result.Any(r => r.Key == "api_user" && r.Value == TestUsername));
                Assert.True(result.Any(r => r.Key == "api_key" && r.Value == TestPassword));
            }
            Assert.True(result.Any(r => r.Key == "to[]" && r.Value == toAddress));
            Assert.True(result.Any(r => r.Key == "cc[]" && r.Value == ccAddress));
            Assert.True(result.Any(r => r.Key == "bcc[]" && r.Value == bcc1Address));
            Assert.True(result.Any(r => r.Key == "bcc[]" && r.Value == bcc2Address));
            Assert.True(result.Any(r => r.Key == "from" && r.Value == fromAddress));
            Assert.True(result.Any(r => r.Key == "subject" && r.Value == subject));
            Assert.True(result.Any(r => r.Key == "text" && r.Value == textBody));
            Assert.True(result.Any(r => r.Key == "html" && r.Value == htmlBody));
            Assert.True(
                result.Any(
                    r => r.Key == "headers" && r.Value == String.Format("{{\"{0}\":\"{1}\"}}", headerKey, testHeader[headerKey])));
            Assert.True(
                result.Any(r => r.Key == "x-smtpapi" && r.Value == String.Format("{{\"category\" : \"{0}\"}}", categoryName)));
        }
Exemplo n.º 23
0
        private SendGridMessage CreateSendGridMessage(TransportMessage message)
        {
            var sendGridMessage = new SendGridMessage();

            sendGridMessage.From = new EmailAddress(message.From);
            sendGridMessage.AddTo(new EmailAddress(message.To));
            sendGridMessage.Subject = message.Subject;
            sendGridMessage.AddCc(message.CC);
            sendGridMessage.AddBcc(message.Bcc);
            sendGridMessage.PlainTextContent = message.Body;

            return(sendGridMessage);
        }
Exemplo n.º 24
0
        public void BuildEmailCopy(string ccEmail)
        {
            if (string.IsNullOrEmpty(ccEmail))
            {
                return;
            }
            var i = 0;

            string[] splitList = { ";" };
            var      ccList    = ccEmail.Split(splitList, StringSplitOptions.None);

            while (i < ccList.Length)
            {
                if (i + 1 < ccList.Length)
                {
                    _message.AddCc(ccList[i++], ccList[i++]);
                }
                else
                {
                    _message.AddCc(ccList[i++]);
                }
            }
        }
Exemplo n.º 25
0
        public void BuildEmailCopy()
        {
            var emailFound = false;

            foreach (var emailToAddress in _message.Personalizations[0].Tos.Where(emailToAddress => emailToAddress.Email == _message.From.Email))
            {
                emailFound = true;
            }

            if (!emailFound)
            {
                _message.AddCc(_message.From.Email);
            }
        }
Exemplo n.º 26
0
        public void SendEmail(List <string> to, string bcc, string cc, string subject, string body)
        {
            SendGridMessage myMessage = new SendGridMessage();

            myMessage.AddTo(to);
            if (!string.IsNullOrEmpty(bcc))
            {
                myMessage.AddCc(bcc);
            }
            if (!string.IsNullOrEmpty(cc))
            {
                myMessage.AddCc(cc);
            }

            myMessage.From    = new MailAddress(FromEmail, FromName);
            myMessage.Subject = subject;
            myMessage.Html    = body;

            // Create a Web transport, using API Key
            var transportWeb = new Web(ApiKey);

            // Send the email.
            AsyncHelper.RunSync(() => transportWeb.DeliverAsync(myMessage));
        }
Exemplo n.º 27
0
        public async Task SendEmailAsync(List <string> to, string subject, string body, string bcc = null, string cc = null)
        {
            SendGridMessage myMessage = new SendGridMessage();

            foreach (var toMail in to)
            {
                myMessage.AddTo(new EmailAddress(toMail));
            }
            if (!string.IsNullOrEmpty(bcc))
            {
                myMessage.AddCc(new EmailAddress(bcc));
            }
            if (!string.IsNullOrEmpty(cc))
            {
                myMessage.AddCc(new EmailAddress(cc));
            }

            myMessage.From        = new EmailAddress(_sendGridConfigure.FromEmail, _sendGridConfigure.FromName);
            myMessage.Subject     = subject;
            myMessage.HtmlContent = body;
            var client = new SendGridClient(_sendGridConfigure.ApiKey);
            // Create a Web transport, using API Key
            await client.SendEmailAsync(myMessage);
        }
Exemplo n.º 28
0
        async Task <HttpStatusCode> IEmailSenderExtended.SendEmailApplicationConfirmationAsync(
            string applicantName, string applicantEmail,
            string organizationContactEmail,
            string subject, string htmlMessage)
        {
            var client = new SendGridClient(SendgridApiKey);

            SendGridMessage sendGridMessage = new SendGridMessage()
            {
                From             = new EmailAddress(FromEmail, "Volly Team"),
                Subject          = subject,
                HtmlContent      = htmlMessage,
                PlainTextContent = htmlMessage
            };

            if (!string.IsNullOrEmpty(applicantEmail))
            {
                sendGridMessage.AddTo(new EmailAddress(applicantEmail.ToLower().Trim(), applicantName));

                var ccEmails = new HashSet <string>();

                if (SendApplicationsCCOrganizationEmailFeature)
                {
                    if (!string.IsNullOrWhiteSpace(organizationContactEmail) &&
                        !organizationContactEmail.ToLower().Trim().Equals(applicantEmail.ToLower().Trim())
                        )
                    {
                        ccEmails.Add(organizationContactEmail.ToLower().Trim());
                    }
                }

                if (!string.IsNullOrWhiteSpace(ApplicationsCCEmail) &&
                    !ApplicationsCCEmail.ToLower().Trim().Equals(applicantEmail.ToLower().Trim())
                    )
                {
                    ccEmails.Add(ApplicationsCCEmail.ToLower().Trim());
                }

                foreach (var email in ccEmails)
                {
                    sendGridMessage.AddCc(new EmailAddress(email));
                }
            }

            var result = await client.SendEmailAsync(sendGridMessage);

            return(result.StatusCode);
        }
Exemplo n.º 29
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.º 30
0
        /// <summary>
        /// Make an eMail header
        /// </summary>
        /// <param name="from">email address of the sender</param>
        /// <param name="to">email address of the recipient</param>
        /// <param name="cc">email address of copy recipient</param>
        /// <param name="subject">eMail Subject (aka header)</param>
        /// <returns>new SendGridMessage, which can be passed into Deliver()</returns>
        public static SendGridMessage Header(MailAddress from, MailAddress to, MailAddress cc, string subject)
        {
            // Create the email object first, then add the properties.
            SendGridMessage msg = new SendGridMessage();

            // Add the message properties.
            msg.From = new EmailAddress(from.Address, from.DisplayName);
            msg.AddTo(new EmailAddress(to.Address, to.DisplayName));
            if (cc != null)
            {
                msg.AddCc(new EmailAddress(cc.Address, cc.DisplayName));
            }
            msg.Subject = subject;

            msg.SetClickTracking(false, false);

            return(msg);
        }