Exemplo n.º 1
0
 private async Task Execute(SendGridMessage message)
 {
     var client = new SendGridClient(_sendGridKey);
     await client.SendEmailAsync(message);
 }
        public async Task <SendResponse> SendAsync(IFluentEmail email, CancellationToken?token = null)
        {
            var sendGridClient = new SendGridClient(_apiKey);

            var mailMessage = new SendGridMessage();

            mailMessage.SetSandBoxMode(_sandBoxMode);

            mailMessage.SetFrom(ConvertAddress(email.Data.FromAddress));

            if (email.Data.ToAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddTos(email.Data.ToAddresses.Select(ConvertAddress).ToList());
            }

            if (email.Data.CcAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddCcs(email.Data.CcAddresses.Select(ConvertAddress).ToList());
            }

            if (email.Data.BccAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddBccs(email.Data.BccAddresses.Select(ConvertAddress).ToList());
            }

            mailMessage.SetSubject(email.Data.Subject);

            if (email.Data.Headers.Any())
            {
                mailMessage.AddHeaders(email.Data.Headers);
            }

            if (email.Data.IsHtml)
            {
                mailMessage.HtmlContent = email.Data.Body;
            }
            else
            {
                mailMessage.PlainTextContent = email.Data.Body;
            }

            if (!string.IsNullOrEmpty(email.Data.PlaintextAlternativeBody))
            {
                mailMessage.PlainTextContent = email.Data.PlaintextAlternativeBody;
            }

            if (email.Data.Attachments.Any())
            {
                foreach (var attachment in email.Data.Attachments)
                {
                    var sendGridAttachment = await ConvertAttachment(attachment);

                    mailMessage.AddAttachment(sendGridAttachment.Filename, sendGridAttachment.Content,
                                              sendGridAttachment.Type, sendGridAttachment.Disposition, sendGridAttachment.ContentId);
                }
            }

            var sendGridResponse = await sendGridClient.SendEmailAsync(mailMessage, token.GetValueOrDefault());

            var sendResponse = new SendResponse();

            if (IsHttpSuccess((int)sendGridResponse.StatusCode))
            {
                return(sendResponse);
            }

            sendResponse.ErrorMessages.Add($"{sendGridResponse.StatusCode}");
            var messageBodyDictionary = await sendGridResponse.DeserializeResponseBodyAsync(sendGridResponse.Body);

            if (messageBodyDictionary.ContainsKey("errors"))
            {
                var errors = messageBodyDictionary["errors"];

                foreach (var error in errors)
                {
                    sendResponse.ErrorMessages.Add($"{error}");
                }
            }

            return(sendResponse);
        }
        public async Task <ActionResult <UserRegisterResponseVM> > Register([FromBody] UserRegisterVM vm)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid Data"));
            }
            else if (vm.Password != vm.PasswordConfirmation)
            {
                return(BadRequest("Password and password confirmation do not match"));
            }
            else
            {
                var entity = await _context.Cities.SingleOrDefaultAsync(b => b.Name == vm.City);

                if (entity == null)
                {
                    return(BadRequest("Could not find city"));
                }
            }

            //var user = new User(vm);
            var user = new User
            {
                UserName        = vm.Email,
                Email           = vm.Email,
                FirstName       = vm.FirstName,
                LastName        = vm.LastName,
                NormalizedEmail = _normalizer.NormalizeEmail(vm.Email),
                Tos             = vm.Tos,
                PhoneNumber     = vm.Phone,
                CityName        = vm.City
            };
            var result = await _userManager.CreateAsync(user, vm.Password);

            //result = await _userManager.AddPasswordAsync(user, vm.Password);
            if (result.Succeeded)
            {
                await _userManager.AddToRoleAsync(user, "user");

                //normalize
                await _userManager.UpdateNormalizedEmailAsync(user);

                //generate email confirmation token
                var confirmation = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                //email token to user
                var apiKey           = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
                var client           = new SendGridClient(apiKey);
                var from             = new EmailAddress("*****@*****.**", "Example User");
                var subject          = "You are now registered!";
                var to               = new EmailAddress(vm.Email, vm.FirstName);
                var plainTextContent = "Confirmation: " + confirmation;
                var htmlContent      = "Confirmation: " + confirmation;
                var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
                var response         = await client.SendEmailAsync(msg);

                return(Ok(new UserRegisterResponseVM("200 ok, awesome!")));
            }
            else
            {
                return(BadRequest("Register failed :("));
            }
        }
