public void ScheduleMulti()
        {
            var client = new SendGridClient(ConfigurationManager.AppSettings["ApiKey"]);

            var sendAt = DateTimeOffset.Now.AddMinutes(15);

            for (int i = 0; i < 5; i++)
            {
                var message = new SendGridMessage();

                message.To.Add(ConfigurationManager.AppSettings["MailTo"]);
                message.From = ConfigurationManager.AppSettings["MailFrom"];

                message.Header.AddSubstitution("-name-", "抱かれたい男 No.1");
                message.Header.AddSendAt(sendAt);

                message.Subject = "-name- さんへ" + i;
                message.Text = "-name- さん";
                message.Html = "<p>-name- さん</p>";

                client.Send(message);

                Thread.Sleep(200);
            }
        }
        public async Task SendAsync()
        {
            var client = new SendGridClient(ConfigurationManager.AppSettings["ApiKey"]);

            var message = new SendGridMessage();

            message.To.Add(ConfigurationManager.AppSettings["MailTo"]);
            message.From = ConfigurationManager.AppSettings["MailFrom"];

            message.Header.AddSubstitution("-name-", "抱かれたい男 No.1");
            message.UseFooter("html", "text");

            message.Subject = "-name- さんへ";
            message.Text = "-name- さん";
            message.Html = "<p>-name- さん</p>";

            await client.SendAsync(message);
        }
        public void Send()
        {
            var client = new SendGridClient(new NetworkCredential(ConfigurationManager.AppSettings["ApiUser"], ConfigurationManager.AppSettings["ApiKey"]));

            var message = new SendGridMessage();

            message.To.Add(ConfigurationManager.AppSettings["MailTo"]);
            message.From = ConfigurationManager.AppSettings["MailFrom"];

            message.Header.AddSubstitution("-name-", "抱かれたい男 No.1");
            message.UseFooter("html", "text");

            message.Subject = "-name- さんへ";
            message.Text = "-name- さん";
            message.Html = "<p>-name- さん</p>";

            client.Send(message);
        }
        public void Schedule()
        {
            var client = new SendGridClient(ConfigurationManager.AppSettings["ApiKey"]);

            var message = new SendGridMessage();

            message.To.Add(ConfigurationManager.AppSettings["MailTo"]);
            message.From = ConfigurationManager.AppSettings["MailFrom"];

            message.Header.AddSubstitution("-name-", "抱かれたい男 No.1");
            message.Header.AddSendAt(DateTimeOffset.Now.AddSeconds(30));

            message.Subject = "-name- さんへ";
            message.Text = "-name- さん";
            message.Html = "<p>-name- さん</p>";

            client.Send(message);
        }
        private async Task SendCustomizedNewEventEmailToGroupMembers(string eventDetailsUri, Event newEvent, Group group, SendGridClient client, ApplicationUser user)
        {
            StringBuilder NotificationEmailContent = new StringBuilder();

            NotificationEmailContent.Append($"Hola {user.Name}!");
            NotificationEmailContent.Append("</br>");
            NotificationEmailContent.Append("</br>");
            NotificationEmailContent.Append("<p>Desde el equipo de MyMeetUp queremos comunicarte que estás de enhorabuena!</br>");
            NotificationEmailContent.Append($"Acaba de crearse recientemente un nuevo evento organizado por el grupo <b>{group.Name}</b>.</p>");
            NotificationEmailContent.Append("<p>Esto son los datos del evento:");
            NotificationEmailContent.Append("<ul>");
            NotificationEmailContent.Append($"<li>Título: <b><i>{newEvent.Title}</i></b></li>");
            NotificationEmailContent.Append($"<li>Dónde: <i>{newEvent.Address} - {newEvent.City} - {newEvent.Country}</i></li>");
            NotificationEmailContent.Append($"<li>Cuándo: <i>{newEvent.FechaHora}</i></li>");
            NotificationEmailContent.Append("</ul></p>");
            NotificationEmailContent.Append($"<p><u>Descripción</u><br><i>{newEvent.Description}</i></li></p>");
            NotificationEmailContent.Append($"<p>Si quieres acceder al evento directamente, puedes utilizar el siguiente enlace: <a href=\"{eventDetailsUri}\" > Quiero saber más sobre este evento!</a></p>");
            NotificationEmailContent.Append("<p>Un saludo,</br>");
            NotificationEmailContent.Append("Equipo MyMeetUp</p>");

            var msg = new SendGridMessage()
            {
                From        = new EmailAddress(SendGridMailAccount, "MyMeetUp Team"),
                Subject     = "MyMeetUp: Atención Nuevo Evento!!",
                HtmlContent = NotificationEmailContent.ToString()
            };

            msg.AddTo(new EmailAddress(MockMailAccountTo));
            var response = await client.SendEmailAsync(msg);

            _log.LogWarning($"SendGrid response: {response.StatusCode}. Email sent to {user.Name} {user.Surname} related to new event created: {newEvent.Title}");
            NotificationEmailContent.Clear();
        }
Beispiel #6
0
        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;
            }

            switch (email.Data.Priority)
            {
            case Priority.High:
                // https://stackoverflow.com/questions/23230250/set-email-priority-with-sendgrid-api
                mailMessage.AddHeader("Priority", "Urgent");
                mailMessage.AddHeader("Importance", "High");
                // https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmail/2bb19f1b-b35e-4966-b1cb-1afd044e83ab
                mailMessage.AddHeader("X-Priority", "1");
                mailMessage.AddHeader("X-MSMail-Priority", "High");
                break;

            case Priority.Normal:
                // Do not set anything.
                // Leave default values. It means Normal Priority.
                break;

            case Priority.Low:
                // https://stackoverflow.com/questions/23230250/set-email-priority-with-sendgrid-api
                mailMessage.AddHeader("Priority", "Non-Urgent");
                mailMessage.AddHeader("Importance", "Low");
                // https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmail/2bb19f1b-b35e-4966-b1cb-1afd044e83ab
                mailMessage.AddHeader("X-Priority", "5");
                mailMessage.AddHeader("X-MSMail-Priority", "Low");
                break;
            }

            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);
        }
Beispiel #7
0
        public static bool Templete(Dictionary <string, string> replacement, string to, long emailTempleteId)
        {
            var response = false;

            try
            {
                using (var db = new DBEntities())
                {
                    //Get email templete data
                    var emailTemplete = db.EmailTempletes.FirstOrDefault(s =>
                                                                         s.EmailTempleteId == emailTempleteId && s.IsActive && !s.IsDelete);

                    if (emailTemplete != null)
                    {
                        //Replace Hash Tag with value
                        replacement.ToList().ForEach(x =>
                        {
                            emailTemplete.Subject = emailTemplete.Subject.Replace(x.Key, x.Value);
                            emailTemplete.Body    = emailTemplete.Body.Replace(x.Key, x.Value);
                        });

                        var apiKey           = "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";
                        var client           = new SendGridClient(apiKey);
                        var from             = new EmailAddress("*****@*****.**", "DevTacker");
                        var subject          = emailTemplete.Subject;
                        var toAddress        = new EmailAddress(to, "Valued User");
                        var plainTextContent = string.Empty;
                        var htmlContent      = emailTemplete.Body;
                        var msg       = MailHelper.CreateSingleEmail(from, toAddress, subject, plainTextContent, htmlContent);
                        var rsesponse = client.SendEmailAsync(msg);


                        ////Create mail object with credentials
                        //var message = new System.Web.Mail.MailMessage();
                        //message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", WebConfigurationManager.AppSettings["smtpserver"]);
                        //message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2");
                        //message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", WebConfigurationManager.AppSettings["smtpserverport"]);
                        //message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", WebConfigurationManager.AppSettings["smtpusessl"]);
                        //message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
                        //message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", WebConfigurationManager.AppSettings["sendusername"]);
                        //message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", WebConfigurationManager.AppSettings["sendpassword"]);

                        ////Preparing the message object....
                        //message.From = emailTemplete.FromEmail;
                        //message.To = to;
                        //message.Subject = emailTemplete.Subject;
                        //message.BodyFormat = Html;
                        //message.Body = emailTemplete.Body;

                        //if (!string.IsNullOrWhiteSpace(emailTemplete.BccEmail))
                        //    message.Bcc = emailTemplete.BccEmail;

                        //SmtpServer = "smtp.gmail.com";
                        //Send(message);

                        response = true;
                    }
                }
            }
            catch (Exception)
            {
                response = false;
            }

            return(response);
        }
 public SendGridEmailSender(string apiKey)
 {
     this.client = new SendGridClient(apiKey);
 }
