Exemple #1
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 #2
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 #3
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();
        }
        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);
        }
        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 #6
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);
        }
        public async Task SendHtmlEmail(string subject, string toEmail, string content)
        {
            string  apiKey = _configurationService.Email.ApiKey;
            dynamic sg     = new SendGridAPIClient(apiKey);

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

            var personalization = new Personalization();

            personalization.AddTo(to);

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

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

            if (response.StatusCode != System.Net.HttpStatusCode.Accepted)
            {
                var responseMsg = response.Body.ReadAsStringAsync().Result;
                _logger.Error($"Unable to send email: {responseMsg}");
            }
        }
        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 #9
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 #10
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 #11
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());
        }
        /// <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 #13
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 #14
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);
        }
Exemple #15
0
        private void AddRecipients(EmailCommunication email, Mail mail)
        {
            Personalization personalization = new Personalization();

            string[] recipients = email.Recipients.Split(';');
            recipients.ToList().ForEach(r => personalization.AddTo(new Email(r)));

            if (email.CcRecipients != null)
            {
                email.CcRecipients.ToList().ForEach(r => personalization.AddCc(new Email(r)));
            }

            if (email.BccRecipients != null)
            {
                email.BccRecipients.ToList().ForEach(r => personalization.AddBcc(new Email(r)));
            }

            mail.AddPersonalization(personalization);
        }
Exemple #16
0
        public void IsToValid()
        {
            // Null Personalization
            Mail mail = new Mail();

            mail.Personalization = null;
            Assert.False(SendGridHelpers.IsToValid(mail));

            // Empty Personalization
            mail.Personalization = new List <Personalization>();
            Assert.False(SendGridHelpers.IsToValid(mail));

            // 'To' with no address
            Personalization personalization = new Personalization();

            personalization.AddTo(new Email());
            mail.AddPersonalization(personalization);
            Assert.False(SendGridHelpers.IsToValid(mail));

            // Personalization with no 'To'
            mail = new Mail();

            Personalization personalization1 = new Personalization();

            personalization1.AddTo(new Email("*****@*****.**"));

            Personalization personalization2 = new Personalization();

            personalization2.AddBcc(new Email("*****@*****.**"));

            mail.AddPersonalization(personalization1);
            mail.AddPersonalization(personalization2);

            Assert.False(SendGridHelpers.IsToValid(mail));

            // valid
            personalization2.AddTo(new Email("*****@*****.**"));
            Assert.True(SendGridHelpers.IsToValid(mail));
        }