Exemplo n.º 4
0
        public async Task SendAsync(IEnumerable <string> to, string subject, string body, bool bodyIsHtml = true, string from = "*****@*****.**",
                                    IEnumerable <string> cc = null, IEnumerable <string> bcc = null, IEnumerable <SendGrid.Helpers.Mail.Attachment> attachment = null)
        {
            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentNullException("subject");
            }

            if (to == null || !to.Any())
            {
                throw new ArgumentNullException("to");
            }

            if (IsDevelopment && string.IsNullOrWhiteSpace(ForcedEmail))
            {
                return;
            }

            List <EmailAddress> toList = new List <EmailAddress>();

            if (!string.IsNullOrWhiteSpace(ForcedEmail))
            {
                toList.Add(new EmailAddress(ForcedEmail));
            }
            else
            {
                foreach (string t in to)
                {
                    toList.Add(new EmailAddress(t));
                }
            }

            var mailMessage = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress(from, "Auctus Mail Service"), toList, subject, bodyIsHtml ? null : body, bodyIsHtml ? body : null);

            if (attachment != null)
            {
                foreach (SendGrid.Helpers.Mail.Attachment a in attachment)
                {
                    mailMessage.Attachments.Add(a);
                }
            }

            if (cc != null && string.IsNullOrWhiteSpace(ForcedEmail))
            {
                foreach (string c in cc)
                {
                    mailMessage.AddCc(c);
                }
            }

            if (bcc != null && string.IsNullOrWhiteSpace(ForcedEmail))
            {
                foreach (string b in bcc)
                {
                    mailMessage.AddBcc(b);
                }
            }

            SendGridClient client = new SendGridClient(SendGridKey);
            await client.SendEmailAsync(mailMessage);
        }
        private async Task <bool> SendEmail(SendEmailToUsersRequest sendEmailToUsersRequest, List <User> Users)
        {
            var apiKey = _sendGridConfig.Value.ApiKey;

            if (apiKey == string.Empty)
            {
                throw new Exception("SendGrid Api Key missing.");
            }

            var client = new SendGridClient(apiKey);
            var eml    = new SendGridMessage()
            {
                From             = new EmailAddress(_sendGridConfig.Value.FromEmail, _sendGridConfig.Value.FromName),
                Subject          = sendEmailToUsersRequest.Subject,
                PlainTextContent = sendEmailToUsersRequest.BodyText,
                HtmlContent      = sendEmailToUsersRequest.BodyHTML
            };

            if (sendEmailToUsersRequest.Recipients.ToUserIDs?.Count() > 0)
            {
                foreach (int userId in sendEmailToUsersRequest.Recipients.ToUserIDs)
                {
                    var User = Users.Where(w => w.ID == userId).FirstOrDefault();
                    if (User != null && User.UserPersonalDetails != null)
                    {
                        eml.AddTo(new EmailAddress(User.UserPersonalDetails.EmailAddress, User.UserPersonalDetails.FirstName + " " + User.UserPersonalDetails.LastName));
                    }
                }
            }

            if (sendEmailToUsersRequest.Recipients.CCUserIDs?.Count() > 0)
            {
                foreach (int userId in sendEmailToUsersRequest.Recipients.CCUserIDs)
                {
                    var User = Users.Where(w => w.ID == userId).FirstOrDefault();
                    if (User != null && User.UserPersonalDetails != null)
                    {
                        eml.AddCc(new EmailAddress(User.UserPersonalDetails.EmailAddress, User.UserPersonalDetails.FirstName + " " + User.UserPersonalDetails.LastName));
                    }
                }
            }

            if (sendEmailToUsersRequest.Recipients.BCCUserIDs?.Count() > 0)
            {
                foreach (int userId in sendEmailToUsersRequest.Recipients.BCCUserIDs)
                {
                    var User = Users.Where(w => w.ID == userId).FirstOrDefault();
                    if (User != null && User.UserPersonalDetails != null)
                    {
                        eml.AddBcc(new EmailAddress(User.UserPersonalDetails.EmailAddress, User.UserPersonalDetails.FirstName + " " + User.UserPersonalDetails.LastName));
                    }
                }
            }

            Response response = await client.SendEmailAsync(eml);

            if (response.StatusCode == System.Net.HttpStatusCode.OK || response.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 6
0
        public static async Task RunAsync([TimerTrigger("0 0 */3 * * *")] TimerInfo myTimer, TraceWriter log)
        {
            var connectionString = Environment.GetEnvironmentVariable("Connection", EnvironmentVariableTarget.Process);
            var storageString    = Environment.GetEnvironmentVariable("AzureWebJobsStorage", EnvironmentVariableTarget.Process);
            var apiKey           = Environment.GetEnvironmentVariable("SENDGRID_API_KEY", EnvironmentVariableTarget.Process);

            ExcelImportExport excelImportExport = new ExcelImportExport("GPException");


            log.Info($"value of storageString is: {storageString}");
            log.Info($"value of apiKey is: {apiKey}");
            log.Info($"value of connectionString is: {connectionString}");

            log.Info($"C# Timer trigger function executed at: {DateTime.Now}");


            //Run the GP Exceptions Stored Procedure
            using (SqlConnection objConn = new SqlConnection(connectionString))
            {
                // Connection object
                objConn.Open();

                // Command text
                var strText = "exec sp_GrossProfitExceptionUpdate";

                // Command Object
                using (SqlCommand objCmd = new SqlCommand(strText, objConn))
                {
                    // Execute procedure
                    var rows = objCmd.ExecuteNonQueryAsync();

                    // This should always be 1
                    log.Info("sp_GrossProfitExceptionUpdate stored procedure updated");
                }

                // Close the object
                objConn.Close();
            }

            List <GPException> GPExceptionList = new List <GPException>();

            GPExceptionList = ExcuteObject <GPException>(GPExceptionSQLString,
                                                         false).ToList();


            var countExceptions = GPExceptionList.Count();

            log.Info("There are: " + countExceptions.ToString() + "Exceptions");

            ExcelImportExport ExcelExport = new ExcelImportExport();

            ExcelExport.SaveFileExcelToAzureStorageAsync(GPExceptionList, storageString, FileName, log, ContainerName).Wait();
            log.Info("GP Exception File created in Azure Storage Area.");
            var client = new SendGridClient(apiKey);
            //  var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, "", htmlContent, false);

            var msg = new SendGridMessage()
            {
                From             = new EmailAddress("*****@*****.**", "GP Exception Team"),
                Subject          = "GP Exceptions",
                PlainTextContent = "Hi Please find the GP Exceptions. There are " + countExceptions.ToString() + "Exceptions.",
                HtmlContent      = "<strong>" + "Hi Please find the GP Exceptions.There are " + countExceptions.ToString() + "Exceptions." + "</strong>"
            };

            msg.AddTo(new EmailAddress("*****@*****.**", "Test User"));
            ExcelExport.AttachEmailtoMessage(storageString, ContainerName, FileName, msg);

            var response = await client.SendEmailAsync(msg);

            log.Info("Response from email server: " + response.StatusCode.ToString());
        }
Exemplo n.º 7
0
        public override async Task <bool> SendNotificationAsync(PushNotificationItem notificationItem, object message, CancellationToken ct)
        {
            var cfg  = (SendGridDeliveryProviderConfiguration)Configuration;
            var sent = false;
            //implicit conversion operator
            MailMessage smsg = message as SerializableMailMessage;

            if (smsg != null)
            {
                try
                {
                    var hView           = smsg.AlternateViews.First(v => v.ContentType.MediaType == "text/html");
                    var tView           = smsg.AlternateViews.First(v => v.ContentType.MediaType == "text/plain");
                    var sendGridMessage = new SendGridMessage
                    {
                        From     = new EmailAddress(cfg.FromAddress, cfg.FromDisplayName),
                        Subject  = smsg.Subject,
                        Contents = new List <Content>()
                        {
                            new Content("text/html", hView.ContentStream.ReadToString()),
                            //new Content("text", tView.ContentStream.ReadToString())
                        },
                        Personalizations = new List <Personalization>()
                        {
                            new Personalization
                            {
                                Tos = new List <EmailAddress>()
                                {
                                    new EmailAddress(notificationItem.Destination.DestinationAddress, notificationItem.Destination.SubscriberName)
                                }
                            }
                        },
                    };

                    sendGridMessage.TrackingSettings = new TrackingSettings()
                    {
                        ClickTracking = new ClickTracking()
                    };

                    if (cfg.EnableClickTracking ?? false)
                    {
                        sendGridMessage.TrackingSettings.ClickTracking.Enable = true;;
                    }
                    if (cfg.EnableGravatar ?? false)
                    {
                        //sendGridMessage.MailSettings.EnableGravatar();
                    }
                    if (cfg.EnableOpenTracking ?? false)
                    {
                        sendGridMessage.TrackingSettings.OpenTracking.Enable = true;;
                    }
                    if (cfg.SendToSink ?? false)
                    {
                        //sendGridMessage.SendToSink();
                    }

                    //var transport = new Web(cfg.ApiKey);
                    //await transport.DeliverAsync(sendGridMessage);
                    //sent = true;

                    var sg       = new SendGridClient(cfg.ApiKey);
                    var response = await sg.SendEmailAsync(sendGridMessage);

                    sent = true;
                }
                catch
                {
                    sent = false;
                    //TODO: log this somewhere
                }
            }
            return(sent);
        }
Exemplo n.º 8
0
        private async Task SendSendGridEmailAsync(string configurationKey, string fromOverride, List <string> to, List <string> cc, List <string> bcc, string subject, string htmlMessage, List <EmailAttachment> emailAttachments = null)
        {
            if (string.IsNullOrEmpty(configurationKey))
            {
                configurationKey = EmailSenderConstants.EmptyConfigurationKeyDefaultKey;
            }

            if (!_sendGridEmailSenderConfigurations.ContainsKey(configurationKey))
            {
                _sendGridEmailSenderConfigurations.Add(configurationKey, LoadSendGridEmailSenderConfiguration(configurationKey, _configuration));
            }

            SendGridEmailSenderConfiguration emailSenderConfiguration = _sendGridEmailSenderConfigurations[configurationKey];

            var client = new SendGridClient(emailSenderConfiguration.ApiKey);

            var mailMessage = new SendGridMessage()
            {
                From        = new EmailAddress(!string.IsNullOrEmpty(fromOverride) ? fromOverride : emailSenderConfiguration.FromEmailAddress),
                Subject     = subject,
                HtmlContent = htmlMessage
            };

            if (to != null)
            {
                to.ForEach(toString => mailMessage.AddTo(new EmailAddress(toString)));
            }

            if (cc != null)
            {
                cc.ForEach(ccString => mailMessage.AddCc(new EmailAddress(ccString)));
            }

            if (bcc != null)
            {
                bcc.ForEach(bccString => mailMessage.AddBcc(new EmailAddress(bccString)));
            }

            if (emailAttachments != null)
            {
                foreach (var emailAttachment in emailAttachments)
                {
                    mailMessage.AddAttachment(new SendGrid.Helpers.Mail.Attachment()
                    {
                        Content  = Convert.ToBase64String(emailAttachment.Content),
                        Filename = emailAttachment.FileName,
                        Type     = emailAttachment.MimeType
                    });
                }
            }

            var response = await client.SendEmailAsync(mailMessage).ConfigureAwait(false);

            // see https://github.com/sendgrid/sendgrid-csharp

            // "After executing the above code, response.StatusCode should be 202 and you should have an email in the inbox of the to recipient."

            if (response.StatusCode != HttpStatusCode.Accepted)
            {
                string body = await response.Body.ReadAsStringAsync().ConfigureAwait(false);

                throw new Exception($"SendGrid email sending failed with status code {response.StatusCode}: {body}");
            }
        }
Exemplo n.º 9
0
 public async void SendEmail(SendGridMessage msg)
 {
     var      client   = new SendGridClient(ApiKey);
     Response response = await client.SendEmailAsync(msg);
 }
Exemplo n.º 10
0
        /// <summary>
        /// Send a mail message.
        /// </summary>
        public async Task SendMessageAsync(
            IList <EmailRecipient> recipients,
            string subject,
            string body,
            EmailSender customSender = null,
            ThreadInfo threadInfo    = null)
        {
            if (_apiKey == null)
            {
                // E-mail is disabled.
                return;
            }

            var from = customSender != null
                                ? new EmailAddress(customSender.FromAddress, customSender.Name)
                                : new EmailAddress(DefaultFromAddress, "CS Classroom");
            var tos = recipients
                      .Select(r => new EmailAddress(r.EmailAddress, r.Name))
                      .ToList();

            SendGridMessage msg;

            if (tos.Count == 1)
            {
                msg = MailHelper.CreateSingleEmail
                      (
                    from,
                    tos[0],
                    subject,
                    plainTextContent: null,
                    htmlContent: body
                      );
            }
            else
            {
                msg = MailHelper.CreateSingleEmailToMultipleRecipients
                      (
                    from,
                    tos,
                    subject,
                    plainTextContent: null,
                    htmlContent: body
                      );
            }

            if (threadInfo != null)
            {
                msg.Headers = new Dictionary <string, string>();

                msg.Headers["Message-Id"] = $"<{threadInfo.MessageId}>";

                if (threadInfo.InReplyTo != null)
                {
                    msg.Headers["In-Reply-To"] = $"<{threadInfo.InReplyTo}>";
                }

                if (threadInfo.References != null)
                {
                    msg.Headers["References"] = string.Join
                                                (
                        " ",
                        threadInfo.References.Select(r => $"<{r}>")
                                                );
                }
            }

            var client = new SendGridClient(_apiKey);
            await client.SendEmailAsync(msg);
        }
Exemplo n.º 11
0
        public void Send(IEnumerable <string> to, string from, string subject, string message)
        {
            try
            {
                // //// From
                var pairFrom  = from.Split(';');
                var emailFrom = pairFrom[0];
                var nameFrom  = pairFrom[1];
                var client    = new SendGridClient(Program.sendGridKey);
                var _from     = new EmailAddress(emailFrom, nameFrom);
                // //// To
                var _to = new List <EmailAddress>();
                foreach (var pairs in to)
                {
                    var pair  = pairs.Split(';');
                    var email = pair[0];
                    var name  = pair[1];
                    _to.Add(new EmailAddress(email, name));
                }
                var plainTextContent = message;
                var htmlContent      = message;
                var msg      = MailHelper.CreateSingleEmailToMultipleRecipients(_from, _to, subject, plainTextContent, htmlContent);
                var response = client.SendEmailAsync(msg);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            // try
            // {
            //     var mailMsg = new System.Net.Mail.MailMessage();

            //     //// To
            //     foreach(var pairs in to)
            //     {
            //         var pair = pairs.Split(';');
            //         var email = pair[0];
            //         var name = pair[1];
            //         mailMsg.To.Add(new System.Net.Mail.MailAddress(email, name));
            //     }

            //     //// From
            //     var pairFrom = from.Split(';');
            //     var emailFrom = pairFrom[0];
            //     var nameFrom = pairFrom[1];
            //     mailMsg.From = new System.Net.Mail.MailAddress(emailFrom, nameFrom);

            //     mailMsg.Subject = subject;
            //     mailMsg.AlternateViews.Add(System.Net.Mail.AlternateView.CreateAlternateViewFromString(message, null, System.Net.Mime.MediaTypeNames.Text.Plain));
            //     mailMsg.AlternateViews.Add(System.Net.Mail.AlternateView.CreateAlternateViewFromString(message.Replace(System.Environment.NewLine, "<br>"), null, System.Net.Mime.MediaTypeNames.Text.Html));

            //     //// Init SmtpClient and send
            //     var smtpClient = new System.Net.Mail.SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
            //     var credentials = new System.Net.NetworkCredential("aqi", "Capital!1234");
            //     smtpClient.Credentials = credentials;

            //     smtpClient.Send(mailMsg);
            // }
            // catch(Exception e)
            // {
            //     Console.WriteLine(e);
            // }
        }
Exemplo n.º 12
0
        public async void HandleApplication(bool accepted, string id, AppSettings settings)
        {
            var application = _context.LocationApplications.FirstOrDefault(x => x.Id == Guid.Parse(id));

            if (application == null)
            {
                throw new AppException("Application not found");
            }

            application.Status = accepted ? 1 : -1;

            _context.SaveChanges();

            if (accepted)
            {
                var newLocation = new Location
                {
                    ApartmentNumber = application.ApartmentNumber,
                    Line1           = application.Line1,
                    Line2           = application.Line2,
                    LocationType    = application.LocationType,
                    Name            = application.Name,
                    ZipCode         = application.ZipCode
                };
                _context.Locations.Add(newLocation);
                var generatedPassword = Crypto.GenerateRendomPassword();
                Crypto.CreatePasswordHash(generatedPassword, out var generatedPassHash, out var generatedPassSalt);
                var builder = new DbContextOptionsBuilder <VehicleHistoryContext>();
                builder.UseSqlServer(settings.ConnectionString);
                using (var context = new VehicleHistoryContext(builder.Options))
                {
                    context.Users.Add(new User
                    {
                        Location               = newLocation,
                        FirstName              = "undefined",
                        LastName               = "undefined",
                        Email                  = application.Email,
                        Group                  = UserGroups.ShopOwner,
                        PasswordHash           = generatedPassHash,
                        PasswordSalt           = generatedPassSalt,
                        PasswordRecoveryActive = true
                    });

                    var emailSubject = "Your application has been accepted";
                    var emailBody    = $"Use the following password the next time you log in: <b>{generatedPassword}</b>. " +
                                       $"You will be prompted to change the password when you log in.";

                    var client  = new SendGridClient(settings.SendGridKey);
                    var message = new SendGridMessage
                    {
                        From        = new EmailAddress("*****@*****.**", "Vehicle History Account Management"),
                        Subject     = emailSubject,
                        HtmlContent = emailBody
                    };

                    message.AddTo(new EmailAddress(application.Email));
                    await client.SendEmailAsync(message);

                    await context.SaveChangesAsync();
                }
            }
            else
            {
                var builder = new DbContextOptionsBuilder <VehicleHistoryContext>();
                builder.UseSqlServer(settings.ConnectionString);
                using (var context = new VehicleHistoryContext(builder.Options))
                {
                    var emailSubject = "Your application has been rejected";
                    var emailBody    = $"You can try applying again or contacting the administrators if you believe this decision is unwarranted.";

                    var client  = new SendGridClient(settings.SendGridKey);
                    var message = new SendGridMessage
                    {
                        From        = new EmailAddress("*****@*****.**", "Vehicle History Account Management"),
                        Subject     = emailSubject,
                        HtmlContent = emailBody
                    };

                    message.AddTo(new EmailAddress(application.Email));
                    await client.SendEmailAsync(message);

                    await context.SaveChangesAsync();
                }
            }
        }
Exemplo n.º 13
0
 private async Task SendEmail(SendGridMessage msg)
 {
     var apiKey   = _appKeys.SendGridApiKey;
     var client   = new SendGridClient(apiKey);
     var response = await client.SendEmailAsync(msg);
 }
Exemplo n.º 14
0
 public static async Task SendGridSendAsync(string apiKey, string from, string to, string subject, string body)
 {
     var client   = new SendGridClient(apiKey);
     var message  = MailHelper.CreateSingleEmail(new EmailAddress(from), new EmailAddress(to), subject, body, body);
     var response = await client.SendEmailAsync(message);
 }
        /// <summary>Actually send the email</summary>
        public async Task <bool> Send(string from, string subject, string body)
        {
            bool results = false;

            if (String.IsNullOrWhiteSpace(_key))
            {
                return(false);
            }

            if (String.IsNullOrWhiteSpace(from))
            {
                throw new System.ArgumentNullException(nameof(from), "From is required.");
            }

            if (String.IsNullOrWhiteSpace(subject))
            {
                throw new System.ArgumentNullException(nameof(subject), "Subject is required.");
            }

            if (String.IsNullOrWhiteSpace(body))
            {
                throw new System.ArgumentNullException(nameof(body), "Body is required.");
            }

            try
            {
                // start a new message
                SendGridClient  mailer = new SendGridClient(this._key);
                SendGridMessage msg    = new SendGridMessage();

                // set from
                msg.SetFrom(new EmailAddress(from));

                // set subject
                msg.SetSubject(subject);

                // set the Reply To if any
                if (!String.IsNullOrWhiteSpace(this.ReplyTo))
                {
                    msg.SetReplyTo(new EmailAddress(this.ReplyTo));
                }

                msg.AddContent((this._html) ? MimeType.Html : MimeType.Text, body);

                // add receipients
                foreach (string to in this.To)
                {
                    msg.AddTo(new EmailAddress(to));
                }

                // wait for the reponse
                Response response = await mailer.SendEmailAsync(msg);

                // get the response
                this.LastResponse = response.StatusCode;

                results = (response.StatusCode == HttpStatusCode.Accepted || response.StatusCode == HttpStatusCode.OK);
            }
            catch (System.Exception)
            {
                return(false);
            }

            return(results);
        }
Exemplo n.º 16
0
        public async Task <SendEmailResponse> SendEmailAsync(SendEmailDetails details)
        {
            // Get the SendGrid key
            var apiKey = Configuration["SendGridKey"];

            // Create a new SendGrid client
            var client = new SendGridClient(apiKey);

            // From
            var from = new EmailAddress(details.FromEmail, details.FromName);

            // To
            var to = new EmailAddress(details.ToEmail, details.ToName);

            // Subject
            var subject = details.Subject;

            // Content
            var content = details.Content;

            // Create Email class ready to send
            var msg = MailHelper.CreateSingleEmail(
                from,
                to,
                subject,
                // Plain content
                details.IsHTML ? null : details.Content,
                // HTML content
                details.IsHTML ? details.Content : null);

            // Finally, send the email...
            var response = await client.SendEmailAsync(msg);

            // If we succeeded...
            if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                // Return successful response
                return(new SendEmailResponse());
            }

            // Otherwise, it failed...

            try
            {
                // Get the result in the body
                var bodyResult = await response.Body.ReadAsStringAsync();

                // Deserialize the response
                var sendGridResponse = JsonConvert.DeserializeObject <SendGridResponse>(bodyResult);

                // Add any errors to the response
                var errorResponse = new SendEmailResponse
                {
                    Errors = sendGridResponse?.Errors.Select(f => f.Message).ToList()
                };

                // Make sure we have at least one error
                if (errorResponse.Errors == null || errorResponse.Errors.Count == 0)
                {
                    // Add an unknown error
                    // TODO: Localization
                    errorResponse.Errors = new List <string>(new[] { "Unknown error from email sending service. Please contact to support." });
                }

                // Return the response
                return(errorResponse);
            }
            catch (Exception ex)
            {
                // TODO: Localization

                // Break if we are debugging
                if (Debugger.IsAttached)
                {
                    var error = ex;
                    Debugger.Break();
                }

                // If something unexpected happened, return message
                return(new SendEmailResponse
                {
                    Errors = new List <string>(new[] { "Unknown error occurred" })
                });
            }
        }
Exemplo n.º 17
0
        private async Task <string> SendMailBySendGrid(Mail mail)
        {
            try
            {
                var apiKey = _configuration["SendGridAPI"];
                var client = new SendGridClient(apiKey);
                var msg    = new SendGridMessage();

                var from             = new EmailAddress(mail.From, "Test SendGrid Sender");
                var to               = new EmailAddress(mail.To, "Test SendGrid Recipient");
                var subject          = mail.Subject;
                var plainTextContent = mail.Text;

                msg.SetFrom(from.ToString(), "");
                msg.AddTo(to.ToString(), "");
                msg.SetSubject(subject);
                msg.AddContent(MimeType.Text, plainTextContent);
                var htmlContent = "";

                Personalization envelope = new Personalization();


                if (!string.IsNullOrEmpty(mail.CCs))
                {
                    var           cc_emails = new List <EmailAddress>();
                    List <string> CCs       = new List <string>();
                    CCs.AddRange(mail.CCs.Split(","));

                    foreach (string cc in CCs)
                    {
                        cc_emails.Add(new EmailAddress(cc, ""));
                    }

                    msg.AddCcs(cc_emails, 0);
                    envelope.Ccs = cc_emails;
                }

                if (!string.IsNullOrEmpty(mail.BCCs))
                {
                    List <EmailAddress> bcc_emails = new List <EmailAddress>();
                    List <string>       BCCs       = new List <string>();
                    BCCs.AddRange(mail.BCCs.Split(","));

                    foreach (var bcc in BCCs)
                    {
                        bcc_emails.Add(new EmailAddress(bcc, ""));
                    }

                    msg.AddBccs(bcc_emails, 0);
                    envelope.Bccs = bcc_emails;
                }

                msg.Personalizations.Add(envelope);

                msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);

                Response response = await client.SendEmailAsync(msg);

                if (response.StatusCode.ToString() == "Accepted")
                {
                    return("OK");
                }
                else
                {
                    return("Bad Request");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 18
0
        public string SendGridMsg(MailAddress from, string subject, string message, List <MailAddress> to, int?id, int?pid, List <MailAddress> cc = null)
        {
            var senderrorsto = ConfigurationManager.AppSettings["senderrorsto"];

            string fromDomain, apiKey;

            if (ShouldUseCustomEmailDomain)
            {
                fromDomain = CustomFromDomain;
                apiKey     = CustomSendGridApiKey;
            }
            else
            {
                fromDomain = DefaultFromDomain;
                apiKey     = DefaultSendGridApiKey;
            }
            var client = new SendGridClient(apiKey);

            if (from == null)
            {
                from = Util.FirstAddress(senderrorsto);
            }

            var mail = new SendGridMessage()
            {
                From             = new EmailAddress(fromDomain, from.DisplayName),
                Subject          = subject,
                ReplyTo          = new EmailAddress(from.Address, from.DisplayName),
                PlainTextContent = "Hello, Email from the helper [SendSingleEmailAsync]!",
                HtmlContent      = "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>"
            };
            var pe = new Personalization();

            foreach (var ma in to)
            {
                if (ma.Host != "nowhere.name" || Util.IsInRoleEmailTest)
                {
                    mail.AddTo(new EmailAddress(ma.Address, ma.DisplayName));
                }
            }

            if (cc?.Count > 0)
            {
                string cclist = string.Join(",", cc);
                if (!cc.Any(vv => vv.Address.Equal(from.Address)))
                {
                    cclist = $"{from.Address},{cclist}";
                }
                mail.ReplyTo = new EmailAddress(cclist);
            }

            pe.Headers.Add(XSmtpApi, XSmtpApiHeader(id, pid, fromDomain));
            pe.Headers.Add(XBvcms, XBvcmsHeader(id, pid));

            mail.Personalizations.Add(pe);

            if (pe.Tos.Count == 0 && pe.Tos.Any(tt => tt.Email.EndsWith("@nowhere.name")))
            {
                return(null);
            }
            var badEmailLink = "";

            if (pe.Tos.Count == 0)
            {
                pe.Tos.Add(new EmailAddress(from.Address, from.DisplayName));
                pe.Tos.Add(new EmailAddress(Util.FirstAddress(senderrorsto).Address));
                mail.Subject += $"-- bad addr for {CmsHost}({pid})";
                badEmailLink  = $"<p><a href='{CmsHost}/Person2/{pid}'>bad addr for</a></p>\n";
            }

            var regex = new Regex("</?([^>]*)>", RegexOptions.IgnoreCase | RegexOptions.Multiline);

            mail.PlainTextContent = regex.Replace(message, string.Empty);
            mail.HtmlContent      = badEmailLink + message + CcMessage(cc);

            var response = client.SendEmailAsync(mail);

            return(fromDomain);
        }
Exemplo n.º 19
0
        public IHttpActionResult Register([FromBody] Registration registration)
        {
            telemetryClient.TrackEvent("Registration:Requested");

            var user         = registration.User;
            var organization = registration.Organization;

            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    // Ensure Email address is unique.
                    var duplicate = _context.Users.Where(u => u.EmailAddress.ToLower().Equals(user.EmailAddress));
                    if (duplicate.Any())
                    {
                        return(BadRequest("Email address is already taken."));
                    }

                    // Generate an organization code if one is not provided.
                    var code = organization.Code;
                    while (string.IsNullOrEmpty(code))
                    {
                        var generated = GetRandomNumber();

                        var found = _context.Organizations
                                    .Where(o => o.Code == generated);

                        if (!found.Any())
                        {
                            code = generated;
                        }
                    }
                    organization.Code = code;

                    // Generate a user pin if one is not provided.
                    if (string.IsNullOrEmpty(user.Pin))
                    {
                        user.Pin = GetRandomNumber();
                    }

                    // Generates a password hash and salt.
                    var service = new SecurityService();
                    user.PasswordSalt = service.GenerateHash(service.GenerateRandomString());
                    user.PasswordHash = service.GenerateHash(string.Format("{0} {1}", user.Password, user.PasswordSalt));
                    user.Password     = null;

                    // Formatting
                    user.EmailAddress = user.EmailAddress.ToLower();

                    // Auto-generated.
                    user.Role                           = "Administrator";
                    user.CreatedAt                      = DateTime.UtcNow;
                    user.AllowedPhoneNumbers            = "*";
                    user.TimeZone                       = "America/New_York";
                    user.IsActive                       = true;
                    user.CanViewPunches                 = true;
                    user.CanCreatePunches               = true;
                    user.CanModifyPunches               = true;
                    user.CanDeletePunches               = true;
                    user.CanSplitAndPopulatePunches     = true;
                    user.CanViewReports                 = true;
                    user.CanViewLocks                   = true;
                    user.CanCreateLocks                 = true;
                    user.CanUndoLocks                   = true;
                    user.CanViewTimecards               = true;
                    user.CanCreateTimecards             = true;
                    user.CanModifyTimecards             = true;
                    user.CanDeleteTimecards             = true;
                    user.CanViewUsers                   = true;
                    user.CanCreateUsers                 = true;
                    user.CanModifyUsers                 = true;
                    user.CanDeleteUsers                 = true;
                    user.CanViewInventoryItems          = true;
                    user.CanSyncInventoryItems          = true;
                    user.CanViewInventoryConsumptions   = true;
                    user.CanSyncInventoryConsumptions   = true;
                    user.CanDeleteInventoryConsumptions = true;
                    user.CanViewRates                   = true;
                    user.CanCreateRates                 = true;
                    user.CanModifyRates                 = true;
                    user.CanDeleteRates                 = true;
                    user.CanViewOrganizationDetails     = true;
                    user.CanModifyOrganizationDetails   = true;
                    user.CanViewCustomers               = true;
                    user.CanCreateCustomers             = true;
                    user.CanModifyCustomers             = true;
                    user.CanDeleteCustomers             = true;
                    user.CanViewProjects                = true;
                    user.CanCreateProjects              = true;
                    user.CanModifyProjects              = true;
                    user.CanDeleteProjects              = true;
                    user.CanViewTasks                   = true;
                    user.CanCreateTasks                 = true;
                    user.CanModifyTasks                 = true;
                    user.CanDeleteTasks                 = true;
                    organization.CreatedAt              = DateTime.UtcNow;
                    organization.MinutesFormat          = "minutes";
                    organization.StripeCustomerId       = "UNSPECIFIED";
                    organization.StripeSubscriptionId   = "UNSPECIFIED";
                    organization.ShowCustomerNumber     = true;
                    organization.ShowProjectNumber      = true;
                    organization.ShowTaskNumber         = true;
                    organization.SortCustomersByColumn  = "Number";
                    organization.SortProjectsByColumn   = "Number";
                    organization.SortTasksByColumn      = "Number";

                    // Determine the actual Stripe Plan Id based on the PlanId.
                    var stripePlanId = ConfigurationManager.AppSettings["StripePlanId1"].ToString(); // Default plan is the contractor plan
                    switch (organization.PlanId)
                    {
                    case 1:
                        stripePlanId = ConfigurationManager.AppSettings["StripePlanId1"].ToString();
                        break;

                    case 2:
                        stripePlanId = ConfigurationManager.AppSettings["StripePlanId2"].ToString();
                        break;

                    case 3:
                        stripePlanId = ConfigurationManager.AppSettings["StripePlanId3"].ToString();
                        break;

                    case 4:
                        stripePlanId = ConfigurationManager.AppSettings["StripePlanId4"].ToString();
                        break;
                    }

                    if (!string.IsNullOrEmpty(stripePlanId))
                    {
                        try
                        {
                            telemetryClient.TrackEvent("Registration:Subscribe");

                            // Create a Stripe customer object and save the customer id.
                            var customerOptions = new CustomerCreateOptions
                            {
                                Email = user.EmailAddress
                            };
                            var             customers = new CustomerService();
                            Stripe.Customer customer  = customers.Create(customerOptions);
                            organization.StripeCustomerId = customer.Id;

                            // Subscribe the customer to the price and save the subscription id.
                            var subscriptionOptions = new SubscriptionCreateOptions
                            {
                                Customer = customer.Id, // ex. cus_IDjvN9UsoFp2mk
                                Items    = new List <SubscriptionItemOptions>
                                {
                                    new SubscriptionItemOptions
                                    {
                                        Price = stripePlanId // ex. price_1Hd5PvLI44a19MHX9w5EGD4r
                                    }
                                },
                                TrialFromPlan = true
                            };
                            var          subscriptions = new SubscriptionService();
                            Subscription subscription  = subscriptions.Create(subscriptionOptions);

                            organization.StripeSubscriptionId = subscription.Id;

                            // Send Welcome Email.
                            telemetryClient.TrackEvent("Registration:Email");

                            var apiKey   = ConfigurationManager.AppSettings["SendGridApiKey"].ToString();
                            var client   = new SendGridClient(apiKey);
                            var from     = new EmailAddress("BRIZBEE <*****@*****.**>");
                            var to       = new EmailAddress(user.EmailAddress);
                            var msg      = MailHelper.CreateSingleTemplateEmail(from, to, "d-8c48a9ad2ddd4d73b6e6c10307182f43", null);
                            var response = client.SendEmailAsync(msg);
                        }
                        catch (Exception ex)
                        {
                            telemetryClient.TrackException(ex);
                            return(BadRequest(ex.Message));
                        }
                    }

                    // Save the organization and user.
                    _context.Organizations.Add(organization);
                    user.OrganizationId = organization.Id;

                    _context.Users.Add(user);

                    _context.SaveChanges();

                    telemetryClient.TrackEvent("Registration:Succeeded");

                    transaction.Commit();

                    return(Created("auth/me", user));
                }
                catch (DbEntityValidationException ex)
                {
                    string message = "";

                    foreach (var eve in ex.EntityValidationErrors)
                    {
                        foreach (var ve in eve.ValidationErrors)
                        {
                            message += string.Format("{0} has error '{1}'; ", ve.PropertyName, ve.ErrorMessage);
                        }
                    }

                    telemetryClient.TrackException(ex);

                    return(BadRequest(message));
                }
                catch (Exception ex)
                {
                    transaction.Rollback();

                    telemetryClient.TrackException(ex);

                    return(BadRequest(ex.Message));
                }
            }
        }
Exemplo n.º 20
0
        public async Task <IActionResult> Status([FromBody] Sayonara.ViewModels.ExtractStatus dto)
        {
            if (String.IsNullOrEmpty(dto.PublicID))
            {
                return(StatusCode(404));
            }

            var extract = await _sayonaraContext.Extracts.SingleOrDefaultAsync(e => e.PublicID.Equals(new System.Guid(dto.PublicID)));

            if (extract != null)
            {
                if (extract.CompletionDate == null)                 //Don't want to update extracts that were already completed.
                {
                    extract.CurrentCount   = dto.CurrentCount;
                    extract.TotalCount     = dto.TotalCount;
                    extract.Status         = dto.Status;
                    extract.CompletionDate = dto.CompletionDate;
                    await _sayonaraContext.SaveChangesAsync();

                    //If email is setup, send a status email on complete (ComplettionDate.HasValue) or on failure (Status.Containts("failed")
                    if ((!String.IsNullOrEmpty(_sayonaraOptions.Value.SendGridAPIKey)) && ((dto.CompletionDate.HasValue) || (dto.Status.Contains("failed"))))
                    {
                        var extractFacility = await _sayonaraContext.Facilities.SingleOrDefaultAsync(f => f.ID == extract.FacilityID);

                        var client = new SendGridClient(_sayonaraOptions.Value.SendGridAPIKey);
                        var msg    = new SendGridMessage();

                        msg.From = new EmailAddress("*****@*****.**", _sayonaraOptions.Value.ApplicationName);
                        msg.AddTo(new EmailAddress(extract.CreatedBy, "Extract Creator"));

                        if (dto.CompletionDate.HasValue)
                        {
                            msg.Subject = extractFacility.Name + "'s extract is done";

                            string path;
                            if (extract.Format == ExtractType.CSV)
                            {
                                path = _sayonaraOptions.Value.ExtractFolder + "\\CSV";
                            }
                            else
                            {
                                path = _sayonaraOptions.Value.ExtractFolder + "\\PDF";
                            }

                            msg.PlainTextContent = "Extract is at " + path;
                        }
                        else
                        {
                            msg.Subject          = extractFacility.Name + "'s extract did not complete";
                            msg.PlainTextContent = "Extract did not succesfully complete. Check Status in Sayonara";
                        }

                        var response = await client.SendEmailAsync(msg);
                    }
                }
                return(Ok());
            }
            else
            {
                return(StatusCode(404));
            }
        }
Exemplo n.º 21
0
 public async Task SendEmailAsync(string email, string subject, string htmlMessage)
 {
     var client   = new SendGridClient(_apiKey);
     var msg      = MailHelper.CreateSingleEmail(new EmailAddress(_fromEmail), new EmailAddress(email), subject, "", htmlMessage);
     var response = await client.SendEmailAsync(msg);
 }
Exemplo n.º 22
0
        /// <summary>
        /// Sends out an email using SendGrid.
        /// Note: Updated to work with SendGrid version 9.8
        /// </summary>
        /// <returns>true if successful</returns>
        public static async Task <bool> SendGridEmail(string from, string to, List <string> cc, List <string> bcc, string subj, string body, string apiKey, string bodyHTML = null)
        {
            try
            {
                var client = new SendGridClient(apiKey);

                //******************** CONSTRUCT EMAIL ********************************************
                // Create the email object first, then add the properties.
                var msg = new SendGridMessage();

                // Add message properties.
                msg.Subject = subj;
                msg.AddContent(MimeType.Text, body);
                if (bodyHTML != null)
                {
                    msg.AddContent(MimeType.Html, bodyHTML);
                }
                msg.From = new EmailAddress(from);
                msg.AddTo(to);

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

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


                //******************** 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)
                {
                    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);
            }
        }
Exemplo n.º 23
0
 private void SendEmail()
 {
     var user             = UserManager.FindById(User.Identity.GetUserId());
     var apiKey           = "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";
     var client           = new SendGridClient(apiKey);
     var from             = new EmailAddress("*****@*****.**", "PlusB Service Desk Notification");
     var subject          = "Activity notification in incident No.  " + IDTicket;
     var to               = new EmailAddress(emailToSend, "Customer");
     var plainTextContent = "Incident Update";
     var htmlContent      = "<!doctype html> " +
                            "<html>" +
                            "<body style='background-color:#85A885;font-family:sans-serif;font-size:14px;-webkit-font-smoothing:antialiased;line-height:1.4;margin:0;padding:0;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;'>" +
                            "<br/>" +
                            "<br/>" +
                            "<table border='0' cellpadding='0'cellspacing='0' style='border-collapse:separate;mso-table-lspace:0pt;mso-table-rspace:0pt;width:100%;'>" +
                            " <tr>" +
                            "<td>&nbsp;</td>" +
                            "<td style='display:block;margin:0 auto !important;max-width:580px;padding:10px;width:580px;'>" +
                            "<div style='box-sizing:border-box;display: block;margin:0 auto;max-width:580px;padding:10px;'>" +
                            "<table style='background:#ffffff;border-radius:3px;width:100%;border-collapse:separate;mso-table-lspace:0pt;mso-table-rspace:0pt;width:100%;'>" +
                            "<tr>" +
                            "<td style='box-sizing:border-box;padding:20px;'>" +
                            "<table border='0' cellpadding='0'cellspacing='0' style='border-collapse:separate;mso-table-lspace:0pt;mso-table-rspace:0pt;width:100%;'>" +
                            "<tr>" +
                            "<td style='font-family:sans-serif;font-size:14px;vertical-align:top;'>" +
                            "<p>Hi there,</p>" +
                            "<p>An action occurred in an incident where you are owner. This is the update just sent by: " + user.Email + "</p>" +
                            "<table border='0' cellpadding='0'cellspacing='0' class='btn btn-primary'>" +
                            "<tbody>" +
                            "<tr>" +
                            "<td align='left'>" +
                            "<table border='0' cellpadding='0'cellspacing='0'>" +
                            "   <tbody>" +
                            "      <tr>" +
                            "         <td style='text-align:center;'><a><strong>" + activityToSend + "</strong></a></td>" +
                            "        </tr>" +
                            "       </tbody>" +
                            "      </table>" +
                            "     </td>" +
                            "    </tr>" +
                            "   </tbody>" +
                            "  </table>" +
                            "   <br/>" +
                            "   <p style='font-size:12px;'>This is an automatic email sent by the PlusB Consulting Service Desk system.</p>" +
                            "    <p style='font-size:12px;'>Thanks for being part of our business!</p>" +
                            "   </td>" +
                            "  </tr>" +
                            "  </table>" +
                            "  </td>" +
                            " </tr>" +
                            "</table>" +
                            "<br/>" +
                            "<div style='clear:both;margin-top:10px;width:100%;'>" +
                            "<table border='0' cellpadding='0' cellspacing='0' style='border-collapse:separate;mso-table-lspace:0pt;mso-table-rspace:0pt;width:100%;'>" +
                            "<tr><br/>" +
                            "<td style='padding-bottom:10px;padding-top:10px;text-decoration:none;color:#000;font-size:12px;'>" +
                            "PlusB Consulting Escazú, San José Costa Rica" +
                            "Don't like these emails? <a>Unsubscribe</a>." +
                            " </td>" +
                            "</tr>" +
                            "<tr>" +
                            "<td style='padding-bottom:10px;padding-top:10px;text-decoration:none;color:#000;font-size:12px;'>" +
                            "Powered by <a>PlusB Consulting S.A</a>." +
                            "</td>" +
                            "</tr>" +
                            "</table>" +
                            "</div" +
                            "</div>" +
                            "</td>" +
                            "<td style='color:#000;font-size:12px;'>&nbsp;</td>" +
                            "</tr>" +
                            "</table>" +
                            "</body>" +
                            "</html>";
     var msg      = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
     var response = client.SendEmailAsync(msg);
 }
        public static async Task <JObject> SendEmailSASUri(HttpRequest req, Logging logging)
        {
            string  requestBody     = new StreamReader(req.Body).ReadToEndAsync().Result;
            dynamic taskInformation = JsonConvert.DeserializeObject(requestBody);

            string _TaskInstanceId = taskInformation["TaskInstanceId"].ToString();
            string _ExecutionUid   = taskInformation["ExecutionUid"].ToString();

            try
            {
                //Get SAS URI
                string _blobStorageAccountName   = taskInformation["Source"]["StorageAccountName"].ToString();
                string _blobStorageContainerName = taskInformation["Source"]["StorageAccountContainer"].ToString();
                string _blobStorageFolderPath    = taskInformation["Source"]["RelativePath"].ToString();
                string _dataFileName             = taskInformation["Source"]["DataFileName"].ToString();
                int    _accessDuration           = (int)taskInformation["Source"]["SasURIDaysValid"];
                string _targetSystemUidInPHI     = taskInformation["Source"]["TargetSystemUidInPHI"];
                string _FileUploaderWebAppURL    = taskInformation["Source"]["FileUploaderWebAppURL"];

                string SASUri = Storage.CreateSASToken(_blobStorageAccountName, _blobStorageContainerName, _blobStorageFolderPath, _dataFileName, _accessDuration);

                //Send Email
                string _emailRecipient        = taskInformation["Target"]["EmailRecipient"].ToString();
                string _emailRecipientName    = taskInformation["Target"]["EmailRecipientName"].ToString();
                string _emailTemplateFileName = taskInformation["Target"]["EmailTemplateFileName"].ToString();
                string _senderEmail           = taskInformation["Target"]["SenderEmail"].ToString();
                string _senderDescription     = taskInformation["Target"]["SenderDescription"].ToString();
                string _subject = taskInformation["Target"]["EmailSubject"].ToString();

                //Get Plain Text and Email Subject from Template Files
                Dictionary <string, string> Params = new Dictionary <string, string>
                {
                    { "NAME", _emailRecipientName },
                    { "SASTOKEN", SASUri },
                    { "FileUploaderUrl", _FileUploaderWebAppURL },
                    { "TargetSystemUidInPHI", _targetSystemUidInPHI },
                };
                string _plainTextContent = System.IO.File.ReadAllText(Shared.GlobalConfigs.GetStringConfig("HTMLTemplateLocation") + _emailTemplateFileName + ".txt");
                _plainTextContent = _plainTextContent.FormatWith(Params, MissingKeyBehaviour.ThrowException, null, '{', '}');

                string _htmlContent = System.IO.File.ReadAllText(Shared.GlobalConfigs.GetStringConfig("HTMLTemplateLocation") + _emailTemplateFileName + ".html");
                _htmlContent = _htmlContent.FormatWith(Params, MissingKeyBehaviour.ThrowException, null, '{', '}');

                var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
                var client = new SendGridClient(new SendGridClientOptions {
                    ApiKey = apiKey, HttpErrorAsException = true
                });
                var msg = new SendGridMessage()
                {
                    From             = new EmailAddress(_senderEmail, _senderDescription),
                    Subject          = _subject,
                    PlainTextContent = _plainTextContent,
                    HtmlContent      = _htmlContent
                };
                msg.AddTo(new EmailAddress(_emailRecipient, _emailRecipientName));
                try
                {
                    var response = await client.SendEmailAsync(msg).ConfigureAwait(false);

                    logging.LogInformation($"SendGrid Response StatusCode - {response.StatusCode}");
                }
                catch (Exception ex)
                {
                    SendGridErrorResponse errorResponse = JsonConvert.DeserializeObject <SendGridErrorResponse>(ex.Message);
                    logging.LogInformation($"Error Message - {ex.Message}");
                    throw new Exception("Could not send email");
                }

                //Update Task Instace

                TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();
                TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.Complete, Guid.Empty, "");

                JObject Root = new JObject
                {
                    ["Result"] = "Complete"
                };

                return(Root);
            }
            catch (Exception TaskException)
            {
                logging.LogErrors(TaskException);
                TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();
                TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.FailedRetry, Guid.Empty, "Failed when trying to Generate Sas URI and Send Email");

                JObject Root = new JObject
                {
                    ["Result"] = "Failed"
                };

                return(Root);
            }
        }
