public static bool SendCurrentIncidentInvoiceEmail(Incident incident, ApiServices Services)
        {
            IncidentInfo invoiceIncident = new IncidentInfo(incident);

            if (invoiceIncident.PaymentAmount < invoiceIncident.ServiceFee)
            {

                SendGridMessage invoiceMessage = new SendGridMessage();

                invoiceMessage.From = SendGridHelper.GetAppFrom();
                invoiceMessage.AddTo(invoiceIncident.IncidentUserInfo.Email);
                invoiceMessage.Html = " ";
                invoiceMessage.Text = " ";
                invoiceMessage.Subject = "StrandD Invoice - Payment for Service Due";

                invoiceMessage.EnableTemplateEngine(WebConfigurationManager.AppSettings["RZ_InvoiceTemplateID"]);
                invoiceMessage.AddSubstitution("%invoicestub%", new List<string> { invoiceIncident.IncidentGUID.Substring(0, 5).ToUpper() });
                invoiceMessage.AddSubstitution("%incidentguid%", new List<string> { invoiceIncident.IncidentGUID });
                invoiceMessage.AddSubstitution("%name%", new List<string> { invoiceIncident.IncidentUserInfo.Name });
                invoiceMessage.AddSubstitution("%phone%", new List<string> { invoiceIncident.IncidentUserInfo.Phone });
                invoiceMessage.AddSubstitution("%email%", new List<string> { invoiceIncident.IncidentUserInfo.Email });
                invoiceMessage.AddSubstitution("%jobdescription%", new List<string> { invoiceIncident.JobCode });
                invoiceMessage.AddSubstitution("%servicefee%", new List<string> { (invoiceIncident.ServiceFee - invoiceIncident.PaymentAmount).ToString() });
                invoiceMessage.AddSubstitution("%datesubmitted%", new List<string> { DateTime.Now.ToShortDateString() });
                invoiceMessage.AddSubstitution("%datedue%", new List<string> { (DateTime.Now.AddDays(30)).ToShortTimeString() });
                invoiceMessage.AddSubstitution("%servicepaymentlink%", new List<string> { (WebConfigurationManager.AppSettings["RZ_ServiceBaseURL"].ToString() + "/view/customer/incidentpayment/" + invoiceIncident.IncidentGUID) });

                // Create an Web transport for sending email.
                var transportWeb = new Web(SendGridHelper.GetNetCreds());

                // Send the email.
                try
                {
                    transportWeb.Deliver(invoiceMessage);
                    Services.Log.Info("Incident Invoice Email Sent to [" + invoiceIncident.IncidentUserInfo.Email + "]");
                    return true;
                }
                catch (InvalidApiRequestException ex)
                {
                    for (int i = 0; i < ex.Errors.Length; i++)
                    {
                        Services.Log.Error(ex.Errors[i]);
                        return false;
                    }
                }
                return false;

            }
            else
            {
                return false;
            }
        }
