Exemple #1
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 #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 static string Run(
            [ActivityTrigger] OrdiniAcquistoModel ordiniAcquisto,
            [OrchestrationClient] DurableOrchestrationClient starter,
            [SendGrid(ApiKey = "SendGridApiKey")]
            out Mail message)
        {
            string currentInstance = Guid.NewGuid().ToString("N");

            Log.Information($"InviaMailOrdineCliente : {currentInstance}");

            string toMail   = Utility.GetEnvironmentVariable("SendGridTo");
            string fromMail = Utility.GetEnvironmentVariable("SendGridFrom");

            Log.Information($"Invio ordine {ordiniAcquisto.IdOrdine} a {ordiniAcquisto.ClienteCorrente.NumeroTelefono}.");
            message = new Mail
            {
                Subject = $"GlobalAzureBootcamp 2018"
            };
            var personalization = new Personalization();

            personalization.AddTo(new Email(toMail));
            Content content = new Content
            {
                Type  = "text/html",
                Value = $@"L'ordine {ordiniAcquisto.IdOrdine} è stato preso in carico
                <br><a href='{Utility.GetEnvironmentVariable("PublicUrl")}/ApprovaOrdine?ordineId={ordiniAcquisto.IdOrdine}'>Conferma ordine</a>"
            };

            message.From = new Email(fromMail);
            message.AddContent(content);
            message.AddPersonalization(personalization);

            return(currentInstance);
        }
Exemple #4
0
        public static Mail RequestApproval([ActivityTrigger] ApprovalRequest approvalRequest, TraceWriter log)
        {
            // Orchestratorを再開するためのOrchestration ClientのエンドポイントとなるURL
            var approveURL = ConfigurationManager.AppSettings.Get("APPROVE_URL");

            // 承認者のメール。サンプルなので固定にしているが、承認者情報をDBに保存してそれを取得するべき
            var email   = ConfigurationManager.AppSettings.Get("APPROVER_EMAIL");
            var message = new Mail
            {
                Subject = $"{approvalRequest.CalendarDate.ToString("yyyy/MM/dd")}のスタンプリクエスト"
            };

            Content content = new Content
            {
                Type  = "text/plain",
                Value = "承認するにはつぎのURLをクリックしてください。\n\n" +
                        $"{approveURL}&isApproved=true&instanceId={approvalRequest.InstanceId}\n\n\n" +
                        "却下するにはつぎのURLをクリックしてください。\n\n" +
                        $"{approveURL}&isApproved=false&instanceId={approvalRequest.InstanceId}"
            };

            message.AddContent(content);
            var personalization = new Personalization();

            personalization.AddTo(new Email(email));
            message.AddPersonalization(personalization);
            return(message);
        }
Exemple #5
0
        public static void Run(
            [QueueTrigger("emails", Connection = "AzureWebJobsStorage")] EmailDetails myQueueItem,
            TraceWriter log,
            [SendGrid(ApiKey = "SendGridApiKey")]
            out Mail mail)
        {
            log.Info($"C# Queue trigger function processed: {myQueueItem}");

            mail = new Mail();
            var personalization = new Personalization();

            personalization.AddTo(new Email(myQueueItem.Email));
            mail.AddPersonalization(personalization);

            var sb = new StringBuilder();

            sb.Append($"Hi {myQueueItem.Name},");
            sb.Append($"<p>You're invited to join us on {myQueueItem.EventDateAndTime} at {myQueueItem.Location}.</p>");
            sb.Append($"<p>Let us know if you can make it by clicking <a href=\"{myQueueItem.ResponseUrl}\">here</a></p>");
            log.Info(sb.ToString());

            var messageContent = new Content("text/html", sb.ToString());

            mail.AddContent(messageContent);
            mail.Subject = "Your invitation...";
            mail.From    = new Email("*****@*****.**");
        }