Exemplo n.º 25
0
    private static async Task SendEmail(List <Site> siteList, Settings settings)
    {
        if (siteList is null)
        {
            throw new ArgumentNullException(nameof(siteList));
        }

        if (settings is null)
        {
            throw new ArgumentNullException(nameof(settings));
        }

        if (siteList.Count == 0)
        {
            return;
        }

        StringBuilder plainTextContent = new StringBuilder();
        StringBuilder htmlContent      = new StringBuilder();

        htmlContent.Append(@"
<!DOCTYPE html>
<html>
<head>
<title>Certificate status</title>

<style type='text/css'>
a:link {
    text-decoration: none;
    color: black;
}

a:visited {
    text-decoration: none;
    color: black;
}

a:hover {
    text-decoration: underline;
    color: black;
}

a:active {
    text-decoration: underline;
    color: black;
}

.error {
    background-color: red;
    color: black;
}

.warning {
    background-color: orange;
    color: black;
}

.info {
    background-color: yellow;
    color: black;
}
</ style >
</head>
<body>
    <table>
        <tr>
            <th>Site</th>
            <th>Valid to</th>
            <th>Expires in (days)</th>
        </tr>");

        foreach (var site in siteList)
        {
            if (site.ValidDays < 1)
            {
                htmlContent.Append("<tr class=\"error\">");
            }
            else if (site.ValidDays < 7)
            {
                htmlContent.Append("<tr class=\"warning\">");
            }
            else if (site.ValidDays < 30)
            {
                htmlContent.Append("<tr class=\"info\"");
            }
            else
            {
                htmlContent.Append("<tr>");
            }

            htmlContent.Append($"<th>{site.Url}</th>");
            htmlContent.Append($"<th>{site.ValidTo.Date}</th>");
            htmlContent.Append($"<th>{site.ValidDays}</th>");
            htmlContent.Append("</tr>");

            string errorText = string.Empty;

            if (site.ValidDays < 0)
            {
                errorText = $"ERROR: Certificate expired {site.ValidDays} days ago";
            }
            else if (site.ValidDays < 7)
            {
                errorText = $"WARNING: Certificate expires in {site.ValidDays} days";
            }
            else if (site.ValidDays < 30)
            {
                errorText = $"INFO: Certificate expires in {site.ValidDays} days";
            }
            plainTextContent.Append($"{site.Url}{Environment.NewLine}");
            if (!string.IsNullOrEmpty(errorText))
            {
                plainTextContent.Append($"{errorText}");
            }

            plainTextContent.Append($"Valid from: {site.ValidFrom}{Environment.NewLine}");
            plainTextContent.Append($"Valid to: {site.ValidTo}{Environment.NewLine}");
            plainTextContent.Append($"Expires in: {site.ValidDays} days{Environment.NewLine}");
            plainTextContent.Append($"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}");
        }

        htmlContent.Append(@"
</body>
</html>");

        var apiKey = settings.SendGrid;
        var client = new SendGridClient(apiKey);

        var from    = new EmailAddress(settings.From.Email, settings.From.DisplayName);
        var subject = "Status for certificates";

        var to = new List <EmailAddress>(settings.To.Count);

        foreach (var t in settings.To)
        {
            to.Add(new EmailAddress(t.Email, t.DisplayName));
        }

        var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, to, subject, plainTextContent.ToString(), htmlContent.ToString());
        await client.SendEmailAsync(msg);
    }
        public async Task MarketPlaceNotify([TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            var account    = CloudStorageAccount.Parse(_configuration["AzureWebJobsStorage"]);
            var client     = account.CreateCloudTableClient();
            var cloudTable = client.GetTableReference(_configuration["table"]);
            var date       = DateTime.Now.AddMinutes(-int.Parse(_configuration["CronInterval"])).AddSeconds(-int.Parse(_configuration["CronThreshold"]));
            var result     = await cloudTable.ExecuteQuerySegmentedAsync(new TableQuery <MarketPlaceEntity>()
                                                                         .Where(TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual, date)), null)
                             .ConfigureAwait(false);

            var count = result.Count();

            if (count > 0)
            {
                var html = new StringBuilder();
                html.Append(@"
                    <html>
                        <head>
                            <style>
                                table {
                                    border-collapse: collapse;
                                    table-layout:fixed; 
                                    width:1000px;
                                }
            
                                table, td, th {
                                    border: 1px solid black;
                                }
                                table td {border:solid 1px #fab; width:100px; word-wrap:break-word;}
                            </style>
                        </head>");

                html.Append($@"
                    <body>
                        <h4>Dear {_configuration["SendGridToUser"]}</h4> 
                        <br>
                        <p>You have new Azure Market place Notification</p>
                        <p>Details:</p>                        
                        <br>
                        <table>
                            <thead>
                                <th>Lead Source</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Phone</th>
                                <th>Country</th>
                                <th>Company</th>
                                <th>Title</th>
                                <th>Date</th>
                            </thead>
                            <tbody>");


                result.ToList().ForEach(r =>
                {
                    var ci = JsonConvert.DeserializeObject <CustomerInfo>(r.CustomerInfo);
                    html.Append($@"
                                    <tr>
                                        <td>{r.LeadSource}</td>
                                        <td>{ci.FirstName} {ci.LastName}</td>
                                        <td>{ci.Email}</td>
                                        <td>{ci.Phone}</td>
                                        <td>{ci.Country}</td>
                                        <td>{ci.Company}</td>
                                        <td>{ci.Title ?? ""}</td>
                                        <td>{r.Timestamp.UtcDateTime.ToString("dd MMMM yyyy HH:mm:ss")} UTC</td> 
                                    </tr> 
                    ");
                });
                html.Append($@"  </tbody>
                                </table>
                            </body>
                        </html>");

                var sendGridClient = new SendGridClient(_configuration["SendGridApiKey"]);
                var msg            = new SendGridMessage();
                msg.SetFrom(new EmailAddress(_configuration["SendGridFromEmail"], _configuration["SendGridFromUser"]));
                msg.SetSubject(_configuration["SendGridSubject"]);
                msg.AddContent(MimeType.Html, html.ToString());
                msg.AddTo(new EmailAddress(_configuration["SendGridToEmail"], _configuration["SendGridToUser"]));
                var response = await sendGridClient.SendEmailAsync(msg).ConfigureAwait(false);
            }
        }
        public virtual DeliverResponse Deliver(MailMessage mailMessage)
        {
            ValidateBeforeDelivery(mailMessage);

            var sendGridMessage = new SendGridMessage
            {
                From = new EmailAddress(mailMessage.From.Address)
            };

            //Override the to addresses if needed
            if (this.HasToAddressOverride)
            {
                var overrideMailAddresses = new[] { new MailAddress(this.ToAddressOverride) };

                foreach (var overrideMailAddress in overrideMailAddresses)
                {
                    sendGridMessage.AddTo(overrideMailAddress.Address);
                }
            }
            else
            {
                foreach (var to in mailMessage.To)
                {
                    sendGridMessage.AddTo(to.Address);
                }

                foreach (var cc in mailMessage.CC)
                {
                    sendGridMessage.AddCc(cc.Address);
                }

                foreach (var bcc in mailMessage.Bcc)
                {
                    sendGridMessage.AddBcc(bcc.Address);
                }
            }

            sendGridMessage.Subject = mailMessage.Subject;

            if (mailMessage.IsBodyHtml)
            {
                sendGridMessage.HtmlContent = mailMessage.Body;
            }
            else
            {
                sendGridMessage.PlainTextContent = mailMessage.Body;
            }

            //Add the attachments if any
            foreach (var attachment in mailMessage.Attachments)
            {
                Byte[] attachmentBytes   = StreamToBytes(attachment.ContentStream);
                var    attachmentContent = Convert.ToBase64String(attachmentBytes);

                if (attachment.ContentStream != null && attachment.Name != null)
                {
                    sendGridMessage.AddAttachment(attachment.Name, attachmentContent);
                }

                //, attachment.ContentDisposition.ToString()
            }

            var client = new SendGridClient(this.ApiKey);

            var response = client.SendEmailAsync(sendGridMessage);

            var result = response.Result;

            var statusCode = result.StatusCode.ToString();

            return(new DeliverResponse
            {
                StatusCode = statusCode, Success = statusCode == "Accepted"
            });
        }
Exemplo n.º 28
0
        public async Task <IEmailResponse> SendSingleEmailAsync(IEmailContent email)
        {
            email.ThrowIfNull(nameof(email));

            return(new SendGridResponse(await _client.SendEmailAsync(Message(email))));
        }
Exemplo n.º 29
0
 private async Task <Response> Send(SendGridMessage message)
 {
     return(await _Client.SendEmailAsync(message));
 }
Exemplo n.º 30
0
 private async Task SendEmail(SendGridMessage msg)
 {
     var apiKey = _config.SendGridApiKey;
     var client = new SendGridClient(apiKey);
     await client.SendEmailAsync(msg);
 }