Beispiel #9
0
        public EmailSender(IConfiguration config)
        {
            var apiKey = config.GetValue <string>("SendGridKey");

            myClient = new SendGridClient(apiKey);
        }
        public static async Task RunAsync(
            [TimerTrigger("0 */5 * * * *")] TimerInfo myTimer
            , [Blob("%BlobContainerName%/%BlobFileName%", FileAccess.Read)] Stream stateIn
            , [Blob("%BlobContainerName%/%BlobFileName%", FileAccess.Write)] TextWriter stateOut
//          //, [SendGrid(ApiKey = "%AzureWebJobsSendGridApiKey%")] SendGridMessage message
            , ILogger log
            , CancellationToken cancellationToken = default
            )
        {
            if (myTimer == null)
            {
                throw new Exception("Invalid timer trigger!");
            }

            log.LogInformation("Twitter Monitor function starting.");

            var twitterAuth = new SingleUserAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey       = Environment.GetEnvironmentVariable("TwitterApiConsumerKey", EnvironmentVariableTarget.Process),
                    ConsumerSecret    = Environment.GetEnvironmentVariable("TwitterApiConsumerSecret", EnvironmentVariableTarget.Process),
                    AccessToken       = Environment.GetEnvironmentVariable("TwitterApiAccessToken", EnvironmentVariableTarget.Process),
                    AccessTokenSecret = Environment.GetEnvironmentVariable("TwitterApiTokenSecret", EnvironmentVariableTarget.Process)
                }
            };

            var p = new Personalization
            {
                Tos = new List <EmailAddress>
                {
                    new EmailAddress(Environment.GetEnvironmentVariable("PrimaryEmail", EnvironmentVariableTarget.Process))
                }
            };
            var secondaryEmail = Environment.GetEnvironmentVariable("SecondaryEmail", EnvironmentVariableTarget.Process);

            if (!string.IsNullOrEmpty(secondaryEmail))
            {
                p.Tos.Add(new EmailAddress(secondaryEmail));
            }

            // april 4 2018 (so that we're not asking for beginning of all time)
            var previousTweetSinceId = 981588894067118080UL;

            if (stateIn != null)
            {
                using var reader = new StreamReader(stateIn, Encoding.UTF8);
                if (!ulong.TryParse(await reader.ReadToEndAsync(), out previousTweetSinceId))
                {
                    throw new Exception("must parse");
                }
            }
            var twitterQuery = Environment.GetEnvironmentVariable("TwitterQuery", EnvironmentVariableTarget.Process);

            log.LogInformation($"Going to query for '{twitterQuery}' starting at SinceId {previousTweetSinceId}");

            var twitterCtx     = new TwitterContext(twitterAuth);
            var searchResponse = (from search in twitterCtx.Search
                                  where search.Type == SearchType.Search &&
                                  search.Query == twitterQuery &&
                                  search.SinceID == previousTweetSinceId
                                  select search).SingleOrDefault();

            // manually assemble
            var sendGridClient = new SendGridClient(Environment.GetEnvironmentVariable("AzureWebJobsSendGridApiKey", EnvironmentVariableTarget.Process));

            var message = new SendGridMessage
            {
                Subject          = Environment.GetEnvironmentVariable("EmailSubject", EnvironmentVariableTarget.Process),
                From             = new EmailAddress(Environment.GetEnvironmentVariable("FromEmail", EnvironmentVariableTarget.Process)),
                Personalizations = new List <Personalization> {
                    p
                }
            };

            var msgText        = "";
            var updatedSinceId = previousTweetSinceId;
            var newTweetsCount = 0;

            if (searchResponse != null && searchResponse.Statuses != null)
            {
                var newResponses = searchResponse.Statuses.Where(a => a.StatusID > previousTweetSinceId);

                newTweetsCount = newResponses.Count();
                log.LogInformation($"Query has returned {newTweetsCount} new results.");

                foreach (var tweet in newResponses)
                {
                    var txt       = tweet.Text;
                    var tweetId   = tweet.StatusID;
                    var createdAt = tweet.CreatedAt;

                    var urls = "";
                    if (tweet.Entities != null && tweet.Entities.UrlEntities != null)
                    {
                        foreach (var urlEntity in tweet.Entities.UrlEntities)
                        {
                            urls += urlEntity.ExpandedUrl + " ";
                        }
                    }

                    if (tweetId > updatedSinceId)
                    {
                        updatedSinceId = tweetId;
                    }

                    // TODO: format the email body nicer than this!
                    msgText += $"{createdAt.ToLocalTime().ToLongDateString()}  {createdAt.ToLocalTime().ToLongTimeString()}\n{txt}\n{urls}\n\n";
                }
            }
            else
            {
                log.LogInformation("Query has returned no results.");
            }


            // write state out and send notifications (latest sinceid)
            if (newTweetsCount > 0)
            {
                log.LogInformation($"About to attempt to send message: {message}");

                message.AddContent("text/plain", msgText);
                var resp = await sendGridClient.SendEmailAsync(message, cancellationToken);

                if (resp.StatusCode != HttpStatusCode.Accepted)
                {
                    log.LogError($"Sendgrid send email failed with status code {(int)resp.StatusCode}");
                }
            }

            var updatedState = updatedSinceId.ToString();
            await stateOut.WriteLineAsync(updatedState);
        }
Beispiel #11
0
 public EmailService(SendGridClient sendGridClient)
 {
     _sendGridClient = sendGridClient;
 }