Exemple #6
0
        private async Task <bool> SendMessage(EmailCommunication email)
        {
            try
            {
                Mail mail = new Mail();
                mail.From    = new Email(email.Sender);
                mail.Subject = email.Subject;
                mail.AddContent(new Content("text/plain", email.Body));

                AddRecipients(email, mail);
                AddAttachments(email, mail);

                string type = Constants.MetaSettings.Types.Api;
                string code = Constants.MetaSettings.Codes.SendGridApiKey;

                IMetaSettingRepository settingRepository = _DataRepositoryFactory.GetDataRepository <IMetaSettingRepository>();
                string apiKey = settingRepository.GetSetting(type, code).Value;

                dynamic sg = new SendGrid.SendGridAPIClient(apiKey, "https://api.sendgrid.com");

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

                return(true);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        Run([ActivityTrigger] RequestApplication request,
            TraceWriter log)
        {
            log.Info("Sending Mail....Please wait");

            var    ToAddress        = Environment.GetEnvironmentVariable("CustomerMail");
            string storagePath      = Environment.GetEnvironmentVariable("StorageaccountBaseURL") + Environment.GetEnvironmentVariable("inputStorageContainer") + request.name;
            string FunctionBasePath = Environment.GetEnvironmentVariable("FunctionBasePath");
            string mailTemplate     = Environment.GetEnvironmentVariable("MailTemplate");
            string instanceid       = request.InstanceId;

            Mail message = new Mail();

            message = new Mail();
            var personalization = new Personalization();

            personalization.AddTo(new Email(ToAddress));
            message.AddPersonalization(personalization);
            log.Info(request.LocationUrl + request.name + request.InstanceId);
            var messageContent = new Content("text/html", string.Format(mailTemplate, storagePath, FunctionBasePath, instanceid));

            message.AddContent(messageContent);
            message.Subject = "Request for Approval";
            log.Info("Mail Sent....Please chek with your admin");

            return(message);
        }
Exemple #8
0
        public static async void Run([QueueTrigger("orderqueue", Connection = "AzureWebJobsStorage")] POCOOrder order,
                                     TraceWriter log, [SendGrid(ApiKey = "AzureWebJobsSendGridApiKey")] IAsyncCollector <Mail> outputMessage)
        {
            string msg = $"Hello " + order.CustomerName + "! Your order for " + order.ProductName + " with quantity of " + order.OrderCount + " has been shipped.";

            log.Info(msg);

            Mail message = new Mail
            {
                Subject = msg,
                From    = new Email("*****@*****.**", "No Reply"),
                ReplyTo = new Email("*****@*****.**", "Prodip Saha")
            };


            var personalization = new Personalization();

            // Change To email of recipient
            personalization.AddTo(new Email(order.CustomerEmail));

            Content content = new Content
            {
                Type  = "text/plain",
                Value = msg + "Thank you for being such a nice customer!"
            };

            message.AddContent(content);
            message.AddPersonalization(personalization);


            await outputMessage.AddAsync(message);
        }
        // This function will get triggered/executed when a new message is written
        // on an Azure Queue called queue.
        public static void ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log, [SendGrid(From = "*****@*****.**", To = "*****@*****.**")] out Mail mail)
        {
            log.WriteLine(message);

            mail = new Mail();

            mail.Subject = "WebJob - Queue message processed successfully";
            mail.AddContent(new Content("text/plain", $"The message '{message}' was successfully processed."));
        }
        /// <summary>
        /// Triggered when an error is reported in other functions.
        /// Called whenever 2 errors occur within a 3 minutes sliding window (throttled at a maximum of 2 notifications per 10 minutes).
        /// </summary>
        public static void GlobalErrorMonitor([ErrorTrigger("0:03:00", 2, Throttle = "0:10:00")] TraceFilter filter, TextWriter log, [SendGrid(From = "*****@*****.**", To = "*****@*****.**")] out Mail mail)
        {
            mail = new Mail();

            mail.Subject = "WebJob - Warning - An error has been detected in a job";
            mail.AddContent(new Content("text/plain", filter.GetDetailedMessage(1)));

            Console.Error.WriteLine("An error has been detected in a function.");

            log.WriteLine(filter.GetDetailedMessage(1));
        }
        internal static void DefaultMessageProperties(Mail mail, SendGridConfiguration config, SendGridAttribute attribute)
        {
            // Apply message defaulting
            if (mail.From == null)
            {
                if (!string.IsNullOrEmpty(attribute.From))
                {
                    Email from = null;
                    if (!TryParseAddress(attribute.From, out from))
                    {
                        throw new ArgumentException("Invalid 'From' address specified");
                    }
                    mail.From = from;
                }
                else if (config.FromAddress != null)
                {
                    mail.From = config.FromAddress;
                }
            }

            if (mail.Personalization == null || mail.Personalization.Count == 0)
            {
                if (!string.IsNullOrEmpty(attribute.To))
                {
                    Email to = null;
                    if (!TryParseAddress(attribute.To, out to))
                    {
                        throw new ArgumentException("Invalid 'To' address specified");
                    }

                    Personalization personalization = new Personalization();
                    personalization.AddTo(to);
                    mail.AddPersonalization(personalization);
                }
                else if (config.ToAddress != null)
                {
                    Personalization personalization = new Personalization();
                    personalization.AddTo(config.ToAddress);
                    mail.AddPersonalization(personalization);
                }
            }

            if (string.IsNullOrEmpty(mail.Subject) &&
                !string.IsNullOrEmpty(attribute.Subject))
            {
                mail.Subject = attribute.Subject;
            }

            if ((mail.Contents == null || mail.Contents.Count == 0) &&
                !string.IsNullOrEmpty(attribute.Text))
            {
                mail.AddContent(new Content("text/plain", attribute.Text));
            }
        }
Exemple #12
0
        public static void ProcessOrder_Imperative(
            [QueueTrigger(@"samples-orders")] Order order,
            [SendGrid] out Mail message)
        {
            message         = new Mail();
            message.Subject = $"Thanks for your order (#{order.OrderId})!";
            message.AddContent(new Content("text/plain", $"{order.CustomerName}, we've received your order ({order.OrderId}) and have begun processing it!"));

            Personalization personalization = new Personalization();

            personalization.AddTo(new Email(order.CustomerEmail));
            message.AddPersonalization(personalization);
        }
Exemple #13
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req,
            [SendGrid()] IAsyncCollector <Mail> message,
            TraceWriter log)
        {
            try
            {
                log.Info("ValidateTwitterFollowerCount function processed a request.");

                var tweetData = new
                {
                    TweetText      = "",
                    FollowersCount = "",
                    Name           = ""
                };

                var tweet = JsonConvert.DeserializeAnonymousType(await req.Content.ReadAsStringAsync(), tweetData);

                if (Convert.ToInt32(tweet.FollowersCount) > 100)
                {
                    Mail mail = new Mail()
                    {
                        Subject = $"{tweet.Name} with  {tweet.FollowersCount} followers has posted a tweet!"
                    };

                    Content content = new Content
                    {
                        Type  = "text/plain",
                        Value = $" Tweet Content : {tweet.TweetText}"
                    };

                    mail.AddContent(content);

                    var personalization = new Personalization();
                    personalization.AddTo(new Email(System.Environment.GetEnvironmentVariable("EmailTo")));
                    mail.AddPersonalization(personalization);

                    await message.AddAsync(mail);
                }

                return(req.CreateResponse(HttpStatusCode.OK));
            }
            catch (System.Exception ex)
            {
                return(req.CreateResponse(HttpStatusCode.InternalServerError, $"We apologize but something went wrong on our end.Exception:{ex.Message}"));
            }
            finally
            {
                log.Info("ValidateTwitterFollowerCount function has finished processing a request.");
            }
        }