Beispiel #2
0
        private static SendGridMessage BuildEmail(string name, string email, string link, string otherName)
        {
            var msg = new SendGridMessage();
            msg.EnableTemplateEngine("5f7c4376-3b0c-4972-9049-ee13ef5b59af");
            msg.DisableClickTracking();
            msg.From = new MailAddress("*****@*****.**", "OkBoba 邮件");
            msg.To = new MailAddress[] { new MailAddress(email, name) };
            msg.Subject = string.Format(i18n.Messaging_Notification_Subject, otherName);
            msg.Html = string.Format(i18n.Messaging_Notification_Body, otherName);

            msg.AddSubstitution("-link-", new List<string>() { link });

            return msg;
        }
        public async Task SendEmailMessageAsync(string toAddress, string fromAddress, string fromName, string subject, 
            string template,
            EmailSendSuccessDelegate onSuccess,
            IDictionary<string, List<string>> substitutions,
            Action<string, IDictionary<string, string>> logIssue)
        {
            var myMessage = new SendGridMessage();
            myMessage.AddTo(toAddress);
            myMessage.From = new MailAddress(fromAddress, fromName);
            myMessage.Subject = subject;
            myMessage.EnableTemplateEngine(template);
            

            if (default(IDictionary<string, List<string>>) != substitutions)
            {
                foreach (var substitutionsKvp in substitutions)
                    myMessage.AddSubstitution(substitutionsKvp.Key, substitutionsKvp.Value);
            }

            // Create credentials, specifying your user name and password.
            var credentials = new NetworkCredential(username, password);

            // Create an Web transport for sending email.
            var transportWeb = new global::SendGrid.Web(credentials);

            // Send the email, which returns an awaitable task.
            try
            {
                await transportWeb.DeliverAsync(myMessage);
            }
            catch (InvalidApiRequestException ex)
            {
                var details = new StringBuilder();

                details.Append("ResponseStatusCode: " + ex.ResponseStatusCode + ".   ");
                for (int i = 0; i < ex.Errors.Count(); i++)
                {
                    details.Append(" -- Error #" + i.ToString() + " : " + ex.Errors[i]);
                }

                throw new ApplicationException(details.ToString(), ex);
            }
            onSuccess.Invoke(toAddress);
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            Dictionary <string, string> users = new Dictionary <string, string>();

            users.Add("*****@*****.**", "Vadym Ivashyn");
            users.Add("*****@*****.**", "Second Vadym");


            var myMessage = new SendGrid.SendGridMessage();

            myMessage.From = new MailAddress("*****@*****.**", "Title");

            foreach (var u in users)
            {
                myMessage.AddTo(u.Key);
            }

            List <string> userNames = users.Values.ToList();

            myMessage.AddSubstitution("%user%", userNames);
            myMessage.AddSubstitution("%title%", new List <string> {
                "Hello from title"
            });
            myMessage.AddSubstitution("%body%", new List <string> {
                "Some text from body"
            });

            myMessage.EnableTemplateEngine("57ece6c2-b625-4bd6-92e7-2def1a3b0693");



            myMessage.Html = "Email content here";

            myMessage.Subject = "Email subject here";


            NetworkCredential nc = new NetworkCredential("*****@*****.**", "KPgZDZiM7c8hXHz");
            var transportWeb     = new SendGrid.Web(nc);

            transportWeb.DeliverAsync(myMessage).Wait();
            Console.WriteLine("Good");
            Console.ReadLine();
        }
        public static void SendIncidentPaymentReceiptEmail(Payment payment, ApiServices Services)
        {
            SendGridMessage receiptMessage = new SendGridMessage();
            IncidentInfo receiptIncident = new IncidentInfo(payment.IncidentGUID);

            receiptMessage.From = SendGridHelper.GetAppFrom();
            receiptMessage.AddTo(receiptIncident.IncidentUserInfo.Email);
            receiptMessage.Html = " ";
            receiptMessage.Text = " ";
            receiptMessage.Subject = " ";

            receiptMessage.EnableTemplateEngine(WebConfigurationManager.AppSettings["RZ_ReceiptTemplateID"]);
            receiptMessage.AddSubstitution("%invoicestub%", new List<string> { receiptIncident.IncidentGUID.Substring(0, 5).ToUpper() });
            receiptMessage.AddSubstitution("%name%", new List<string> { receiptIncident.IncidentUserInfo.Name });
            receiptMessage.AddSubstitution("%jobdescription%", new List<string> { receiptIncident.JobCode });
            receiptMessage.AddSubstitution("%servicefee%", new List<string> { receiptIncident.ServiceFee.ToString() });
            receiptMessage.AddSubstitution("%datesubmitted%", new List<string> { DateTime.Now.ToShortDateString() });
            receiptMessage.AddSubstitution("%paymentmethod%", new List<string> { receiptIncident.PaymentMethod });
            receiptMessage.AddSubstitution("%paymentamount%", new List<string> { receiptIncident.PaymentAmount.ToString() });

            // Create an Web transport for sending email.
            var transportWeb = new Web(SendGridHelper.GetNetCreds());

            // Send the email.
            try
            {
                transportWeb.Deliver(receiptMessage);
                Services.Log.Info("Payment Receipt Email Sent to [" + receiptIncident.IncidentUserInfo.Email + "]");
            }
            catch (InvalidApiRequestException ex)
            {
                for (int i = 0; i < ex.Errors.Length; i++)
                {
                    Services.Log.Error(ex.Errors[i]);
                }
            }
        }
        public static void SendIncidentSubmissionAdminEmail(Incident incident, ApiServices Services)
        {
            SendGridMessage submissionMessage = new SendGridMessage();
            IncidentInfo submisionIncident = new IncidentInfo(incident);

            submissionMessage.From = SendGridHelper.GetAppFrom();
            submissionMessage.AddTo(WebConfigurationManager.AppSettings["RZ_SysAdminEmail"]);
            submissionMessage.Html = " ";
            submissionMessage.Text = " ";
            submissionMessage.Subject = " [" + WebConfigurationManager.AppSettings["MS_MobileServiceName"] + "]";

            submissionMessage.EnableTemplateEngine(WebConfigurationManager.AppSettings["RZ_SubmisionTemplateID"]);
            submissionMessage.AddSubstitution("%timestamp%", new List<string> { submisionIncident.CreatedAt.ToString() });
            submissionMessage.AddSubstitution("%incidentguid%", new List<string> { submisionIncident.IncidentGUID });
            submissionMessage.AddSubstitution("%vehicledetails%", new List<string> { submisionIncident.IncidentVehicleInfo.RegistrationNumber });
            submissionMessage.AddSubstitution("%name%", new List<string> { submisionIncident.IncidentUserInfo.Name });
            submissionMessage.AddSubstitution("%phone%", new List<string> { submisionIncident.IncidentUserInfo.Phone });
            submissionMessage.AddSubstitution("%email%", new List<string> { submisionIncident.IncidentUserInfo.Email });
            submissionMessage.AddSubstitution("%jobdescription%", new List<string> { submisionIncident.JobCode });
            submissionMessage.AddSubstitution("%location%", new List<string> { submisionIncident.LocationObj.RGDisplay });

            // Create an Web transport for sending email.
            var transportWeb = new Web(SendGridHelper.GetNetCreds());

            // Send the email.
            try
            {
                transportWeb.Deliver(submissionMessage);
                Services.Log.Info("New Incident Submission Email Sent to [" + submisionIncident.IncidentUserInfo.Email + "]");
            }
            catch (InvalidApiRequestException ex)
            {
                for (int i = 0; i < ex.Errors.Length; i++)
                {
                    Services.Log.Error(ex.Errors[i]);
                }
            }
        }