Beispiel #12
0
        private async Task ProcessAsync(EmailRequest request, EmailAction action, CancellationToken cancellationToken)
        {
            var properties = action.Properties;

            switch (action.Type)
            {
            case ActionType.Archive:
                // one folder per day is fine for now
                if (!DateTimeOffset.TryParse(request.Timestamp, out DateTimeOffset ts))
                {
                    // some dates are not parsable, just use todays date
                    // not 100% perfect (retried or delayed emails) might have wrong date
                    // but only archival mode
                    ts = DateTimeOffset.UtcNow;
                }
                var id = $"{ts:yyyy-MM}/{request.Timestamp:dd}/{request.Timestamp:HH-mm-ss}_{request.Email.From.Email} - {request.Email.Subject}";

                var name          = $"{id}.json";
                var containerName = action.Properties.Property("containerName").Value.ToString();
                await _blobStorageService.UploadAsync(containerName, name, JsonConvert.SerializeObject(request.Email, Formatting.Indented), cancellationToken);

                // save all attachments in subfolder
                var   tasks = Task.WhenAll(request.Email.Attachments.Select(a => _blobStorageService.UploadAsync(containerName, $"{id} (Attachments)/{a.FileName}", Convert.FromBase64String(a.Base64Data), cancellationToken)));
                await tasks;
                if (tasks.Exception != null)
                {
                    throw tasks.Exception;
                }

                break;

            case ActionType.Forward:
            {
                var secretName = action.Properties.Property("webhook")?.Value?.ToObject <SecretObject>()?.SecretName ?? throw new KeyNotFoundException($"Could not find secretName of webhook in action {action.Id}");
                var webhookUrl = await _keyVaultHelper.GetSecretAsync(secretName, cancellationToken);

                request.Body.Position = 0;
                var r = await _httpClient.PostStreamAsync(webhookUrl, request.Body, cancellationToken);

                if (r.StatusCode != HttpStatusCode.OK &&
                    r.StatusCode != HttpStatusCode.Accepted)
                {
                    throw new WebhookException($"Failed calling webhook {action.Id}");
                }
            }
            break;

            case ActionType.Webhook:
            {
                var secretName = action.Properties.Property("webhook")?.Value?.ToObject <SecretObject>()?.SecretName ?? throw new KeyNotFoundException($"Could not find secretName of webhook in action {action.Id}");
                var webhookUrl = await _keyVaultHelper.GetSecretAsync(secretName, cancellationToken);

                string Format(string text) => text
                .Replace("%sender%", request.Email.From.Email)
                .Replace("%subject%", request.Email.Subject)
                .Replace("%body%", request.Email.Text ?? request.Email.Html)
                .Replace("\"%attachments%\"", request.Email.Attachments != null ? JsonConvert.SerializeObject(request.Email.Attachments) : "null");

                var json = action.Properties.Property("body")?.Value?.ToString();
                json = Format(json);

                var r = await _httpClient.PostAsync(webhookUrl, json, cancellationToken);

                if (r.StatusCode != HttpStatusCode.OK &&
                    r.StatusCode != HttpStatusCode.Accepted)
                {
                    throw new WebhookException($"Failed calling webhook {action.Id}");
                }
            }
            break;

            case ActionType.Email:
            {
                var secretName  = action.Properties.Property("sendgrid")?.Value?.ToObject <SecretObject>()?.SecretName ?? throw new KeyNotFoundException($"Could not find secretName of email in action {action.Id}");
                var domain      = action.Properties.Property("domain")?.Value?.ToString() ?? throw new KeyNotFoundException($"Could not find domain of email in action {action.Id}");
                var targetEmail = action.Properties.Property("targetEmail")?.Value?.ToString() ?? throw new KeyNotFoundException($"Could not find targetEmail of email in action {action.Id}");

                var sendgridKey = await _keyVaultHelper.GetSecretAsync(secretName, cancellationToken);

                var sendgridClient = new SendGridClient(sendgridKey);
                // only add section if CC emails exist
                var prefix = "";
                if (request.Email.Cc.Length > 0)
                {
                    var newLine = "\r\n";
                    if (!string.IsNullOrEmpty(request.Email.Html))
                    {
                        newLine += "<br>";
                    }

                    if (request.Email.Cc.Any())
                    {
                        prefix += $"CC: {string.Join("; ", request.Email.Cc.Select(x => x.Email))}";
                    }
                    prefix += newLine + "__________";
                }

                // mail can be sent to multiple targets - our domain may not be the first and may even appear multiple times (same address or various domain addresses)
                // -> match first with domain name
                var emails = request.Email.To.Select(e => e.Email)
                             .Concat((request.Email.Cc ?? new EmailAddress[0]).Select(c => c.Email))
                             .ToArray();

                domain = domain.StartsWith("@") ? domain.Substring(1) : domain;
                var fromEmail = emails.FirstOrDefault(e => e.EndsWith($"@{domain}", StringComparison.InvariantCultureIgnoreCase)) ?? $"unknown@{domain}";
                string EnsureNotEmpty(string message)
                {
                    // pgp signed emails have no content but attachments only;
                    // seems to be this bug
                    // https://github.com/sendgrid/sendgrid-nodejs/issues/435
                    return(string.IsNullOrEmpty(message) ? " " : message);
                }

                var mail = MailHelper.CreateSingleEmail(new EmailAddress(fromEmail), new EmailAddress(targetEmail), request.Email.Subject, EnsureNotEmpty(prefix + request.Email.Text), EnsureNotEmpty(prefix + request.Email.Html));
                // causes the reply button to magically replace "fromEmail" with the email of the original author -> respond gets sent to the correct person
                mail.ReplyTo = request.Email.From;
                foreach (var attachment in request.Email.Attachments)
                {
                    mail.AddAttachment(new Attachment
                        {
                            ContentId = attachment.ContentId,
                            Content   = attachment.Base64Data,
                            Filename  = attachment.FileName,
                            Type      = attachment.ContentType
                        });
                }
                var response = await sendgridClient.SendEmailAsync(mail, cancellationToken);

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

                    throw new BadRequestException($"Sendgrid did not accept. The response was: {response.StatusCode}." + Environment.NewLine + errorResponse);
                }
            }
            break;

            default:
                throw new ArgumentOutOfRangeException($"Unsupported type {action.Type}");
            }
        }