Exemple #17
0
        internal static void _sendSalesAlerts(string accountNameKey, string firstName = "", string lastName = "", string companyName = "", string phone = "", string email = "", string comments = "", string productName = "", string productId = "", string fullyQualifiedName = "", string locationPath = "", string origin = "", string ipAddress = "")
        {
            try
            {
                #region Get Account Settings

                var accountSettings = DataAccess.AccountSettings.GetAccountSettings(accountNameKey);

                #endregion

                if (accountSettings.SalesSettings.UseSalesAlerts && accountSettings.SalesSettings.AlertEmails.Length > 0)
                {
                    #region Generate Email Alert Message & Subject (Based on parameters)

                    StringBuilder subject = new StringBuilder();
                    StringBuilder body    = new StringBuilder();

                    subject.Append("New sales lead");

                    #region Names

                    if (firstName != "" && lastName != "")
                    {
                        //Subject
                        subject.Append(" from ");
                        subject.Append(firstName);
                        subject.Append(" ");
                        subject.Append(lastName);

                        //Body
                        body.Append("<b>From: </b>");
                        body.Append(firstName);
                        body.Append(" ");
                        body.Append(lastName);
                        body.Append("<br>");
                        body.Append("<br>");
                    }
                    else if (firstName != "")
                    {
                        //Subject
                        subject.Append(" from ");
                        subject.Append(firstName);

                        //Body
                        body.Append("<b>From: </b>");
                        body.Append(firstName);
                        body.Append("<br>");
                        body.Append("<br>");
                    }
                    else if (lastName != "")
                    {
                        //Subject
                        subject.Append(" from ");
                        subject.Append(lastName);

                        //Body
                        body.Append("<b>From: </b>");
                        body.Append(lastName);
                        body.Append("<br>");
                        body.Append("<br>");
                    }

                    #endregion

                    #region CompanyName

                    if (companyName != "")
                    {
                        //Body
                        body.Append("<b>Company: </b>");
                        body.Append(companyName);
                        body.Append("<br>");
                        body.Append("<br>");
                    }

                    #endregion


                    #region Product

                    if (productName != "")
                    {
                        //Subject
                        subject.Append(" for ");
                        subject.Append(productName);
                        body.Append("<br>");
                        body.Append("<br>");
                    }

                    if (productName != "" && fullyQualifiedName != "")
                    {
                        //Body
                        body.Append("<b>Product: </b>");
                        body.Append("<a href='http://");
                        body.Append(accountNameKey);
                        body.Append(".");
                        body.Append(CoreServices.PlatformSettings.Urls.AccountManagementDomain);
                        body.Append("/product/");
                        body.Append(fullyQualifiedName);
                        body.Append("'>");
                        body.Append(productName);
                        body.Append("</a>");
                        body.Append("<br>");
                        body.Append("<br>");
                    }
                    else if (productName != "")
                    {
                        //Body
                        body.Append("<b>Product: </b>");
                        body.Append(productName);
                        body.Append("<br>");
                        body.Append("<br>");
                    }

                    #endregion

                    #region Comments

                    else if (comments != "")
                    {
                        //Body
                        body.Append("<b>Comments: </b>");
                        body.Append(comments);
                        body.Append("<br>");
                        body.Append("<br>");
                    }

                    #endregion

                    #region Origin

                    else if (origin != "")
                    {
                        //Body
                        body.Append("<b>Origin: </b>");
                        body.Append(origin);
                        body.Append("<br>");
                        body.Append("<br>");
                    }

                    #endregion

                    #region IP

                    else if (ipAddress != "")
                    {
                        //Body
                        body.Append("<b>IP Address: </b>");
                        body.Append(ipAddress);
                        body.Append("<br>");
                        body.Append("<br>");
                    }

                    #endregion

                    #endregion

                    #region Send Email Alerts (v3 SendGrid API)

                    dynamic sg = new SendGridAPIClient(CoreServices.PlatformSettings.SendGrid.ApiKey);

                    Email from = new Email("*****@*****.**", "Sales Alert");

                    var personalization = new Personalization();
                    foreach (var emailAddress in accountSettings.SalesSettings.AlertEmails)
                    {
                        Email to = new Email(emailAddress);
                        personalization.AddTo(to);
                    }

                    //Mail mail = new Mail(from, subject, to, content);
                    Mail mail = new Mail();
                    mail.From            = from;
                    mail.Subject         = subject.ToString();
                    mail.Personalization = new List <Personalization>();
                    mail.Personalization.Add(personalization);

                    Content content = new Content("text/html", body.ToString());
                    mail.Contents = new List <Content>();
                    mail.Contents.Add(content);


                    // Send the email.
                    try
                    {
                        var requestBody = mail.Get();

                        //dynamic response = await sg.client.mail.send.post(requestBody: requestBody);
                        dynamic response = sg.client.mail.send.post(requestBody: requestBody);
                        //dynamic d = response;
                    }
                    catch (Exception e)
                    {
                        //Log the Exception ??
                    }

                    #endregion

                    #region Send Email Alert(s) [Legacy]

                    /*
                     *
                     * var myMessage = new SendGridMessage(); //.SendGrid.GetInstance();
                     *
                     *
                     * // Add the message properties.
                     * myMessage.From = new MailAddress("*****@*****.**", "Sales Alert");
                     * //myMessage.Header.AddTo(recipients);
                     * myMessage.AddTo(accountSettings.SalesSettings.AlertEmails);
                     * myMessage.Subject = subject.ToString();
                     * myMessage.Html = body.ToString();
                     *
                     *
                     * // Create network credentials to access your SendGrid account.
                     * var username = CoreServices.PlatformSettings.SendGrid.UserName;
                     * var pswd = CoreServices.PlatformSettings.SendGrid.ApiKey;
                     * var credentials = new NetworkCredential(username, pswd);
                     *
                     * // Create a Web transport for sending email.
                     * //var transportWeb = SendGridMail.Transport.Web.GetInstance(credentials);
                     * //var sendGridMailWeb = SendGridMail.Web.GetInstance(credentials);
                     * var transportWeb = new Web(credentials);
                     *
                     * // Send the email.
                     * try
                     * {
                     *  //transportWeb.Deliver(myMessage);
                     *  //sendGridMailWeb.Deliver(myMessage);
                     *  transportWeb.Deliver(myMessage);
                     * }
                     * catch
                     * {
                     *
                     * }
                     *
                     */
                    #endregion
                }
            }
            catch (Exception e)
            {
            }
        }