Exemple #14
0
        public static async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req,
                                     [Table("UserProfile")] CloudTable userProfileTable,
                                     [SendGrid()] ICollector <Mail> message,
                                     TraceWriter log)
        {
            try
            {
                log.Info($"RegisterUserAndSendEmail function processed a request.");

                var user = JsonConvert.DeserializeObject <UserProfile>(await req.Content.ReadAsStringAsync());

                if (user == null)
                {
                    throw new System.Exception("Please provide values for First name,Last Name and Profile Picture");
                }

                var userProfile = new UserProfile(user.FirstName, user.LastName, user.ProfilePicture, string.Empty);

                TableOperation tableOperationInsert = TableOperation.Insert(userProfile);

                userProfileTable.Execute(tableOperationInsert);

                Mail mail = new Mail()
                {
                    Subject = $"Thanks {userProfile.FirstName} {userProfile.LastName} for your Sign Up!"
                };

                //var personalization = new Personalization();
                //personalization.AddTo(new Email("the-email-address-of-recipient"));

                Content content = new Content
                {
                    Type  = "text/plain",
                    Value = $"{userProfile.FirstName}, here's the link for your profile picture {userProfile.ProfilePicture}!"
                };

                mail.AddContent(content);

                message.Add(mail);
            }
            catch (System.Exception ex)
            {
                log.Info($"RegisterUserAndSendEmail function : Exception:{ ex.Message}");
                throw;
            }
            finally
            {
                log.Info("RegisterUserAndSendEmail function has finished processing a request.");
            }
        }