Beispiel #13
0
        public static IRestResponse SendEmailToresetpassword(string FName, string LName, int RecUserid, string password, string Recuiteremail)
        {
            string host  = System.Web.HttpContext.Current.Request.Url.Host;
            string port  = System.Web.HttpContext.Current.Request.Url.Port.ToString();
            string port1 = System.Configuration.ConfigurationManager.AppSettings["RedirectURL"];



            string UrlEmailAddress = string.Empty;

            if (host == "localhost")
            {
                UrlEmailAddress = host + ":" + port;
            }
            else
            {
                UrlEmailAddress = port1;
            }
            var emailcontent = "";

            emailcontent = "<html>" +
                           "<head><meta charset='UTF-8'>" +
                           "<title>JobSeekerDetails</title>" +
                           "<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>" +
                           "<meta content='width=device-width' name='viewport'>" +
                           "<style type='text/css'>@font-face{font-family:&#x27;Postmates Std&#x27;; font-weight:600; font-style:normal; src: local(&#x27;Postmates Std Bold&#x27;), url(https://s3-us-west-1.amazonaws.com/buyer-static.postmates.com/assets/email/postmates-std-bold.woff) format(&#x27;woff&#x27;); } @font-face { font-family:&#x27;Postmates Std&#x27;; font-weight:500; font-style:normal; src:local(&#x27;Postmates Std Medium&#x27;), url(https://s3-us-west-1.amazonaws.com/buyer-static.postmates.com/assets/email/postmates-std-medium.woff) format(&#x27;woff&#x27;); } @font-face { font-family:&#x27;Postmates Std&#x27;; font-weight:400; font-style:normal; src:local(&#x27;Postmates Std Regular&#x27;), url(https://s3-us-west-1.amazonaws.com/buyer-static.postmates.com/assets/email/postmates-std-regular.woff) format(&#x27;woff&#x27;); }</style>" +
                           "<style media='screen and (max-width: 680px)'> @media screen and (max-width:680px) { .page-center { padding-left:0 !important; padding-right:0 !important; } .footer-center { padding-left:20px !important; padding-right:20px !important; } }</style>" +
                           "</head>" +
                           "<body style='background-color:#f4f4f5;'>" +
                           "<table cellpadding='0' cellspacing='0' style='width:100%; height:100%; background-color:#f4f4f5; text-align:center;'>" +
                           "<tbody>" +
                           "<tr>" +
                           "<td style='text-align:center;'>" +
                           //<!-- http://evolutyz.in/img/hero-alt-long2.jpg min-height:100vh;height:100%;-->
                           "<table align='center' cellpadding='0' cellspacing='0' id='body' style='background-color:#fff; width:100%; padding:15px; background-image: url(https://csg33dda4407ebcx4721xba0.blob.core.windows.net/companylogos/hero-alt-long-trans.png); background-position:100% top; background-repeat: no-repeat; background-size: 100%; max-width:680px;'>" +
                           "<tbody>" +
                           "<tr>" +
                           "<td>" +
                           "<table align='center' cellpadding='0' cellspacing='0' class='page-center' style='text-align: left; padding-bottom:88px; width:100%; padding-left:90px; padding-right:90px;'>" +
                           "<tbody>" +
                           "<tr>" +
                           "<td style='padding-top:24px;'>" +
                           "<img src='https://media.glassdoor.com/sqll/1077141/evolutyz-squarelogo-1516869456062.png' style='border-radius: 100px;width: 155px;'>" +
                           "</td>" +
                           "</tr>" +
                           "<tr>" +
                           "<td colspan='2' style='padding-top:72px; -ms-text-size-adjust:100%; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: 100%; color:#5f5f5f; font-family:  sans-serif; font-size:48px; font-smoothing: always; font-style: normal; font-weight:600; letter-spacing:-2.6px; line-height:52px; mso-line-height-rule: exactly; text-decoration: none;'>Jobseeker Details</td>" +
                           "</tr>" +
                           "<tr>" +
                           "<td style='padding-top:48px; padding-bottom:48px;'> <table cellpadding='0' cellspacing='0' style='width: 100%'>" +
                           "<tbody>" +
                           "<tr>" +
                           "<td style='width:100%; height:1px; max-height:1px; background-color: #d9dbe0; opacity: 0.81'>" +
                           "</td>" +
                           "</tr>" +
                           "</tbody>" +
                           "</table>" +
                           "</td>" +
                           "</tr>" +
                           //"<tr>"+
                           //"<td style='-ms-text-size-adjust: 100%; -ms-text-size-adjust: 100%; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: 100%; color: #9095a2; font-family:  sans-serif; font-size:16px; font-smoothing: always; font-style: normal; font-weight:400; letter-spacing:-0.18px; line-height:24px; mso-line-height-rule: exactly; text-decoration: none; vertical-align: top; width: 100%;'> Job seeker details to take assessment. </td>"+
                           //"</tr>"+
                           "<tr>" +
                           "<td colspan='2'>" +
                           "<table width=240 height=100 cellspacing=1 cellpadding=1 border=0 style='margin: auto; color: #585858;'>" +
                           "<tbody>" +
                           "<tr>" +
                           "<td><span style='font-size:18px; color: #2b2b2b;'><small>User name:</small></span></td>" +
                           "<td style='text-align: right;'><span><strong> " + FName + "</strong></span></td>" +
                           "</tr> " +
                           "<tr> " +
                           "<td>" +
                           "<span style='font-size:18px; color: #2b2b2b;'><small>Password:</small>" +
                           "</td> " +
                           "<td style='text-align: right;'><span><strong>" + password + "</strong></span></td> " +
                           "</tr> " +
                           //"<tr> " +
                           //"<td><span style='font-size: 18px; color: #2b2b2b;'><small>Email:</small></td> " +
                           // "<td style='text-align: right;'><span><strong>[email protected]</strong></span></td> " +
                           //"</tr>" +
                           "</tbody> " +
                           "</table>" +
                           "</td>" +
                           "</tr>" +
                           "<tr>" +
                           "<td style = 'padding-top:24px; -ms-text-size-adjust: 100%; -ms-text-size-adjust: 100%; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: 100%; color: #9095a2; font-family: sans-serif; font-size:16px; font-smoothing: always; font-style: normal; font-weight:400; letter-spacing:-0.18px; line-height:24px; mso-line-height-rule: exactly; text-decoration: none; vertical-align: top; width: 100%;' > Please tap the button below to take assessment. </td>" +
                           "</tr>" +
                           "<tr>" +
                           "<td>" +
                           //"<a data-click-track-id ='37' href =' UrlEmailAddress + "/Home/ResetPassword?token=  "1234 "' style ='margin-top:36px; -ms-text-size-adjust: 100%; -ms-text-size-adjust: 100%; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: 100%; color: #ffffff; font-family:  sans-serif; font-size:12px; font-smoothing: always; font-style: normal; font-weight:600; letter-spacing:0.7px; line-height:48px; mso-line-height-rule: exactly; text-decoration: none; vertical-align: top; width:220px; background-color: #795548; border-radius:28px; display: block; text-align: center; text-transform: uppercase' target = '_blank' > Start Assessment </a>"+
                           "</td>" +
                           "</tr>" +
                           "</tbody>" +
                           "</table>" +
                           "</td>" +
                           "</tr>" +
                           "</tbody>" +
                           "</table>" +
                           //<!-- height:100%; -->
                           "<table align = 'center' cellpadding = '0' cellspacing = '0' id = 'footer' style = 'background-color: #3c3c3c; width:100%; max-width:680px; '>" +
                           "<tbody>" +
                           "<tr>" +
                           "<td>" +
                           "<table align = 'center' cellpadding = '0' cellspacing = '0' class='footer-center' style='text-align: left; width: 100%; padding-left:90px; padding-right:90px;'>" +
                           "<tbody>" +
                           "<tr>" +
                           "<td colspan = '2' style='padding-top:50px;padding-bottom:15px;width:100%;color: #f8c26c;font-size:40px;'> Evolutyz Corner</td>" +
                           "</tr>" +
                           "<tr>" +
                           "<td colspan = '2' style= 'padding-top:24px; padding-bottom:48px;' >" +
                           "<table cellpadding= '0' cellspacing= '0' style= 'width:100%'>" +
                           "<tbody>" +
                           "<tr>" +
                           "<td style= 'width:100%; height:1px; max-height:1px; background-color: #EAECF2; opacity: 0.19' >" +
                           "</td>" +
                           "</tr>" +
                           "</tbody>" +
                           "</table>" +
                           "</td>" +
                           "</tr>" +
                           "<tr>" +
                           "<td style= '-ms-text-size-adjust:100%; -ms-text-size-adjust:100%; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: 100%; color: #9095A2; font-family: sans-serif; font-size:15px; font-smoothing: always; font-style: normal; font-weight:400; letter-spacing: 0; line-height:24px; mso-line-height-rule: exactly; text-decoration: none; vertical-align: top; width:100%;' > If you have any questions or concerns, we are here to help. Contact us via our <a data-click-track-id='1053' href='mailto:[email protected]' title='*****@*****.**' style='font-weight:500; color: #ffffff' target='_blank'>Help Center.</a>" +
                           "</td>" +
                           "</tr>" +
                           "<tr>" +
                           "<td style='height:72px;'>" +
                           "</td>" +
                           "</tr>" +
                           "</tbody>" +
                           "</table>" +
                           "</td>" +
                           "</tr>" +
                           "</tbody>" +
                           "</table>" +
                           "</td>" +
                           "</tr>" +
                           "</tbody>" +
                           "</table>" +
                           "</body>" +
                           "</html>";

            var client = new SendGridClient("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");

            var msgs = new SendGridMessage()
            {
                From    = new EmailAddress("*****@*****.**"),
                Subject = "Credentials for EvolutyzCorner Portal",
                //TemplateId = "d-0741723a4269461e99a89e57a58dc0d3",
                HtmlContent = emailcontent
            };

            msgs.AddTo(new EmailAddress(Recuiteremail));

            var responses = client.SendEmailAsync(msgs);

            return(null);
        }