Exemple #18
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 #19
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);
        }
        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 #21
0
        public static async Task Envoyercourriel(Mentore mentore, string message, string apiKey)
        {
            dynamic sg = new SendGridAPIClient(apiKey);



            //Mon object de courriel
            var monCourriel     = new Mail();
            var mesInformations = new Personalization();

            //De:
            var contactEmail = new Email();

            ///contactEmail.Address = "*****@*****.**";
            contactEmail.Address = "*****@*****.**";
            contactEmail.Name    = "Inscription Mentorat";
            monCourriel.From     = contactEmail;

            ////À:
            //for (int i = 0; i <= monMail.LesDestinataires.Count - 1; i++)
            //{
            //    contactEmail = new Email();
            //    contactEmail.Address = monMail.LesDestinataires[i];
            //    mesInformations.AddTo(contactEmail);
            //}

            //À:

            ///      contactEmail = new Email();
            ///      contactEmail.Address = "*****@*****.**";
            ///      mesInformations.AddTo(contactEmail);
            ///
            ///      contactEmail = new Email();
            ///      contactEmail.Address = "*****@*****.**";
            ///      mesInformations.AddCc(contactEmail);

            contactEmail         = new Email();
            contactEmail.Address = "*****@*****.**";
            mesInformations.AddTo(contactEmail);


            //if (monMail.LesCC != null)
            //{
            //    for (int i = 0; i <= monMail.LesCC.Count - 1; i++)
            //    {
            //        contactEmail = new Email();
            //        contactEmail.Address = monMail.LesCC[i];
            //        mesInformations.AddCc(contactEmail);
            //    }
            //}

            //contactEmail = new Email();
            //contactEmail.Address = "*****@*****.**";
            //mesInformations.AddCc(contactEmail);


            //CC:


            ////CCI:
            //for (int i = 0; i <= monMail.LesCCI.Count - 1; i++)
            //{
            //    contactEmail = new Email();
            //    contactEmail.Address = monMail.LesCCI[i];
            //    mesInformations.AddBcc(contactEmail);
            //}


            //Objet
            //monCourriel.Subject = "Ha oui!";
            mesInformations.Subject = "Nouvelle inscription au service de mentorat";

            monCourriel.AddPersonalization(mesInformations);

            //Message
            string strMsg  = HttpUtility.HtmlDecode(message);
            var    content = new Content();

            content.Type  = "text/html";
            content.Value = strMsg;
            monCourriel.AddContent(content);

            //for (int i = 0; i <= lstLiensImg.Count - 1; i++)
            //{
            //    //je permet seulement les .png
            //    if (lstLiensImg[i].IndexOf(".png") > 0)
            //    {
            //        string headerPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/Signatures/" + lstLiensImg[i]);
            //        var attch = new Attachment();
            //        byte[] imageArray = System.IO.File.ReadAllBytes(headerPath);
            //        string strAttachement = Convert.ToBase64String(imageArray);

            //        attch.Content = strAttachement;
            //        attch.Type = "image/png";
            //        attch.ContentId = lstLiensImg[i].Replace(".png", "");
            //        attch.Filename = lstLiensImg[i];
            //        attch.Disposition = "inline";
            //        monCourriel.AddAttachment(attch);
            //    }
            //}

            //désactivé pour ne pas envoyer de courriel
            dynamic response = await sg.client.mail.send.post(requestBody : monCourriel.Get());
        }
        public static async Task Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
            HttpRequestMessage req,
            [Table("UserProfile")] CloudTable userProfileTable,
            [Queue("emaillogqueue")]  CloudQueue queue,
            [Blob("emailogblobcontainer/{rand-guid}.log")] TextWriter logEmailBlob,
            [SendGrid()] ICollector <Mail> message,
            TraceWriter log)
        {
            try
            {
                log.Info("LogEmailInBlob 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);

                userProfileTable.Execute(tblInsertOperation);

                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}!"
                };

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

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

                var queueMessage = await queue.GetMessageAsync();

                var data = queueMessage.AsString;

                await queue.DeleteMessageAsync(queueMessage);

                await logEmailBlob.WriteAsync(data);
            }
            catch (System.Exception ex)
            {
                log.Info($"LogEmailInBlob function : Exception:{ ex.Message}");
                throw;
            }
            finally
            {
                log.Info("LogEmailInBlob function has finished processing a request.");
            }
        }
        internal static void WritePlatformLog(CategoryType categoryType, ActivityType activityType, string description, string details = null, string accountId = null, string accountName = null, string userId = null, string userName = null, string userEmail = null, string ipAddress = null, string origin = null, string serializedObject = null)
        {
            CloudTableClient cloudTableClient = Settings.Azure.Storage.StorageConnections.PlatformStorage.CreateCloudTableClient();

            //Create and set retry policy for logging
            //IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 4);
            IRetryPolicy linearRetryPolicy = new LinearRetry(TimeSpan.FromSeconds(1), 4);

            cloudTableClient.DefaultRequestOptions.RetryPolicy = linearRetryPolicy;

            //Gather up all the entities into a list for our parallel task to execute in a ForEach
            List <Object> entityTypes = new List <object>();


            //Create an instance of each entity type and pass in associated CloudTableClient & TableName
            PlatformLogTableEntity_ByTime logTableEntity_Time = new PlatformLogTableEntity_ByTime(cloudTableClient, "platformactivitylogbytime");

            entityTypes.Add(logTableEntity_Time);

            PlatformLogTableEntity_ByCategory logTableEntity_Category = new PlatformLogTableEntity_ByCategory(cloudTableClient, "platformactivitylogbycategory");

            entityTypes.Add(logTableEntity_Category);

            PlatformLogTableEntity_ByActivity logTableEntity_Activity = new PlatformLogTableEntity_ByActivity(cloudTableClient, "platformactivitylogbyactivity");

            entityTypes.Add(logTableEntity_Activity);

            if (accountId != null)
            {
                PlatformLogTableEntity_ByAccountID logTableEntity_AccountID = new PlatformLogTableEntity_ByAccountID(cloudTableClient, "platformactivitylogbyaccountid");
                entityTypes.Add(logTableEntity_AccountID);
            }

            if (userId != null)
            {
                PlatformLogTableEntity_ByUserID logTableEntity_UserID = new PlatformLogTableEntity_ByUserID(cloudTableClient, "platformactivitylogbyuserid");
                entityTypes.Add(logTableEntity_UserID);
            }



            try
            {
                Parallel.ForEach(entityTypes, obj =>
                {
                    #region Trace Statements

                    //Display the id of the thread for each parallel instance to verifiy prallelism
                    //Trace.TraceInformation("Current thread ID: " + Thread.CurrentThread.ManagedThreadId);

                    #endregion

                    //Transform the LogItem into each corresponding table entity type for insert execution into logs
                    (obj as IPlatformLogTableEntity).Category    = categoryType.ToString();
                    (obj as IPlatformLogTableEntity).Activity    = activityType.ToString();
                    (obj as IPlatformLogTableEntity).Description = description.ToString();
                    (obj as IPlatformLogTableEntity).Details     = details;

                    (obj as IPlatformLogTableEntity).UserID    = userId;
                    (obj as IPlatformLogTableEntity).UserName  = userName;
                    (obj as IPlatformLogTableEntity).UserEmail = userEmail;

                    (obj as IPlatformLogTableEntity).IPAddress = ipAddress;
                    (obj as IPlatformLogTableEntity).Origin    = origin;

                    (obj as IPlatformLogTableEntity).AccountID   = accountId;
                    (obj as IPlatformLogTableEntity).AccountName = accountName;

                    (obj as IPlatformLogTableEntity).Object = serializedObject;


                    //create an insert operation for each entity, assign to designated CloudTable, and add to our list of tasks:
                    TableOperation operation = TableOperation.Insert((obj as TableEntity));
                    (obj as IPlatformLogTableEntity).cloudTable.Execute(operation);
                });
            }
            catch (Exception e)
            {
                //Email platform admins about this exception
                #region Email Platform Admins About Exception

                try
                {
                    /*
                     *
                     * Using SendGrid Library is not possible in this one case due to circular reference issues
                     *
                     */

                    #region Create Parameter String

                    var parametersString = new StringBuilder();

                    parametersString.Append("(");

                    try
                    {
                        parametersString.Append(categoryType.ToString());
                        parametersString.Append(", ");

                        parametersString.Append(activityType.ToString());
                        parametersString.Append(", ");

                        parametersString.Append(description);
                        parametersString.Append(", ");

                        if (!String.IsNullOrEmpty(details))
                        {
                            parametersString.Append(details);
                            parametersString.Append(", ");
                        }
                        else
                        {
                            parametersString.Append("null");
                            parametersString.Append(", ");
                        }

                        if (!String.IsNullOrEmpty(accountId))
                        {
                            parametersString.Append(accountId);
                            parametersString.Append(", ");
                        }
                        else
                        {
                            parametersString.Append("null");
                            parametersString.Append(", ");
                        }

                        if (!String.IsNullOrEmpty(accountName))
                        {
                            parametersString.Append(accountName);
                            parametersString.Append(", ");
                        }
                        else
                        {
                            parametersString.Append("null");
                            parametersString.Append(", ");
                        }


                        if (!String.IsNullOrEmpty(userId))
                        {
                            parametersString.Append(userId);
                            parametersString.Append(", ");
                        }
                        else
                        {
                            parametersString.Append("null");
                            parametersString.Append(", ");
                        }

                        if (!String.IsNullOrEmpty(userName))
                        {
                            parametersString.Append(userName);
                            parametersString.Append(", ");
                        }
                        else
                        {
                            parametersString.Append("null");
                            parametersString.Append(", ");
                        }


                        if (!String.IsNullOrEmpty(userEmail))
                        {
                            parametersString.Append(userEmail);
                            parametersString.Append(", ");
                        }
                        else
                        {
                            parametersString.Append("null");
                            parametersString.Append(", ");
                        }

                        if (!String.IsNullOrEmpty(ipAddress))
                        {
                            parametersString.Append(ipAddress);
                            parametersString.Append(", ");
                        }
                        else
                        {
                            parametersString.Append("null");
                            parametersString.Append(", ");
                        }

                        if (!String.IsNullOrEmpty(origin))
                        {
                            parametersString.Append(origin);
                            parametersString.Append(", ");
                        }
                        else
                        {
                            parametersString.Append("null");
                            parametersString.Append(", ");
                        }
                        if (!String.IsNullOrEmpty(serializedObject))
                        {
                            parametersString.Append(serializedObject);
                            //parametersString.Append(", ");
                        }
                        else
                        {
                            parametersString.Append("null");
                            //parametersString.Append(", ");
                        }

                        parametersString.Append(")");
                    }
                    catch
                    {
                        parametersString.Append(" ...Error parsing next parameter -----> )");
                    }


                    #endregion

                    dynamic sg = new SendGridAPIClient(Settings.Services.SendGrid.Account.APIKey);

                    Email  from    = new Email(Settings.Endpoints.Emails.FromExceptions, "Platform Exception");
                    string subject = "Exception Alert! (From: Platform Logger)";

                    var personalization = new Personalization();
                    foreach (var email in Settings.Endpoints.Emails.PlatformEmailAddresses)
                    {
                        Email to = new Email(email);
                        personalization.AddTo(to);
                    }

                    //Mail mail = new Mail(from, subject, to, content);
                    Mail mail = new Mail();
                    mail.From            = from;
                    mail.Subject         = subject;
                    mail.Personalization = new List <Personalization>();
                    mail.Personalization.Add(personalization);



                    //var myMessage = new SendGridMessage();

                    //myMessage.From = new MailAddress(Settings.Endpoints.Emails.FromExceptions, "Platform Exception");
                    //myMessage.AddTo(Settings.Endpoints.Emails.PlatformEmailAddresses);
                    //myMessage.Subject = "Exception Alert! (From: Platform Logger)";

                    //myMessage.Html =

                    var body =
                        "Exception location: <b>" + System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "</b>" +
                        "<br/><br/>" +
                        "Exception occurred while attempting to write to the platform log..." +
                        "<br/><br/><b>" +
                        e.Message +
                        "</b><br/><br/>" +
                        "Log Parameters:<br/><br/><b>" +
                        parametersString.ToString() +
                        "</b><br/><br/>" +
                        JsonConvert.SerializeObject(e) +
                        "<br/><br/>";

                    Content content = new Content("text/html", body);

                    //var username = Settings.Services.SendGrid.Account.UserName;
                    //var pswd = Settings.Services.SendGrid.Account.APIKey;
                    //var credentials = new NetworkCredential(username, pswd);

                    //var transportWeb = new Web(credentials);
                    //transportWeb.Deliver(myMessage);

                    mail.Contents = new List <Content>();
                    mail.Contents.Add(content);

                    var requestBody = mail.Get();

                    //dynamic response = await sg.client.mail.send.post(requestBody: requestBody);
                    dynamic response = sg.client.mail.send.post(requestBody: requestBody);
                    //dynamic d = response;
                }
                catch
                {
                }



                #endregion
            }
        }
        public static void Send(List <string> recipients, string fromEmail, string fromName, string subject, string body, bool isHtml, bool isImportant = false)
        {
            dynamic sg = new SendGridAPIClient(Settings.Services.SendGrid.Account.APIKey);

            Email from = new Email(fromEmail, fromName);

            var personalization = new Personalization();

            foreach (var email in recipients)
            {
                if (email.ToLower() == "platformadmin@[Config_PlatformEmail]")
                {
                    //on recipients with LISTS we always BCC platformAdmin in order to keep that email hidden from the account users
                    Email bcc = new Email(email);
                    personalization.Bccs = new List <Email>();
                    personalization.Bccs.Add(bcc);
                }
                else
                {
                    Email to = new Email(email);
                    personalization.AddTo(to);
                }
            }


            //Mail mail = new Mail(from, subject, to, content);
            Mail mail = new Mail();

            mail.From            = from;
            mail.Subject         = subject;
            mail.Personalization = new List <Personalization>();
            mail.Personalization.Add(personalization);

            if (isHtml)
            {
                Content content = new Content("text/html", body);
                mail.Contents = new List <Content>();
                mail.Contents.Add(content);
            }
            else
            {
                Content content = new Content("text/plain", body);
                mail.Contents = new List <Content>();
                mail.Contents.Add(content);
            }



            // Send the email.
            try
            {
                if (Settings.Services.SendGrid.Account.Active) //<-- We check to see if email service is inactive due to load testing to avoid extra service charges
                {
                    var requestBody = mail.Get();

                    //dynamic response = await sg.client.mail.send.post(requestBody: requestBody);
                    dynamic response = sg.client.mail.send.post(requestBody: requestBody);
                    //dynamic d = response;
                }
            }
            catch (Exception e)
            {
                //Log the Exception
                PlatformLogManager.LogActivity(
                    CategoryType.Error,
                    ActivityType.Error_SendGrid,
                    e.Message,
                    "An error occured when attempting to use SendGrid"
                    );

                //Log the Exception
                PlatformLogManager.LogActivity(
                    CategoryType.Error,
                    ActivityType.Error_Exception,
                    e.Message,
                    "An exception occured when attempting to use SendGrid",
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name,
                    JsonConvert.SerializeObject(e)
                    );
            }
        }