Exemple #15
0
        public async Task <HttpStatusCode> SendEmailsContacts(List <ContactsModel> contacts, string username)
        {
            dynamic sg = new SendGrid.SendGridAPIClient(GetKey());

            var             mail = new Mail();
            Personalization personalization;

            foreach (var contact in contacts)
            {
                personalization = new Personalization();
                Email to = new Email();

                if (!string.IsNullOrEmpty(contact.Name))
                {
                    to.Name = contact.Name;
                }
                else
                {
                    var atIndex = contact.Email.IndexOf('@');
                    to.Name = contact.Email.Substring(0, atIndex);
                }
                to.Address = contact.Email;
                personalization.AddTo(to);
                personalization.AddSubstitution("%invited%", to.Name);
                personalization.AddSubstitution("%username%", username);
                //personalization.AddCustomArgs("marketing", "false");
                //personalization.AddCustomArgs("transactional", "true");
                mail.AddPersonalization(personalization);
            }

            var body = @"
			<p>
			Hello %invited%,
			</p>
			<p>&nbsp;</p>
			<p>
			Your friend %username%, has invited you to join him on our community.
			</p>"            ;

            mail.AddContent(new Content("text/html", body));
            mail.From    = new Email(ConfigurationManager.AppSettings["DomainEmail"], ConfigurationManager.AppSettings["DomainName"]);
            mail.Subject = "%invited%, special Invitation to join";

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

            return((HttpStatusCode)response.StatusCode);
            //System.Diagnostics.Trace.WriteLine(response.Body.ReadAsStringAsync().Result);
            //System.Diagnostics.Trace.WriteLine(response.Headers.ToString());
            //System.Diagnostics.Trace.WriteLine(mail.Get());
        }
Exemple #16
0
        // Use NuGet to install SendGrid (Basic C# client lib)
        private async Task configSendGridasync(IdentityMessage message)
        {
            String  apiKey = ConfigurationManager.AppSettings["SendGrid_Key"];
            dynamic sg     = new SendGridAPIClient(apiKey);

            Email   from        = new Email("*****@*****.**");
            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);
            Content htmlContent = new Content("text/html", message.Body);

            mail.AddContent(htmlContent);
            dynamic response = await sg.client.mail.send.post(requestBody : mail.Get());
        }
        public static Mail CreateMail(string content, string date)
        {
            var personalization = new Personalization();

            personalization.Tos = GetEmailReceivers().ToList();

            var mail = new Mail();

            mail.AddPersonalization(personalization);
            mail.From    = new Email(Environment.GetEnvironmentVariable("SendGrid:From"));
            mail.Subject = string.Format(Environment.GetEnvironmentVariable("SendGrid:Subject"), date);
            mail.AddContent(new Content("text", content));
            //mail.AddAttachment("telemetry.md", content);

            return(mail);
        }
        /// <summary>
        /// Send an email notification using SendGrid.
        /// </summary>
        /// <param name="filter">The <see cref="TraceFilter"/> that triggered the notification.</param>
        public void EmailNotify(TraceFilter filter)
        {
            Mail message = new Mail()
            {
                From    = _sendGridConfig.FromAddress,
                Subject = "WebJob Error Notification"
            };

            message.AddContent(new Content("text/plain", filter.GetDetailedMessage(5)));
            Personalization personalization = new Personalization();

            personalization.AddTo(_sendGridConfig.ToAddress);
            message.AddPersonalization(personalization);

            _sendGrid.client.mail.send.post(requestBody: message.Get());
        }
Exemple #19
0
        private Task configSendGridasync(IdentityMessage message)
        {
            String  apiKey = ConfigurationManager.AppSettings["SendGrid_Key"];
            dynamic sg     = new SendGridAPIClient(apiKey);

            Email   from        = new Email("*****@*****.**");
            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);
            Content htmlContent = new Content("text/html", message.Body);

            mail.AddContent(htmlContent);

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

            return(Task.FromResult(0));
        }
Exemple #20
0
        private static Mail CreateMail(IReadOnlyCollection <StationStatus> statuses, DateTime verificarionTimeUtc)
        {
            var mail = new Mail
            {
                Subject = $"{nameof(WeatherStationUpload)} notification"
            };

            Content content = new Content
            {
                Type  = "text/plain",
                Value = string.Join(Environment.NewLine,
                                    new[] { $"Verification time UTC: {verificarionTimeUtc}" }
                                    .Concat(statuses.Select(status => status.ToString())))
            };

            mail.AddContent(content);

            return(mail);
        }