Beispiel #14
0
 public MailingLibrary()
 {
     _logLibrary = new LogLibrary <MailingLibrary>();
     _authentificationLibrary = new AuthentificationLibrary();
     _transactionsClient      = new SendGridClient(ResolveSendGridKey());
 }
        public async Task <IActionResult> OnPostAsync([Bind("Identity, ProfileImage")] InputModel input, string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                //add Proof of identity image
                string wwwRootPath = _hostEnvironment.WebRootPath;
                string fileName    = Path.GetFileNameWithoutExtension(input.Identity.FileName);
                string extension   = Path.GetExtension(input.Identity.FileName);
                input.IdentityImageName = fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
                string path = Path.Combine(wwwRootPath + "/image", fileName);
                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    await input.Identity.CopyToAsync(fileStream);
                }

                //add Profile Image
                string wwwRootPath1 = _hostEnvironment.WebRootPath;
                string fileName1    = Path.GetFileNameWithoutExtension(input.ProfileImage.FileName);
                string extension1   = Path.GetExtension(input.ProfileImage.FileName);
                input.ProfileImageName = fileName1 = fileName1 + DateTime.Now.ToString("yymmssfff") + extension1;
                string path1 = Path.Combine(wwwRootPath1 + "/image", fileName1);
                using (var fileStream1 = new FileStream(path1, FileMode.Create))
                {
                    await input.ProfileImage.CopyToAsync(fileStream1);
                }

                var user = new ApplicationUser
                {
                    FirstName     = Input.FirstName,
                    LastName      = Input.LastName,
                    DOB           = Input.DOB,
                    Address1      = Input.Address1,
                    Address2      = Input.Address2,
                    PhoneNumber   = Input.Mobile,
                    Gender        = Input.Gender,
                    Occupation    = Input.Occupation,
                    Residency     = Input.Residency,
                    City          = Input.City,
                    State         = Input.State,
                    ZipCode       = Input.ZipCode,
                    Identity      = fileName,
                    ProfileImage  = fileName1,
                    UserName      = Input.Username,
                    Email         = Input.Email,
                    FirstAccessed = true,
                    isProfile     = false,
                    isAccount     = true
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("New user account successfully created.");

                    //Create User/Customer role *Default role*
                    var role = new ApplicationRole();
                    role.Name = "Admin";
                    await _roleManager.CreateAsync(role);

                    //Add new user to the default role
                    var addrole = await _userManager.AddToRoleAsync(user, "Admin");

                    _logger.LogInformation("User role added.");

                    //Send User Proof of Identity information to company email
                    var    apiKey      = "";
                    var    client      = new SendGridClient(apiKey);
                    var    from        = new EmailAddress("*****@*****.**");
                    var    to          = new EmailAddress("*****@*****.**");
                    string subject     = "Official Planiture Customer - " + Input.FirstName + "" + Input.LastName + "- Proof of Identity";
                    string htmlContent = "See attachment for customer's ID information";
                    var    msg         = MailHelper.CreateSingleEmail(from, to, subject, null, htmlContent);
                    //get image location
                    var imagePath = Path.Combine(_hostEnvironment.WebRootPath, "image", user.Identity);
                    //convert image to bytes
                    byte[] bytes = Encoding.ASCII.GetBytes(imagePath);
                    //attach image bytes to email and send
                    var trying = new Attachment()
                    {
                        Disposition = "attachment/image",
                        ContentId   = null,
                        Filename    = fileName,
                        Type        = "*",
                        Content     = Convert.ToBase64String(bytes)
                    };
                    msg.AddAttachment(trying);
                    var response = client.SendEmailAsync(msg);

                    //Email Verification Process
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);


                    //Send Email Confirmation Link

                    var    apiKey1      = "";
                    var    client1      = new SendGridClient(apiKey1);
                    var    from1        = new EmailAddress("*****@*****.**");
                    var    to1          = new EmailAddress(Input.Email);
                    string subject1     = "Official Planiture Email Address Confirmation";
                    string htmlContent1 =
                        "<p>Hi there, " +
                        "<br />" +
                        "<br />" +
                        "This message is to confirm that the Planiture account with the username " + Input.Username + " " +
                        "belongs to you. Verifying your email address helps you to secure your account. If you forget your " +
                        "password, you will now be able to reset it by email." +
                        "<br />" +
                        "<br />" +
                        "<br />" +
                        "To confirm that this is your Planiture account, click here:" +
                        "<br />" +
                        "<br>" +
                        "<a href='" + callbackUrl + "' style='background-color: red; border: 1px solid black; color: white;" +
                        " padding: 10px; width: 60%; font-weight: 500; border-radius: 10px;text-decoration: none;'>Confirm Email</a>" +
                        "<br>" +
                        "<br>" +
                        "If this is not your Planiture account or you did not sign up for Planiture, please ignore this email." +
                        "<br />" +
                        "<br />" +
                        "Thanks, <br />The Planiture Family</p>";
                    var msg1      = MailHelper.CreateSingleEmail(from1, to1, subject1, null, htmlContent1);
                    var response1 = await client1.SendEmailAsync(msg1);

                    _logger.LogInformation("Email Sent");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("EmailVerificationMessage"));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Beispiel #16
0
 public NotificationService(Lazy <NotificationsConfiguration> lazyNotificationsConfiguration)
 {
     _sendGridClient = new SendGridClient(lazyNotificationsConfiguration.Value.SendGridApiKey);
 }
        private async Task SendCustomizedNewGroupMemberToCoordinatorStaff(Group group, ApplicationUser newMemberInfo, SendGridClient client, ApplicationUser coordinator)
        {
            StringBuilder NotificationEmailContent = new StringBuilder();

            NotificationEmailContent.Append($"Hola {coordinator.Name},");
            NotificationEmailContent.Append("</br>");
            NotificationEmailContent.Append("</br>");
            NotificationEmailContent.Append($"<p>Desde el equipo de MyMeetUp queremos informarle como coordinador de grupo <b>{group.Name}</b>,</br>");
            NotificationEmailContent.Append($"que acaba de darse de alta un nuevo miembro. Enhorabuena!.</p>");
            NotificationEmailContent.Append("<p><ul>");
            NotificationEmailContent.Append($"<li><b><i>{newMemberInfo.Name} {newMemberInfo.Surname}</i></b></li>");
            NotificationEmailContent.Append($"<li><i>{newMemberInfo.Email}</i></li>");
            NotificationEmailContent.Append($"<li><i>{newMemberInfo.City} - {newMemberInfo.Country}</i></li>");
            NotificationEmailContent.Append("</ul></p>");
            NotificationEmailContent.Append("<p>Un saludo,</br>");
            NotificationEmailContent.Append("Equipo MyMeetUp</p>");

            var msg = new SendGridMessage()
            {
                From        = new EmailAddress(SendGridMailAccount, "MyMeetUp Team"),
                Subject     = "MyMeetUp: Nuevo Miembro en tu Grupo!!",
                HtmlContent = NotificationEmailContent.ToString()
            };

            msg.AddTo(new EmailAddress(MockMailAccountTo));
            var response = await client.SendEmailAsync(msg);

            _log.LogWarning($"SendGrid response: {response.StatusCode}. Email sent to {coordinator.Name} {coordinator.Surname} related to there is a new member in the group: {newMemberInfo.Name} {newMemberInfo.Surname}");
            NotificationEmailContent.Clear();
        }
Beispiel #18
0
 public MailService(IOptions <MailServiceOptions> options, TemplateService templateService)
 {
     this.options         = options.Value;
     this.client          = new SendGridClient(this.options.ApiKey);
     this.templateService = templateService;
 }
