private async Task <SendNotificationResult> SendNotificationAsync(Notification notification)
        {
            var retVal         = new SendNotificationResult();
            var apiKey         = _settingsManager.GetSettingByName(_sendGridApiKeySettingName).Value;
            var sendGridClient = new SendGridAPIClient(apiKey);

            var from    = new Email(notification.Sender);
            var to      = new Email(notification.Recipient);
            var content = new Content("text/html", notification.Body);
            var mail    = new Mail(from, notification.Subject, to, content);

            mail.ReplyTo = from;

            try
            {
                SendGrid.CSharp.HTTP.Client.Response result = await sendGridClient.client.mail.send.post(requestBody : mail.Get());

                retVal.IsSuccess = result.StatusCode == HttpStatusCode.Accepted;
                if (!retVal.IsSuccess)
                {
                    retVal.ErrorMessage = result.StatusCode.ToString() + ":" + await result.Body.ReadAsStringAsync();
                }
            }
            catch (Exception ex)
            {
                retVal.ErrorMessage = ex.Message;
            }
            return(retVal);
        }
Exemple #2
0
        public async Task SendEmailAsync(string recipient, string subject, string message)
        {
            if (string.IsNullOrWhiteSpace(recipient))
            {
                var user = await GetCurrentUser();

                recipient = user.Email;
            }
            string apiKey = Options.SendGridAppKey;
            var    sg     = new SendGridAPIClient(apiKey);

            var from = new Email("*****@*****.**");
            var to   = new Email(recipient);
            var text = new Content("text/plain", message);
            var html = new Content("text/html", $@"<!DOCTYPE HTML>
            <html>
            <head>
            <meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"" />
            </head>
            <body>{message}</body></html>");
            var mail = new Mail(from, subject, to, text);

            mail.AddContent(html);

            // Escape quotes per https://github.com/sendgrid/sendgrid-csharp/issues/245
            var     body     = mail.Get().Replace("'", "\\\"");
            dynamic response = sg.client.mail.send.post(requestBody: body);
            var     code     = response.StatusCode;
            var     res      = response.Body.ReadAsStringAsync().Result;
            var     head     = response.Headers.ToString();
        }
        public SendGridAPIClient GetInstance(string envVar, EnvironmentVariableTarget target)
        {
            var apiKey = Environment.GetEnvironmentVariable(envVar, target);
            var sg     = new SendGridAPIClient(apiKey);

            return(sg);
        }
 protected override void DisposeInternal()
 {
     if (_sendGridApi != null)
     {
         _sendGridApi = null;
     }
 }
Exemple #5
0
        // Use NuGet to install SendGrid (Basic C# client lib)
        private async Task configSendGridasync(IdentityMessage message)
        {
            var     apiKey = ConfigurationManager.AppSettings["sendGridApiKey"];
            dynamic sg     = new SendGridAPIClient(apiKey);

            Mail mail = new Mail();

            Content content = new Content();

            content.Type  = "text/plain";
            content.Value = message.Body;
            mail.AddContent(content);
            content       = new Content();
            content.Type  = "text/html";
            content.Value = message.Body;
            mail.AddContent(content);

            mail.From    = new Email("*****@*****.**", "ZenZoy");
            mail.Subject = message.Subject;

            Personalization personalization = new Personalization();
            var             emailTo         = new Email();

            emailTo.Name    = message.Destination;
            emailTo.Address = message.Destination;
            personalization.AddTo(emailTo);
            mail.AddPersonalization(personalization);

            dynamic response = sg.client.mail.send.post(requestBody: mail.Get());

            var status       = response.StatusCode;
            var responseBody = await response.Body.ReadAsStringAsync();
        }
Exemple #6
0
        public SendNotificationResult SendNotification(Notification notification)
        {
            var retVal         = new SendNotificationResult();
            var apiKey         = _settingsManager.GetSettingByName(_sendGridApiKeySettingName).Value;
            var sendGridClient = new SendGridAPIClient(apiKey);

            var from    = new Email(notification.Sender);
            var to      = new Email(notification.Recipient);
            var content = new Content("text/html", notification.Body);
            var mail    = new Mail(from, notification.Subject, to, content);

            mail.ReplyTo = from;

            try
            {
                Task.Run(async() => await sendGridClient.client.mail.send.post(mail.Get())).Wait();
                retVal.IsSuccess = true;
            }
            catch (Exception ex)
            {
                retVal.ErrorMessage = ex.Message;
            }

            return(retVal);
        }
        private Mail Map(MailRequest request)
        {
            var mail            = new Mail();
            var personalization = new Personalization();

            if (string.IsNullOrWhiteSpace(_apiKey))
            {
                throw new ArgumentNullException(nameof(_apiKey));
            }

            _sendGridApi = new SendGridAPIClient(_apiKey);

            foreach (var mailAddress in request.To)
            {
                personalization.Tos.Add(new Email(mailAddress.ToString()));
            }

            foreach (var bccAddress in request.Bcc)
            {
                personalization.Bccs.Add(new Email(bccAddress.ToString()));
            }

            foreach (var ccAddress in request.Cc)
            {
                personalization.AddCc(new Email(ccAddress.ToString()));
            }

            mail.AddPersonalization(personalization);
            mail.Subject = request.Subject;
            return(mail);
        }
Exemple #8
0
            public async Task SendAsync(IdentityMessage message)
            {
                var content = new SendGrid.Helpers.Mail.Content();

                content.Type  = "text/html";
                content.Value = message.Body;

                var msg = new SendGrid.Helpers.Mail.Mail(
                    new SendGrid.Helpers.Mail.Email("*****@*****.**", CONSTANTS.SYSTEM_USER_NAME),
                    message.Subject,
                    new SendGrid.Helpers.Mail.Email(message.Destination),
                    content
                    );

                var trackingSettings = new SendGrid.Helpers.Mail.TrackingSettings();

                trackingSettings.ClickTracking        = new SendGrid.Helpers.Mail.ClickTracking();
                trackingSettings.OpenTracking         = new SendGrid.Helpers.Mail.OpenTracking();
                trackingSettings.ClickTracking.Enable = false;
                trackingSettings.OpenTracking.Enable  = false;
                msg.TrackingSettings = trackingSettings;

                dynamic sendGridClient = new SendGridAPIClient(Settings.EmailServiceKey);

                var response = await sendGridClient.client.mail.send.post(requestBody : msg.Get());
            }
Exemple #9
0
        public async Task SendAsync(IdentityMessage message)
        {
            //var myMessage = new SendGridMessage();
            //myMessage.AddTo(message.Destination);
            //myMessage.From = new MailAddress("*****@*****.**", "fzrain");
            //myMessage.Subject = message.Subject;
            //myMessage.Text = message.Body;
            //myMessage.Html = message.Body;

            //var credentials = new NetworkCredential("fzy55601", "fzy86087108");
            //// Create a Web transport for sending email.
            //var transportWeb = new Web(credentials);
            //// Send the email.
            //await transportWeb.DeliverAsync(myMessage);

            String  apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY", EnvironmentVariableTarget.User);
            dynamic sg     = new SendGridAPIClient(apiKey);

            Email   from    = new Email("*****@*****.**");
            String  subject = "Hello World from the SendGrid CSharp Library";
            Email   to      = new Email("*****@*****.**");
            Content content = new Content("text/plain", "Textual content");
            Mail    mail    = new Mail(from, subject, to, content);

            dynamic response = sg.client.mail.send.post(requestBody: mail.Get());
        }
        public async Task SendHtmlEmail(string subject, string toEmail, string content)
        {
            string  apiKey = _configurationService.Email.ApiKey;
            dynamic sg     = new SendGridAPIClient(apiKey);

            Email   from        = new Email(_configurationService.Email.From);
            Email   to          = new Email(toEmail);
            Content mailContent = new Content("text/html", content);
            Mail    mail        = new Mail(from, subject, to, mailContent);

            var personalization = new Personalization();

            personalization.AddTo(to);

            if (_configurationService.Email.Bcc != null && _configurationService.Email.Bcc.Any())
            {
                foreach (var bcc in _configurationService.Email.Bcc)
                {
                    personalization.AddBcc(new Email(bcc));
                }
                mail.AddPersonalization(personalization);
            }

            dynamic response = await sg.client.mail.send.post(requestBody : mail.Get());

            if (response.StatusCode != System.Net.HttpStatusCode.Accepted)
            {
                var responseMsg = response.Body.ReadAsStringAsync().Result;
                _logger.Error($"Unable to send email: {responseMsg}");
            }
        }
Exemple #11
0
        public Task SendEmailAsync(string email, string subject, string message)
        {
            // Plug in your email service here to send an email.
            var     apiKey = _appCodes.SendGridApiKey;
            dynamic sg     = new SendGridAPIClient(apiKey);

            var from = new Email("*****@*****.**", "CIS-Do Not Reply");
            var to   = new Email("*****@*****.**", "Lee Humphries");
            //var to = new Email("*****@*****.**", "Obike NZ");
            //Email[] cc = { to, new Email("*****@*****.**"), new Email("*****@*****.**"), new Email("*****@*****.**"), new Email("*****@*****.**") };

            var     content  = new Content("text/plain", message);
            var     mail     = new Mail(from, subject, to, content);
            dynamic response = sg.client.mail.send.post(requestBody: mail.Get());
            var     respCode = response.StatusCode as HttpStatusCode?;

            if (!respCode.HasValue)
            {
                return(Task.FromException(new Exception("Attempted to send message, but no response was returned.")));
            }
            switch (respCode.Value)
            {
            case HttpStatusCode.Accepted:
                break;

            default:
                return(Task.FromException(new Exception(
                                              $"Attempted to send message, the HTTP response ({respCode.Value}) was returned.")));
            }

            return(Task.FromResult(0));
        }
Exemple #12
0
        public async Task ProcessMessagesAsync(CancellationToken token)
        {
            CloudQueue queue = _queueClient.GetQueueReference(mailQueueName);
            await queue.CreateIfNotExistsAsync();

            while (!token.IsCancellationRequested)
            {
                // The default timeout is 90 seconds, so we won’t continuously poll the queue if there are no messages.
                // Pass in a cancellation token, because the operation can be long-running.
                CloudQueueMessage message = await queue.GetMessageAsync(token);

                if (message != null)
                {
                    IMailMessage mailMessage = JsonConvert.DeserializeObject <MailMessage>(message.AsString);

                    string  apiKey = "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";
                    dynamic sg     = new SendGridAPIClient(apiKey);

                    Email  from    = new Email(mailMessage.From);
                    string subject = mailMessage.Subject;
                    Email  to      = new Email(mailMessage.To);

                    Content content = new Content("text/html", mailMessage.Body);
                    Mail    mail    = new Mail(from, subject, to, content);
                    //mail.TemplateId = "451f5afd-498d-4117-af97-e815cdb98560";
                    //mail.Personalization[0].AddSubstitution("-name", model.Name);
                    //mail.Personalization[0].AddSubstitution("-pwd-", model.Password);

                    dynamic response = await sg.client.mail.send.post(requestBody : mail.Get());

                    queue.DeleteMessage(message);
                }
            }
        }
Exemple #13
0
        private async Task <int> SendMassEmailAsync(CustomEmailViewModel model, Dictionary <string, string> recipients)
        {
            string baseBody = this.RenderPartialViewToString("EmailShell", model);

            //SendGrid.Web transportWeb = new SendGrid.Web(ConfigurationManager.AppSettings["sendgrid:APIKey"]);
            SendGridAPIClient sendGrid = new SendGridAPIClient(ConfigurationManager.AppSettings["sendgrid:APIKey"]);

            int count = 0;

            foreach (KeyValuePair <string, string> recipient in recipients)
            {
                //SendGridMessage message = new SendGridMessage
                //{
                //    From = new MailAddress("*****@*****.**", "Becky & Nick"),
                //    Subject = model.Subject,
                //    Html = baseBody.Replace("-recipientName-", recipient.Key)
                //};

                Mail mail = new Mail(new Email("*****@*****.**", "Nick & Rebecca"), model.Subject, new Email(recipient.Value, recipient.Key), new Content("text/html", baseBody.Replace("-recipientName-", recipient.Key)));

                await sendGrid.client.mail.send.post(requestBody : mail.Get());

                //message.AddTo($"{recipient.Key} <{recipient.Value}>");

                //await transportWeb.DeliverAsync(message);

                count++;
            }

            return(count);
        }
        public SendGridAPIClient GetInstance(RestApiCredentialsRequest input)
        {
            var apiCredentials = _credentialsService.GetRestApiCredentials(input);
            var sg             = new SendGridAPIClient(apiCredentials.Key);

            return(sg);
        }
 public SendGridService(ISendGridCredentialsService sendGridCredentialsService)
 {
     _sendGrid = sendGridCredentialsService.GetInstance(new RestApiCredentialsRequest()
     {
         ApiKeyName = "SendGridKey",
         Strategy   = Strategy.EnvVar
     });
 }
Exemple #16
0
        public async Task <IHttpActionResult> RegisterUser(Poco.User credentials)
        {
            if (string.IsNullOrWhiteSpace(credentials.Email))
            {
                return(BadRequest("The email is not valid!"));
            }

            if (string.IsNullOrWhiteSpace(credentials.Password))
            {
                return(BadRequest("The password is not valid!"));
            }

            try
            {
                using (var ctx = new ChattyDbContext())
                {
                    User user = ctx.Users.SingleOrDefault(x => x.Email == credentials.Email);
                    if (user != null)
                    {
                        return(InternalServerError(new InvalidOperationException("This email has already taken!")));
                    }

                    user = new User {
                        Email = credentials.Email, Password = credentials.Password
                    };
                    user.Ticket = Guid.NewGuid().ToString();
                    ctx.Users.Add(user);
                    ctx.SaveChanges();

                    string            apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
                    SendGridAPIClient mc     = new SendGridAPIClient(apiKey);

                    Email   to      = new Email(user.Email);
                    Email   from    = new Email("*****@*****.**");
                    string  subject = "Welocme to Chatty!";
                    Content content = new Content("text/plain",
                                                  String.Format("Hi {0},\n\nYou registration on Chatty is almost complete. Please click on this link to confirm your registration!\n\n{1}",
                                                                user.Email.Split('@')[0],
                                                                String.Format("https://chatty-api.azurewebsites.net/users/confirm?ticket={0}", user.Ticket)));
                    Mail mail = new Mail(from, subject, to, content);

                    dynamic response = await mc.client.mail.send.post(requestBody : mail.Get());

                    return(Ok(Dto.Wrap(new Poco.User
                    {
                        UserId = user.UserId,
                        Email = user.Email,
                        AuthAccessToken = null,
                        AuthExpirationDate = null
                    })));
                }
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
        private async Task SendEmailAsyncViaSendGrid(string to, string subject, string body)
        {
            SendGridAPIClient sendGridClient;
            string            apiKey = System.Configuration.ConfigurationManager.AppSettings["KeySendGrid"];

            sendGridClient = new SendGridAPIClient(apiKey);

            Mail mail = ConfigMail(to, subject, body);
            await sendGridClient.client.mail.send.post(requestBody : mail.Get());
        }
Exemple #18
0
 static async Task Execute(IdentityMessage message)
 {
     string  apiKey   = ConfigurationManager.AppSettings["SGAPIKEY"];
     dynamic sg       = new SendGridAPIClient(apiKey);
     Email   from     = new Email("*****@*****.**");
     string  subject  = "Confirm Email address";
     Email   to       = new Email(message.Destination);
     Content content  = new Content("text/html", message.Body);
     Mail    mail     = new Mail(from, subject, to, content);
     dynamic response = await sg.client.mail.send.post(requestBody : mail.Get());
 }
Exemple #19
0
        public async Task SendAsync(IdentityMessage message)
        {
            string  apiKey = "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";
            dynamic sg     = new SendGridAPIClient(apiKey);

            Content content = new Content("text/html", message.Body);
            Email   from    = new Email("*****@*****.**");
            Email   to      = new Email(message.Destination);
            Mail    mail    = new Mail(from, message.Subject, to, content);

            dynamic response = await sg.client.mail.send.post(requestBody : mail.Get());
        }
Exemple #20
0
        public async Task <dynamic> SendEmailAsync(string recipient, string subjectLine, string content)
        {
            dynamic sg = new SendGridAPIClient(apiKey); // SendGrid's client is a giant tree of dynamics, wtf

            Email   from         = new Email(systemEmail);
            string  subject      = subjectLine;
            Email   to           = new Email(recipient);
            Content contentBlock = new Content("text/html", content);
            Mail    mail         = new Mail(from, subject, to, contentBlock);

            return(await sg.client.mail.send.post(requestBody : mail.Get()));
        }
Exemple #21
0
        // Use NuGet to install SendGrid (Basic C# client lib)
        private async Task configSendGridasync(IdentityMessage message)
        {
            dynamic sg = new SendGridAPIClient(
                "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");

            var     from     = new Email("*****@*****.**");
            var     to       = new Email(message.Destination);
            var     content  = new Content("text/plain", message.Body);
            var     mail     = new Mail(from, message.Subject, to, content);
            dynamic response = await sg.client.mail.send.post(
                requestBody : mail.Get());
        }
Exemple #22
0
        public Task SendAsync(IdentityMessage message)
        {
            var sg      = new SendGridAPIClient(ConfigurationManager.AppSettings["sendGridApiKey"]);
            var from    = new Email("*****@*****.**");
            var subject = message.Subject;
            var to      = new Email(message.Destination);
            var content = new Content("text/html", message.Body);
            var mail    = new Mail(from, subject, to, content);

            sg.client.mail.send.post(requestBody: mail.Get());
            return(Task.FromResult(0));
        }
Exemple #23
0
        private async Task configSendGridasync(IdentityMessage message)
        {
            dynamic sg = new SendGridAPIClient(Environment.GetEnvironmentVariable("SENDGRID", EnvironmentVariableTarget.User));
            Email   to = new Email(message.Destination);
            //    Email to = new Email("*****@*****.**");
            Email from = new Email("*****@*****.**");

            //       Email from = new Email("*****@*****.**");
            SendGrid.Helpers.Mail.Content content = new SendGrid.Helpers.Mail.Content("text/html", message.Body);
            Mail mail = new Mail(from, message.Subject, to, content);

            dynamic response = await sg.client.mail.send.post(requestBody : mail.Get());
        }
Exemple #24
0
        /// <summary>
        /// send a message with send grid api key async
        /// </summary>
        /// <param name="message"></param>
        public static async Task SendGridApiAsync(string sendGridApiKey, MessageCredential credential, MessageSend message)
        {
            dynamic sg = new SendGridAPIClient(sendGridApiKey);

            var mail = PrepareSendGridMessage(credential, message);

            dynamic response = await sg.client.mail.send.post(requestBody : mail.Get());

            if (response.StatusCode != HttpStatusCode.Accepted)
            {
                throw new Exception(string.Format("Error {0}, please check {1}", response.StatusCode, "https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html"));
            }
        }
Exemple #25
0
        static async Task SendEmail()
        {
            string  apiKey = @"your_SendGrid_Key";
            dynamic sg     = new SendGridAPIClient(apiKey);

            Email   from    = new Email("home@localhost");
            string  subject = "PC is ready";
            Email   to      = new Email("*****@*****.**");
            Content content = new Content("text/plain", $"PC was turned on at {DateTime.UtcNow}");
            Mail    mail    = new Mail(from, subject, to, content);

            dynamic response = await sg.client.mail.send.post(requestBody : mail.Get());
        }
        public void SendDeck(string recipient)
        {
            string            apiKey = "enter api here";
            SendGridAPIClient sg     = new SendGridAPIClient(apiKey);

            Email   from    = new Email("*****@*****.**");
            string  subject = "Hello from Flashato";
            Email   to      = new Email(recipient);
            Content content = new Content("text/plain", "Hello there");
            Mail    mail    = new Mail(from, subject, to, content);

            dynamic response = sg.client.mail.send.post(requestBody: mail.Get());
        }
        public static async Task SendMail(EmailData emailData)
        {
            string apiKey = "YOUR API KEY FROM SENDGRID WEBSITE";
            var    sg     = new SendGridAPIClient(apiKey);

            Email   from    = new Email(emailData.FromEmailAddress);
            string  subject = emailData.Subject;
            Email   to      = new Email(emailData.ToEmailAddress);
            Content content = new Content("text/html", emailData.Content);
            Mail    mail    = new Mail(from, subject, to, content);

            var response = await sg.client.mail.send.post(requestBody : mail.Get());
        }
Exemple #28
0
        public void Send(string recipient, string subject, string body)
        {
            string apiKey = ConfigurationManager.AppSettings["SendGridApiKey"];

            dynamic sg = new SendGridAPIClient(apiKey);

            Email   from    = new Email(ConfigurationManager.AppSettings["SendFrom"], "BeerScheduler Support");
            Email   to      = new Email(recipient);
            Content content = new Content("text/html", body);
            Mail    mail    = new Mail(from, subject, to, content);

            sg.client.mail.send.post(requestBody: mail.Get());
        }
Exemple #29
0
        public static async Task SendMail(string email, string subject, string content)
        {
            string apiKey = GetConfigValue("SendGridPrivateKey");

            dynamic sg = new SendGridAPIClient(apiKey);

            Email   from         = new Email("*****@*****.**");
            Email   to           = new Email(email);
            Content innerContent = new Content("text/html", content);
            Mail    mail         = new Mail(from, subject, to, innerContent);

            dynamic response = await sg.client.mail.send.post(requestBody : mail.Get());
        }
Exemple #30
0
        public async Task SendAsync(IdentityMessage message)
        {
            var     apiKey = System.Configuration.ConfigurationManager.ConnectionStrings["SendGridAPI"].ConnectionString;
            dynamic sg     = new SendGridAPIClient(apiKey);

            Email   from    = new Email(email: FromAddress.Address, name: FromAddress.DisplayName);
            string  subject = message.Subject;
            Email   to      = new Email(message.Destination);
            Content content = new Content("text/plain", message.Body);
            Mail    mail    = new Mail(from, subject, to, content);

            dynamic response = await sg.client.mail.send.post(requestBody : mail.Get());
        }