Exemple #21
0
        public static Mail Run([QueueTrigger("PathValue", Connection = "ConnectionValue")] Order order, TraceWriter log)
#endif
{
    log.Info($"C# Queue trigger function processed order: {order.OrderId}");

    Mail message = new Mail()
    {
        Subject = $"Thanks for your order (#{order.OrderId})!"
    };

    Content content = new Content
    {
        Type  = "text/plain",
        Value = $"{order.CustomerName}, your order ({order.OrderId}) is being processed!"
    };

    message.AddContent(content);
    return(message);
}
Exemple #22
0
        public static void SendEmail(
            [ActivityTrigger] DurableActivityContext context,
            [SendGrid] out Mail message,
            TraceWriter log)
        {
            var info             = context.GetInput <KokuhakuInformation>();
            var approvalEndpoint = ConfigurationManager.AppSettings["KokuhakuApprovalEndpoint"];
            var fromEmail        = ConfigurationManager.AppSettings["FromEmail"];

            message = new Mail
            {
                Subject = "あなたにラブレターが届いています",
            };

            var personalization = new Personalization();
            var toEmail         = info.TargetEmail;

            if (toEmail.StartsWith(SlackEmailFormatPrefix)) // for slack email address format.
            {
                var endIndex = toEmail.IndexOf('|');
                toEmail = toEmail.Substring(SlackEmailFormatPrefix.Length, endIndex - SlackEmailFormatPrefix.Length);
            }

            log.Info($"To: {toEmail}, Org: {info.TargetEmail}");
            personalization.AddTo(new Email(toEmail));
            message.AddPersonalization(personalization);
            message.From = new Email(fromEmail);
            message.AddContent(new Content
            {
                Type  = "text/html",
                Value = $@"<html>
<body>
<h2>要求</h2>
我君ヲ愛ス。{info.Activity.From.Name}ヨリ。
<hr />
<h2>回答</h2>
<a href='{approvalEndpoint}?instanceId={context.InstanceId}&approved=true'>受けて立つ場合はこちらをクリック</a>
<br/>
<a href='{approvalEndpoint}?instanceId={context.InstanceId}&approved=false'>受けて立たない場合はこちらをクリック</a>
</body>
</html>",
            });
        }
Exemple #23
0
        /// <summary>
        /// Get a mail object to sendgrid
        /// </summary>
        private static Mail PrepareSendGridMessage(MessageCredential credential, MessageSend message)
        {
            Personalization personalizacion = new Personalization();

            foreach (var mailto in message.MailTo)
            {
                personalizacion.AddTo(new Email(mailto));
            }

            foreach (var ccp in message.CCP)
            {
                personalizacion.AddCc(new Email(ccp));
            }

            foreach (var cco in message.CCO)
            {
                personalizacion.AddBcc(new Email(cco));
            }

            Mail mail = new Mail();

            mail.From = new Email(credential.UserName, credential.DisplayName);

            mail.Subject    = message.Subject;
            mail.CustomArgs = message.Args;

            foreach (var attachment in message.Attachment)
            {
                Byte[] bytes = File.ReadAllBytes(attachment);

                mail.AddAttachment(new SendGrid.Helpers.Mail.Attachment()
                {
                    Filename = Path.GetFileName(attachment), Content = Convert.ToBase64String(bytes)
                });

                bytes = null;
            }

            mail.AddContent(new Content("text/html", message.Body));
            mail.AddPersonalization(personalizacion);

            return(mail);
        }
        public static Mail Run(TimerInfo myTimer, TraceWriter log)
        {
            var today = DateTime.Today.ToShortDateString();

            log.Info($"Generating daily report for {today} at {DateTime.Now}");

            Mail message = new Mail()
            {
                Subject = "15 DK'LIK TEST MAILI"
            };

            Content content = new Content
            {
                Type  = "text/plain",
                Value = "Bu mail 15 dk da bir yinelenecektir."
            };

            message.AddContent(content);
            return(message);
        }