Beispiel #19
0
        private static async Task Main()
        {
            var env           = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production";
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json", optional: true)
                                .AddJsonFile($"appsettings.{env}.json", optional: true)
                                .Build();

            // Retrieve the API key.
            var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY") ?? configuration["SendGrid:ApiKey"];

            var client = new SendGridClient(HttpClient, apiKey, httpErrorAsException: true);

            // Send a Single Email using the Mail Helper
            var from             = new EmailAddress(configuration.GetValue("SendGrid:From", "*****@*****.**"), "Example User");
            var subject          = "Hello World from the Twilio SendGrid CSharp Library Helper!";
            var to               = new EmailAddress(configuration.GetValue("SendGrid:To", "*****@*****.**"), "Example User");
            var plainTextContent = "Hello, Email from the helper [SendSingleEmailAsync]!";
            var htmlContent      = "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>";
            var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var response         = await client.SendEmailAsync(msg);

            Console.WriteLine(msg.Serialize());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // Send a Single Email using the Mail Helper with convenience methods and initialized SendGridMessage object
            msg = new SendGridMessage
            {
                From             = from,
                Subject          = subject,
                PlainTextContent = plainTextContent,
                HtmlContent      = htmlContent
            };
            msg.AddTo(to);
            response = await client.SendEmailAsync(msg);

            Console.WriteLine(msg.Serialize());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // Send a Single Email using the Mail Helper, entirely with convenience methods
            msg = new SendGridMessage();
            msg.SetFrom(from);
            msg.SetSubject(subject);
            msg.AddContent(MimeType.Text, plainTextContent);
            msg.AddContent(MimeType.Html, htmlContent);
            msg.AddTo(to);
            response = await client.SendEmailAsync(msg);

            Console.WriteLine(msg.Serialize());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // Send a Single Email Without the Mail Helper
            var data = @"{
              'personalizations': [
                {
                  'to': [
                    {
                      'email': '*****@*****.**'
                    }
                  ],
                  'subject': 'Hello World from the Twilio SendGrid C# Library!'
                }
              ],
              'from': {
                'email': '*****@*****.**'
              },
              'content': [
                {
                  'type': 'text/plain',
                  'value': 'Hello, Email!'
                }
              ]
            }";
            var json = JsonConvert.DeserializeObject <object>(data);

            response = await client.RequestAsync(BaseClient.Method.POST,
                                                 json.ToString(),
                                                 urlPath : "mail/send");

            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // GET Collection
            var queryParams = @"{
                'limit': 100
            }";

            response = await client.RequestAsync(method : BaseClient.Method.GET,
                                                 urlPath : "asm/groups",
                                                 queryParams : queryParams);

            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Body.ReadAsStringAsync().Result);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue to POST.");
            Console.ReadLine();

            // POST
            var requestBody = @"{
              'description': 'Suggestions for products our users might like.',
              'is_default': false,
              'name': 'Magic Products'
            }";

            json     = JsonConvert.DeserializeObject <object>(requestBody);
            response = await client.RequestAsync(method : BaseClient.Method.POST,
                                                 urlPath : "asm/groups",
                                                 requestBody : json.ToString());

            var dsResponse = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(response.Body.ReadAsStringAsync().Result);

            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Body.ReadAsStringAsync().Result);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue to GET single.");
            Console.ReadLine();

            if (dsResponse != null && dsResponse.ContainsKey("id"))
            {
                var groupId = dsResponse["id"].ToString();

                // GET Single
                response = await client.RequestAsync(method : BaseClient.Method.GET,
                                                     urlPath : $"asm/groups/{groupId}");

                Console.WriteLine(response.StatusCode);
                Console.WriteLine(response.Body.ReadAsStringAsync().Result);
                Console.WriteLine(response.Headers);
                Console.WriteLine("\n\nPress <Enter> to continue to PATCH.");
                Console.ReadLine();


                // PATCH
                requestBody = @"{
                    'name': 'Cool Magic Products'
                }";
                json        = JsonConvert.DeserializeObject <object>(requestBody);

                response = await client.RequestAsync(method : BaseClient.Method.PATCH,
                                                     urlPath : $"asm/groups/{groupId}",
                                                     requestBody : json.ToString());

                Console.WriteLine(response.StatusCode);
                Console.WriteLine(response.Body.ReadAsStringAsync().Result);
                Console.WriteLine(response.Headers.ToString());

                Console.WriteLine("\n\nPress <Enter> to continue to PUT.");
                Console.ReadLine();

                // DELETE
                response = await client.RequestAsync(method : BaseClient.Method.DELETE,
                                                     urlPath : $"asm/groups/{groupId}");

                Console.WriteLine(response.StatusCode);
                Console.WriteLine(response.Headers.ToString());
                Console.WriteLine("\n\nPress <Enter> to DELETE and exit.");
                Console.ReadLine();
            }
        }
Beispiel #20
0
 public MailService(IOptions <MailServiceOptions> options)
 {
     _options = options.Value;
     _client  = new SendGridClient(options.Value.MailApiToken);
 }
Beispiel #21
0
        public void PutMe([FromBody] NewUser usr)
        {
            AuthorizationToken AuthTok = _userService.AuthorizationTokens.Single(
                t => t.Uid == Request.Headers["Authorization"]
                );

            User FoundUser = _userService.Users.Find(AuthTok.UserUid);

            if (usr.Email != null && usr.Email != FoundUser.Email)
            {
                // User is trying to change their email
                // Check there are no dups
                int count = _userService.Users
                            .Where(u => u.Email == usr.Email)
                            .ToList().Count;
                if (count > 1)
                {
                    throw new ArgumentException();
                }

                // Need to confirm new email
                FoundUser.EmailConfirmed = false;
                // Generate email verification token
                Guid   g          = Guid.NewGuid();
                string EmailToken = Convert.ToBase64String(g.ToByteArray());
                EmailToken = EmailToken.Replace("=", "");
                EmailToken = EmailToken.Replace("+", "");
                EmailToken = EmailToken.Replace("/", "");

                // Send email
                var apiKey           = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
                var client           = new SendGridClient(apiKey);
                var from             = new EmailAddress("*****@*****.**", "Buck Tower");
                var subject          = "Confirm your Buildarium account, " + usr.FirstName;
                var to               = new EmailAddress(usr.Email, usr.FirstName + " " + usr.LastName);
                var plainTextContent = "Confirm your email by visiting this link: https://app.buildarium.com/confirm/" +
                                       EmailToken;
                var htmlContent = "<strong>Confirm your email by visiting this link:</strong> https://app.buildarium.com/confirm/" +
                                  EmailToken;
                var msg      = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
                var response = client.SendEmailAsync(msg);

                FoundUser.Email = usr.Email;
            }

            if (usr.Username != null && usr.Username != FoundUser.Username)
            {
                // User is trying to change their username
                // Check there are no dups
                int count = _userService.Users
                            .Where(u => u.Username == usr.Username)
                            .ToList().Count;
                if (count > 1)
                {
                    throw new ArgumentException();
                }

                FoundUser.Username = usr.Username;
            }

            // Change other meta
            FoundUser.FirstName = usr.FirstName;
            FoundUser.LastName  = usr.LastName;

            // Save all changes to Postgres
            _userService.SaveChanges();
        }
Beispiel #22
0
 public MailSender()
 {
     //ToDo: add key
     _client = new SendGridClient("asdf");
 }
Beispiel #23
0
        public async Task SendEmailAsync(MailRequest mailRequest)
        {
            var email = new SendGridMessage();

            email.SetFrom(_mailSettings.Mail);
            var recipients = new List <EmailAddress> {
                new EmailAddress(mailRequest.ToEmail, "Pevaar Client")
            };

            email.AddTos(recipients);
            email.SetSubject(mailRequest.Subject);
            //var builder = new BodyBuilder();
            //if (mailRequest.Attachments != null)
            //{
            //    byte[] fileBytes;
            //  foreach (var file in mailRequest.Attachments)
            //    {
            //        if (file.Length > 0)
            //        {
            //            using (var ms = new MemoryStream())
            //            {
            //                file.CopyTo(ms);
            //                fileBytes = ms.ToArray();
            //            }
            //            builder.Attachments.Add(file.FileName, fileBytes, ContentType.Parse(file.ContentType));
            //        }
            //    }
            //}

            if (mailRequest.Subject == "Cotización" && mailRequest.BotAttachments != null)
            {
                mailRequest.BotAttachments.Clear();
            }
            else if (mailRequest.BotAttachments != null && mailRequest.Subject != "Cotización")
            {
                foreach (var file in mailRequest.BotAttachments)
                {
                    using (var webClient = new WebClient())
                    {
                        byte[] fileBytes;
                        var    filestream = webClient.OpenRead(file.ContentUrl);

                        using (var ms = new MemoryStream())
                        {
                            filestream.CopyTo(ms);
                            fileBytes = ms.ToArray();
                        }
                        //Byte[] bytes = File.ReadAllBytes(filestream.);
                        email.AddAttachment(file.Name, Convert.ToBase64String(fileBytes), file.ContentType, "inline", file.Name);
                    }
                }
            }

            //builder.HtmlBody = mailRequest.Body;
            //email.AddContent(MimeType.Html, mailRequest.Body);
            email.SetTemplateId("d-f39627877d8042f3b3ec9d14143b1bf9");
            email.SetTemplateData(new InfTemplateMail {
                subject = mailRequest.Subject, Name = mailRequest.Name, Phone = mailRequest.Phone, Description = mailRequest.Description, Email = mailRequest.Email
            });

            //using var smtp = new SmtpClient();
            //smtp.Connect(_mailSettings.Host, _mailSettings.Port);
            //smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password);
            //await smtp.SendAsync(email);
            //smtp.Disconnect(true);
            var apiKey   = _mailSettings.SENDGRID_API_KEY;
            var client   = new SendGridClient(apiKey);
            var response = await client.SendEmailAsync(email);
        }