Beispiel #7
0
        //Note that at the moment, we actually are submitting through SendGrid, not Gmail.
        public async void Send(EnvelopeDO envelope)
        {
            if (envelope == null)
                throw new ArgumentNullException("envelope");
            if (!string.Equals(envelope.Handler, EnvelopeDO.SendGridHander, StringComparison.OrdinalIgnoreCase))
                throw new ArgumentException(@"This envelope should not be handled with Gmail.", "envelope");
            if (envelope.Email == null)
                throw new ArgumentException(@"This envelope has no Email.", "envelope");
            if (envelope.Email.Recipients.Count == 0)
                throw new ArgumentException(@"This envelope has no recipients.", "envelope");
            
            var email = envelope.Email;
            if (email == null)
                throw new ArgumentException(@"Envelope email is null", "envelope");

            try
            {
                var fromName = !String.IsNullOrWhiteSpace(email.FromName) ? email.FromName : email.From.Name;

                var mailMessage = new SendGridMessage { From = new MailAddress(email.From.Address, fromName) };

                if (!String.IsNullOrWhiteSpace(email.ReplyToAddress))
                {
                    mailMessage.ReplyTo = new[] { new MailAddress(email.ReplyToAddress, email.ReplyToName) };
                }

                mailMessage.To = email.To.Select(toEmail => new MailAddress(toEmail.Address, toEmail.NameOrAddress())).ToArray();
                mailMessage.Bcc = email.BCC.Select(bcc => new MailAddress(bcc.Address, bcc.NameOrAddress())).ToArray();
                mailMessage.Cc = email.CC.Select(cc => new MailAddress(cc.Address, cc.NameOrAddress())).ToArray();

                mailMessage.Subject = email.Subject;

                if ((email.PlainText == null || email.HTMLText == null) && string.IsNullOrEmpty(envelope.TemplateName))
                {
                    throw new ArgumentException("Trying to send an email that doesn't have both an HTML and plain text body");
                }

                if (email.PlainText == null || email.HTMLText == null)
                {
                    mailMessage.Html = "<html></html>";
                    mailMessage.Text = "";
                }
                else
                {
                    mailMessage.Html = email.HTMLText;
                    mailMessage.Text = email.PlainText;
                }

                var headers = new Dictionary<String, String>();
                if (!String.IsNullOrEmpty(email.MessageID))
                    headers.Add("Message-ID", email.MessageID);
                if (!String.IsNullOrEmpty(email.References))
                    headers.Add("References", email.References);

                if (headers.Any())
                    mailMessage.AddHeaders(headers);

                foreach (var attachment in email.Attachments)
                {
                    mailMessage.AddAttachment(attachment.GetData(), attachment.OriginalName);
                }

                if (!string.IsNullOrEmpty(envelope.TemplateName))
                {
                    mailMessage.EnableTemplateEngine(envelope.TemplateName);//Now TemplateName will be TemplateId on Sendgrid.
                    if (envelope.MergeData != null)
                    {
                        //Now, we need to do some magic.
                        //Basically - we need the length of each substitution to match the length of recipients
                        //In our case, most of the time, all the substitutions are the same, except for token-related fields
                        //To make it easier to use, we attempt to pad out the substition arrays if they lengths don't match
                        //We only do that if we're given a string value. In any other case, we allow sengrid to fail.
                        var subs = new Dictionary<String, List<String>>();
                        foreach (var pair in envelope.MergeData)
                        {

                            var arrayType = pair.Value as JArray;
                            List<String> listVal;
                            if (arrayType != null)
                            {
                                listVal = arrayType.Select(a => a.ToString()).ToList();
                            }
                            else
                            {
                                listVal = new List<string>();
                                for (var i = 0; i < email.Recipients.Count(); i++) //Pad out the substitution
                                    listVal.Add(pair.Value == null ? String.Empty : pair.Value.ToString());
                            }
                            subs.Add(pair.Key, listVal);
                            
                        }
                        foreach(var sub in subs)
                            mailMessage.AddSubstitution(sub.Key, sub.Value);
                    }
                }

                try
                {
                    await _transport.DeliverAsync(mailMessage);

                    OnEmailSent(email.Id);
                }
                catch (Exception ex)
                {
                    OnEmailRejected(ex.Message, email.Id);
                }
            }
            catch (Exception ex)
            {
                OnEmailCriticalError(-1, "Unhandled exception.", ex.Message, email.Id);
            }
        }
Beispiel #8
0
        private SendGridMessage CreateDefaultMessage(string templateId)
        {
            var message = new SendGridMessage
            {
                From = new MailAddress(_globalSettings.Mail.ReplyToEmail, _globalSettings.SiteName),
                Html = " ",
                Text = " "
            };

            if(!string.IsNullOrWhiteSpace(templateId))
            {
                message.EnableTemplateEngine(templateId);
            }

            message.AddSubstitution("{{siteName}}", new List<string> { _globalSettings.SiteName });
            message.AddSubstitution("{{baseVaultUri}}", new List<string> { _globalSettings.BaseVaultUri });

            return message;
        }