Exemple #25
0
        public void DefaultMessageProperties_CreatesExpectedMessage()
        {
            SendGridAttribute     attribute = new SendGridAttribute();
            SendGridConfiguration config    = new SendGridConfiguration
            {
                ApiKey      = "12345",
                FromAddress = new Email("*****@*****.**", "Test2"),
                ToAddress   = new Email("*****@*****.**", "Test")
            };

            Mail message = new Mail();

            message.Subject = "TestSubject";
            message.AddContent(new Content("text/plain", "TestText"));

            SendGridHelpers.DefaultMessageProperties(message, config, attribute);

            Assert.Same(config.FromAddress, config.FromAddress);
            Assert.Equal("*****@*****.**", message.Personalization.Single().Tos.Single().Address);
            Assert.Equal("TestSubject", message.Subject);
            Assert.Equal("TestText", message.Contents.Single().Value);
        }
Exemple #26
0
        private void SendEmailNotification(string sendToEmailAddress, string subject, string message)
        {
            if (string.IsNullOrEmpty(sendToEmailAddress))
            {
                string invalidEmailMessage = "Notification not sent. Email address not available";
                Trace.TraceError(string.Format(message));
                Trace.TraceError(invalidEmailMessage);
                throw new FormatException(invalidEmailMessage);
            }

            var     sg          = new SendGrid.SendGridAPIClient(Config.SendGridApiKey, Config.SendGridEndPoint);
            Email   from        = new Email(Config.NotificationFromEmailAddress, Config.NotificationFromName);
            Content content     = new Content("text/plain", message.Replace(htmlLineBreak, Environment.NewLine));
            Content htmlContent = new Content("text/html", message);

            var to   = new Email(sendToEmailAddress);
            var mail = new Mail(from, subject, to, content);

            mail.AddContent(htmlContent);
            mail.Subject = subject;

            var requestBody = mail.Get();

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

            HttpStatusCode statusCode = response.StatusCode;

            if (((int)statusCode >= 200) && ((int)statusCode <= 299))
            {
                Trace.TraceInformation("Email notification sent.");
            }
            else
            {
                Trace.TraceError(string.Format("Error sending email notification. {0}, {1}", statusCode, message));
                throw new HttpException((int)statusCode, "Email could not be sent!");
            }
        }
Exemple #27
0
        private static Mail FormSendGridMail(EmailMessage message)
        {
            SendGridEmail from    = new SendGridEmail(message.From);
            string        subject = message.Subject;
            Content       content = new Content(message.ContentType, message.EmailContent);
            Mail          mail    = new Mail();

            mail.From    = from;
            mail.Subject = subject;
            mail.AddContent(content);
            var tos = new List <SendGridEmail>();

            foreach (var to in message.To)
            {
                tos.Add(new SendGridEmail(to));
            }

            mail.AddPersonalization(new Personalization
            {
                Tos = tos
            });

            return(mail);
        }
        public static async Task Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req,
            [Table("UserProfile")] CloudTable userProfileTable,
            [Queue("emaillogqueue")] CloudQueue queue,
            IBinder binder,
            [SendGrid()] IAsyncCollector <Mail> message,
            [TwilioSms()] IAsyncCollector <SMSMessage> smsMessage,
            TraceWriter log)
        {
            try
            {
                log.Info($"RegisterUserAndSendSms function processed a request.");

                var user = JsonConvert.DeserializeObject <UserProfile>(await req.Content.ReadAsStringAsync());
                if (user == null)
                {
                    throw new System.Exception("Please provide values for First name,Last Name and Profile Picture");
                }
                var userProfile = new UserProfile(user.FirstName, user.LastName, user.ProfilePicture, user.Email);

                var tblInsertOperation = TableOperation.Insert(userProfile);
                var insertResult       = await userProfileTable.ExecuteAsync(tblInsertOperation);

                var insertedUser = (UserProfile)insertResult.Result;

                var mail = new Mail
                {
                    Subject = $"Thanks {userProfile.FirstName} {userProfile.LastName} for your Sign Up!"
                };

                var personalization = new Personalization();
                personalization.AddTo(new Email(userProfile.Email));

                Content content = new Content
                {
                    Type  = "text/plain",
                    Value = $"{userProfile.FirstName}, here's the link for your profile picture {userProfile.ProfilePicture}!"
                };

                await queue.AddMessageAsync(new CloudQueueMessage(content.Value.ToString()));

                var queueMessage = await queue.GetMessageAsync();

                var data = queueMessage.AsString;
                using (var emailLogBlob = binder.Bind <TextWriter>(new BlobAttribute($"emailogblobcontainer/{insertedUser.RowKey}.log")))
                {
                    await emailLogBlob.WriteAsync(data);
                }

                var attachment = new Attachment();
                attachment.Content  = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(data));
                attachment.Filename = $"{insertedUser.FirstName}_{insertedUser.LastName}.log";
                mail.AddAttachment(attachment);
                mail.AddContent(content);
                mail.AddPersonalization(personalization);
                await message.AddAsync(mail);

                //SMS Code
                var sms = new SMSMessage();
                sms.To   = "XXXXXXXXXXXXXXX";
                sms.From = System.Configuration.ConfigurationManager.AppSettings["AzureWebJobsFromNumber"];
                sms.Body = "How is it going!";

                await smsMessage.AddAsync(sms);
            }
            catch (System.Exception ex)
            {
                log.Info($"RegisterUserAndSendSms function : Exception:{ ex.Message}");
                throw;
            }
            finally
            {
                log.Info("RegisterUserAndSendSms function has finished processing a request.");
            }
        }