Beispiel #24
0
 public static void SetupClient()
 {
     client = new SendGridClient(EmailConfig.instance.Api_Key);
 }
Beispiel #25
0
        public Task Post(
            HelpDeskEmail objHelpDeskEmail)
        {
            try
            {
                // Email settings
                SendGridMessage msg = new SendGridMessage();
                var apiKey = configuration["SENDGRID_APIKEY"];
                var senderEmail = configuration["SenderEmail"];
                var client = new SendGridClient(apiKey);

                var FromEmail = new EmailAddress(
                    senderEmail,
                    senderEmail
                    );

                // Format Email contents
                string strPlainTextContent =
                    $"{objHelpDeskEmail.EmailType}: " +
                    $"{GetHelpDeskTicketUrl(objHelpDeskEmail.TicketGuid)}";

                string strHtmlContent =
                    $"<b>{objHelpDeskEmail.EmailType}:</b> ";
                strHtmlContent = strHtmlContent +
                    $"<a href='{ GetHelpDeskTicketUrl(objHelpDeskEmail.TicketGuid) }'>";
                strHtmlContent = strHtmlContent +
                    $"{GetHelpDeskTicketUrl(objHelpDeskEmail.TicketGuid)}</a>";

                if (objHelpDeskEmail.EmailType == "Help Desk Ticket Created")
                {
                    msg = new SendGridMessage()
                    {
                        From = FromEmail,
                        Subject = objHelpDeskEmail.EmailType,
                        PlainTextContent = strPlainTextContent,
                        HtmlContent = strHtmlContent
                    };

                    // Created Email always goes to Administrator
                    // Send to senderEmail configured in appsettings.json
                    msg.AddTo(
                        new EmailAddress(senderEmail, objHelpDeskEmail.EmailType)
                        );
                }

                if (objHelpDeskEmail.EmailType == "Help Desk Ticket Updated")
                {
                    // Must pass a valid GUID 
                    // Get the existing record
                    if (_context.HelpDeskTickets
                        .Where(x => x.TicketGuid == objHelpDeskEmail.TicketGuid)
                        .FirstOrDefault() != null)
                    {
                        // See if the user is the Administrator
                        if (!this.User.IsInRole("Administrators"))
                        {
                            // Always send email to Administrator
                            objHelpDeskEmail.EmailAddress = senderEmail;
                        }

                        msg = new SendGridMessage()
                        {
                            From = FromEmail,
                            Subject = objHelpDeskEmail.EmailType,
                            PlainTextContent = strPlainTextContent,
                            HtmlContent = strHtmlContent
                        };

                        // Send Email
                        msg.AddTo(new EmailAddress(
                            objHelpDeskEmail.EmailAddress,
                            objHelpDeskEmail.EmailType)
                            );
                    }
                    else
                    {
                        Task.FromResult("Error - Bad TicketGuid");
                    }
                }

                client.SendEmailAsync(msg);
            }
            catch
            {
                // Could not send email
                // Perhaps SENDGRID_APIKEY not set in 
                // appsettings.json
            }

            return Task.FromResult("");
        }
Beispiel #26
0
        static async Task Execute()
        {
            // Retrieve the API key from the environment variables. See the project README for more info about setting this up.
            var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");

            /* var fromEmail = "*****@*****.**";
             * var fromEmailAliasName = "Phong Ha";
             * var toEmail = "*****@*****.**";
             * var toEmailAlias = "Phong89"; */

            //Modify the follow values with your from/to email addresses.
            var fromEmail          = "*****@*****.**";
            var fromEmailAliasName = "First LastName";
            var toEmail            = "*****@*****.**";
            var toEmailAlias       = "First LastNmae";

            if (apiKey == null)
            {
                Console.WriteLine("Error: SendGrid API Key environment variable: SENDGRID_API_KEY not found. Please configure System Variables.");
                Console.WriteLine("\n\nPress <Enter> to continue.");
                Console.ReadLine();
                Environment.Exit(0);
            }

            var client = new SendGridClient(apiKey);

            // Send a Single Email using the Mail Helper
            var from             = new EmailAddress(fromEmail, fromEmailAliasName);
            var subject          = "Hello World from the SendGrid CSharp Library Helper!";
            var to               = new EmailAddress(toEmail, toEmailAlias);
            var plainTextContent = "Hello, Email from the helper [SendSingleEmailAsync]!";
            var htmlContent      = "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>";
            var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);

            var response = await client.SendEmailAsync(msg);

            Console.WriteLine(msg.Serialize());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // Send a Single Email using the Mail Helper with convenience methods and initialized SendGridMessage object
            msg = new SendGridMessage()
            {
                From             = new EmailAddress(fromEmail, fromEmailAliasName),
                Subject          = "Hello World from the SendGrid CSharp Library Helper!",
                PlainTextContent = "Hello, Email from the helper [SendSingleEmailAsync]!",
                HtmlContent      = "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>"
            };
            msg.AddTo(new EmailAddress(toEmail, toEmailAlias));

            response = await client.SendEmailAsync(msg);

            Console.WriteLine(msg.Serialize());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // Send a Single Email using the Mail Helper, entirely with convenience methods
            msg = new SendGridMessage();
            msg.SetFrom(new EmailAddress(fromEmailAliasName, "Phong Ha"));
            msg.SetSubject("Hello World from the SendGrid CSharp Library Helper!");
            msg.AddContent(MimeType.Text, "Hello, Email from the helper [SendSingleEmailAsync]!");
            msg.AddContent(MimeType.Html, "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>");
            msg.AddTo(new EmailAddress(toEmail, toEmailAlias));

            response = await client.SendEmailAsync(msg);

            Console.WriteLine(msg.Serialize());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();
        }
        public void Attachment()
        {
            var client = new SendGridClient(ConfigurationManager.AppSettings["ApiKey"]);

            var message = new SendGridMessage();

            message.To.Add(ConfigurationManager.AppSettings["MailTo"]);
            message.From = ConfigurationManager.AppSettings["MailFrom"];

            message.Subject = "file attachment";
            message.Text = "file attachment test";

            message.AddAttachment(ConfigurationManager.AppSettings["AttachmentImage"]);

            client.Send(message);
        }
        /// <summary>
        /// Sends an email via SendGrid API.
        /// </summary>
        /// <param name="details"></param>
        /// <returns>SendEmailResponse Object.</returns>
        public async Task <SendEmailResponse> SendEmailAsync(SendEmailDetails details)
        {
            var apiKey = Configuration["NutshellRepoSendGridKey"];

            var client = new SendGridClient(apiKey);

            var from = new EmailAddress(
                Configuration["SendEmailSettings:SendEmailFromEmail"],
                Configuration["SendEmailSettings:SendEmailFromName"]
                );

            var subject = details.Subject;

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

            var content = details.Content;

            var msg = MailHelper.CreateSingleEmail(
                from,
                to,
                subject,
                //content goes here if message type is text
                details.IsHTML ? null : content,
                //content goes here if message type is HTML
                details.IsHTML ? content : null
                );

            var response = await client.SendEmailAsync(msg);

            if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                return(new SendEmailResponse());
            }

            //if we have an error sending the email
            try
            {
                var bodyResult = await response.Body.ReadAsStringAsync();

                var sendGridResponse = JsonConvert.DeserializeObject <SendGridResponse>(bodyResult);

                var errorResponse = new SendEmailResponse
                {
                    Errors = sendGridResponse?.Errors.Select(f => f.Message).ToList()
                };

                if (errorResponse.Errors == null || errorResponse.Errors.Count == 0)
                {
                    errorResponse.Errors = new List <string>(new[] { "Unknown error from email sending service." });
                }

                return(errorResponse);
            }
            catch (Exception)
            {
                return(new SendEmailResponse
                {
                    Errors = new List <string>(new[] { "Unknown error occurred" })
                });
            }
        }
        public void TemplateEngine()
        {
            var client = new SendGridClient(ConfigurationManager.AppSettings["ApiKey"]);

            var message = new SendGridMessage();

            message.To.Add(ConfigurationManager.AppSettings["MailTo"]);
            message.From = ConfigurationManager.AppSettings["MailFrom"];

            message.Subject = " ";
            message.Text = " ";

            message.UseTemplateEngine("91ba5fd7-984c-4810-95fd-030be7242106");

            message.Header.AddSubstitution("-name-", "抱かれたい男 No.1");
            message.Header.AddSubstitution("-url-", "http://buchizo.wordpress.com/");

            client.Send(message);
        }
 private async Task VerstuurMail(SendGridMessage bericht)
 {
     SendGridClient client   = new SendGridClient(_apiKey);
     var            response = await client.SendEmailAsync(bericht);
 }
        private async Task SendCustomizedNewGroupEmailToUser(string groupDetailsUri, Group newGroup, SendGridClient client, ApplicationUser user)
        {
            StringBuilder NotificationEmailContent = new StringBuilder();

            NotificationEmailContent.Append($"Hola {user.Name}!");
            NotificationEmailContent.Append("</br>");
            NotificationEmailContent.Append("</br>");
            NotificationEmailContent.Append("<p>Se acaba e crear un nuevo grupo afín a tus intereses, que creemos que te podría interesar.</br>");
            NotificationEmailContent.Append($"Su nombre es <b>{newGroup.Name}</b> y su sede está en <b>{newGroup.City}</b>, <b>{newGroup.Country}</b>.</p>");
            NotificationEmailContent.Append("<p>Sobre este grupo y sus intereses, podemos contarte lo siguiente:</p>");
            NotificationEmailContent.Append($"<p><i>{newGroup.AboutUs}</i></p>");
            NotificationEmailContent.Append($"<p>Si quieres unirte al grupo, pulsa el siguiente enlace: <a href=\"{groupDetailsUri}\" > Quiero saber más de: {newGroup.Name}</a></p>");
            NotificationEmailContent.Append("<p>Un saludo,</br>");
            NotificationEmailContent.Append("Equipo MyMeetUp</p>");

            var msg = new SendGridMessage()
            {
                From        = new EmailAddress(SendGridMailAccount, "MyMeetUp Team"),
                Subject     = "MyMeetUp: Nuevo Grupo interesante!",
                HtmlContent = NotificationEmailContent.ToString()
            };

            msg.AddTo(new EmailAddress(MockMailAccountTo));
            var response = await client.SendEmailAsync(msg);

            _log.LogWarning($"SendGrid response: {response.StatusCode}. Email sent to {user.Name} {user.Surname} related to new group created: {newGroup.Name}");
            NotificationEmailContent.Clear();
        }
        public void EmbedImage()
        {
            var client = new SendGridClient(ConfigurationManager.AppSettings["ApiKey"]);

            var message = new SendGridMessage();

            message.To.Add(ConfigurationManager.AppSettings["MailTo"]);
            message.From = ConfigurationManager.AppSettings["MailFrom"];

            message.Subject = "file attachment";
            message.Html = "file attachment test<br /><img src=\"cid:hogehoge\" /><br />inline image";

            message.AddAttachment(ConfigurationManager.AppSettings["AttachmentImage"], "maki.jpg");
            message.Content.Add("maki.jpg", "hogehoge");

            client.Send(message);
        }
        public SendGridApiEmailSender(IOptions <AppSettingsModel> appSettingsOptions)
        {
            var appSettings = appSettingsOptions?.Value ?? throw new ArgumentNullException(nameof(appSettingsOptions));

            _sendGridClient = new SendGridClient(appSettings.SMTPPassword);
        }