Exemple #25
0
        public async Task <bool> SendAsync(EmailMessage email, bool deleteAttachmentes, params string[] attachments)
        {
            var config = this.Config as Config;

            if (config == null)
            {
                email.Status = Status.Cancelled;
                return(false);
            }

            try
            {
                email.Status = Status.Executing;

                var personalization = new Personalization
                {
                    Subject = email.Subject
                };


                var message = new Mail
                {
                    From    = new Email(email.FromEmail, email.FromName),
                    Subject = email.Subject
                };

                if (!string.IsNullOrWhiteSpace(email.ReplyToEmail))
                {
                    message.ReplyTo = new Email(email.ReplyToEmail, email.ReplyToName);
                }


                foreach (var address in email.SentTo.Split(','))
                {
                    personalization.AddTo(new Email(address.Trim()));
                }


                message.AddPersonalization(personalization);

                var content = new Content();
                content.Value = email.Message;

                if (email.IsBodyHtml)
                {
                    content.Type = "text/html";
                }
                else
                {
                    content.Type = "text/plain";
                }

                message.AddContent(content);

                message = AttachmentHelper.AddAttachments(message, attachments);

                var     sg       = new SendGridAPIClient(config.ApiKey, "https://api.sendgrid.com");
                dynamic response = await sg.client.mail.send.post(requestBody : message.Get());

                System.Net.HttpStatusCode status = response.StatusCode;

                switch (status)
                {
                case System.Net.HttpStatusCode.OK:
                case System.Net.HttpStatusCode.Created:
                case System.Net.HttpStatusCode.Accepted:
                case System.Net.HttpStatusCode.NoContent:
                    email.Status = Status.Completed;
                    break;

                default:
                    email.Status = Status.Failed;
                    break;
                }

                return(true);
            }
            // ReSharper disable once CatchAllClause
            catch (Exception ex)
            {
                email.Status = Status.Failed;
                Log.Warning(@"Could not send email to {To} using SendGrid API. {Ex}. ", email.SentTo, ex);
            }
            finally
            {
                if (deleteAttachmentes)
                {
                    FileHelper.DeleteFiles(attachments);
                }
            }

            return(false);
        }