Exemple #29
0
        private static void KitchenSink()
        {
            String  apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User);
            dynamic sg     = new SendGrid.SendGridAPIClient(apiKey, "https://api.sendgrid.com");

            Mail mail = new Mail();

            Email email = new Email();

            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            mail.From     = email;

            mail.Subject = "Hello World from the SendGrid CSharp Library";

            Personalization personalization = new Personalization();

            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddTo(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            personalization.Subject = "Thank you for signing up, %name%";
            personalization.AddHeader("X-Test", "True");
            personalization.AddHeader("X-Mock", "True");
            personalization.AddSubstitution("%name%", "Example User");
            personalization.AddSubstitution("%city%", "Denver");
            personalization.AddCustomArgs("marketing", "false");
            personalization.AddCustomArgs("transactional", "true");
            personalization.SendAt = 1461775051;
            mail.AddPersonalization(personalization);

            personalization = new Personalization();
            email           = new Email();
            email.Name      = "Example User";
            email.Address   = "*****@*****.**";
            personalization.AddTo(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            personalization.Subject = "Thank you for signing up, %name%";
            personalization.AddHeader("X-Test", "True");
            personalization.AddHeader("X-Mock", "True");
            personalization.AddSubstitution("%name%", "Example User");
            personalization.AddSubstitution("%city%", "Denver");
            personalization.AddCustomArgs("marketing", "false");
            personalization.AddCustomArgs("transactional", "true");
            personalization.SendAt = 1461775051;
            mail.AddPersonalization(personalization);

            Content content = new Content();

            content.Type  = "text/plain";
            content.Value = "Textual content";
            mail.AddContent(content);
            content       = new Content();
            content.Type  = "text/html";
            content.Value = "<html><body>HTML content</body></html>";
            mail.AddContent(content);
            content       = new Content();
            content.Type  = "text/calendar";
            content.Value = "Party Time!!";
            mail.AddContent(content);

            Attachment attachment = new Attachment();

            attachment.Content     = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12";
            attachment.Type        = "application/pdf";
            attachment.Filename    = "balance_001.pdf";
            attachment.Disposition = "attachment";
            attachment.ContentId   = "Balance Sheet";
            mail.AddAttachment(attachment);

            attachment             = new Attachment();
            attachment.Content     = "BwdW";
            attachment.Type        = "image/png";
            attachment.Filename    = "banner.png";
            attachment.Disposition = "inline";
            attachment.ContentId   = "Banner";
            mail.AddAttachment(attachment);

            mail.TemplateId = "13b8f94f-bcae-4ec6-b752-70d6cb59f932";

            mail.AddHeader("X-Day", "Monday");
            mail.AddHeader("X-Month", "January");

            mail.AddSection("%section1", "Substitution for Section 1 Tag");
            mail.AddSection("%section2", "Substitution for Section 2 Tag");

            mail.AddCategory("customer");
            mail.AddCategory("vip");

            mail.AddCustomArgs("campaign", "welcome");
            mail.AddCustomArgs("sequence", "2");

            ASM asm = new ASM();

            asm.GroupId = 3;
            List <int> groups_to_display = new List <int>()
            {
                1, 4, 5
            };

            asm.GroupsToDisplay = groups_to_display;
            mail.Asm            = asm;

            mail.SendAt = 1461775051;

            mail.SetIpPoolId = "23";

            // This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html)
            // mail.BatchId = "some_batch_id";

            MailSettings mailSettings = new MailSettings();
            BCCSettings  bccSettings  = new BCCSettings();

            bccSettings.Enable       = true;
            bccSettings.Email        = "*****@*****.**";
            mailSettings.BccSettings = bccSettings;
            BypassListManagement bypassListManagement = new BypassListManagement();

            bypassListManagement.Enable       = true;
            mailSettings.BypassListManagement = bypassListManagement;
            FooterSettings footerSettings = new FooterSettings();

            footerSettings.Enable       = true;
            footerSettings.Text         = "Some Footer Text";
            footerSettings.Html         = "<bold>Some HTML Here</bold>";
            mailSettings.FooterSettings = footerSettings;
            SandboxMode sandboxMode = new SandboxMode();

            sandboxMode.Enable       = true;
            mailSettings.SandboxMode = sandboxMode;
            SpamCheck spamCheck = new SpamCheck();

            spamCheck.Enable       = true;
            spamCheck.Threshold    = 1;
            spamCheck.PostToUrl    = "https://gotchya.example.com";
            mailSettings.SpamCheck = spamCheck;
            mail.MailSettings      = mailSettings;

            TrackingSettings trackingSettings = new TrackingSettings();
            ClickTracking    clickTracking    = new ClickTracking();

            clickTracking.Enable           = true;
            clickTracking.EnableText       = false;
            trackingSettings.ClickTracking = clickTracking;
            OpenTracking openTracking = new OpenTracking();

            openTracking.Enable           = true;
            openTracking.SubstitutionTag  = "Optional tag to replace with the open image in the body of the message";
            trackingSettings.OpenTracking = openTracking;
            SubscriptionTracking subscriptionTracking = new SubscriptionTracking();

            subscriptionTracking.Enable           = true;
            subscriptionTracking.Text             = "text to insert into the text/plain portion of the message";
            subscriptionTracking.Html             = "<bold>HTML to insert into the text/html portion of the message</bold>";
            subscriptionTracking.SubstitutionTag  = "text to insert into the text/plain portion of the message";
            trackingSettings.SubscriptionTracking = subscriptionTracking;
            Ganalytics ganalytics = new Ganalytics();

            ganalytics.Enable           = true;
            ganalytics.UtmCampaign      = "some campaign";
            ganalytics.UtmContent       = "some content";
            ganalytics.UtmMedium        = "some medium";
            ganalytics.UtmSource        = "some source";
            ganalytics.UtmTerm          = "some term";
            trackingSettings.Ganalytics = ganalytics;
            mail.TrackingSettings       = trackingSettings;

            email         = new Email();
            email.Address = "*****@*****.**";
            mail.ReplyTo  = email;

            String ret = mail.Get();

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

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

            Console.WriteLine(ret);
            Console.ReadLine();
        }
Exemple #30
0
        public string SendGridMsg(MailAddress from, string subject, string message, List <MailAddress> to, int?id, int?pid, List <MailAddress> cc = null)
        {
            var senderrorsto = ConfigurationManager.AppSettings["senderrorsto"];

            string fromDomain, apiKey;

            if (ShouldUseCustomEmailDomain)
            {
                fromDomain = CustomFromDomain;
                apiKey     = CustomSendGridApiKey;
            }
            else
            {
                fromDomain = DefaultFromDomain;
                apiKey     = DefaultSendGridApiKey;
            }

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

            var mail = new Mail
            {
                From    = new Email(fromDomain, from.DisplayName),
                Subject = subject,
                ReplyTo = new Email(from.Address, from.DisplayName)
            };
            var pe = new Personalization();

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

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

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

            mail.AddPersonalization(pe);

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

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

            var regex = new Regex("</?([^>]*)>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            var text  = regex.Replace(message, string.Empty);
            var html  = badEmailLink + message + CcMessage(cc);

            mail.AddContent(new MContent("text/plain", text));
            mail.AddContent(new MContent("text/html", html));

            var reqBody = mail.Get();

            using (var wc = new WebClient())
            {
                wc.Headers.Add("Authorization", $"Bearer {apiKey}");
                wc.Headers.Add("Content-Type", "application/json");
                wc.UploadString("https://api.sendgrid.com/v3/mail/send", reqBody);
            }
            return(fromDomain);
        }