Beispiel #34
0
        private async Task configSendGridasync(IdentityMessage message)
        {
            //   var myMessage = new SendGridMessage();
            //   myMessage.AddTo(message.Destination);
            //   myMessage.From = new System.Net.Mail.MailAddress(
            //                       "*****@*****.**", "VTechClub-ComputerRepairBranch");
            //   myMessage.Subject = message.Subject;
            //   myMessage.Text = message.Body;
            //   myMessage.Html = message.Body;

            //var credentials = new NetworkCredential(
            //           ConfigurationManager.AppSettings["mailAccount"],
            //           ConfigurationManager.AppSettings["mailPassword"]
            //           );
            //   var cre = new NetworkCredential();
            //   cre.UserName = "******";
            //   cre.Password = "******";

            //   // Create a Web transport for sending email.
            ////  var transportWeb = new Web(credentials);
            // var transportWeb = new  Web(cre );
            //   // Send the email.
            //   if (transportWeb != null)
            //   {
            //       await transportWeb.DeliverAsync(myMessage);
            //   }
            //   else
            //   {
            //       Trace.TraceError("Failed to create Web transport.");
            //       await Task.FromResult(0);
            //   }



            //var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
            var client           = new SendGridClient("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");
            var from             = new EmailAddress("*****@*****.**", "VTechClub-ComputerRepairBranch");
            var subject          = message.Subject;
            var to               = new EmailAddress(message.Destination);
            var plainTextContent = message.Body;
            var htmlContent      = message.Body;
            var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);


            //byte[] imageArray = System.IO.File.ReadAllBytes(@"~\Images\VtechLogo.png");
            //string base64ImageRepresentation = Convert.ToBase64String(imageArray);
            //var att = new Attachment()
            //{
            //    Content = Convert.ToBase64String(imageArray),
            //    Type="image/png",
            //    Filename="VtechLogo.png",
            //    ContentId="Vtech 2",
            //    Disposition="inline",
            //    };

            //msg.AddAttachment("VtechLogo.png", base64ImageRepresentation);
            msg.AddSubstitution("-name-", "VTech Club App");
            msg.AddSubstitution("-city-", "Orlando");
            msg.AddSubstitution("-state-", "Florida");
            msg.AddHeader("-header-", "Welcome to Vtech Club app");

            //msg.SetFooterSetting(
            //         true,
            //         "hello world",
            //         "<br/><h1>hello world</h1>");
            // Attachment att = new Attachment{ s}



            //msg.SetFooterSetting(
            //          true,
            //          "Computer Repair Branch",
            //          "<strong>Valencia Technology Club</strong>");
            var response = await client.SendEmailAsync(msg);
        }
Beispiel #35
0
 private async Task SendMailAsync(Message message)
 {
     var mail     = this.PrepareMail(message);
     var sendgrid = new SendGridClient(apiKey);
     var response = await sendgrid.SendEmailAsync(mail);
 }
Beispiel #36
0
 public static void SendEmail(string To, string body, string Subject)
 {
     var apiKey           = "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";
     var client           = new SendGridClient(apiKey);
     var from             = new EmailAddress("*****@*****.**", "PlusB Service Desk");
     var subject          = Subject;
     var to               = new EmailAddress(To, "Customer");
     var plainTextContent = body;
     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>" + body + " </p>" +
                            "<table border='0' cellpadding='0'cellspacing='0'>" +
                            "<tbody>" +
                            "<tr>" +
                            "<td align='left'>" +
                            "<table border='0' cellpadding='0'cellspacing='0'>" +
                            "   <tbody>" +
                            "      <tr>" +
                            "        </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;color:#000;font-size:12px;'>" +
                            "<span style='color:#000;font-size:12px;'>PlusB Consulting Escazú, San José Costa Rica</span>" +
                            " <br/> Don't like these emails? <a style='color:#000;font-size:12px;'>Unsubscribe</a>." +
                            " </td>" +
                            "</tr>" +
                            "<tr>" +
                            "<td style='padding-bottom:10px;padding-top:10px;text-decoration:none;color:#000;font-size:12px;'>" +
                            "Powered by <a style='color:#000;font-size:12px;'>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);
 }
Beispiel #37
0
 public EmailNotificationService(SendGridClient sgClient)
 {
     this.sgClient = sgClient;
 }