Ejemplo n.º 1
0
        /// <summary>
        /// Send an email
        /// </summary>
        /// <param name="request">Contains detailed email info and optionally provider info (such as ApiKeys)</param>
        /// <param name="messageId">The message id returned by the service provider</param>
        /// <param name="detailMessage">The message returned by the service provider, e.g. "failed to send message", "Sent", "Message Queued for delivery"</param>
        /// <returns>True if email was sent successfully</returns>
        public override bool SendMail(SendMailRequest request, out string messageId, out string detailMessage)
        {
            // Create the email object
            var msg = new SendGridMessage();

            // email detail
            msg.Subject = request.Subject;
            msg.From    = new MailAddress(request.From);
            msg.AddTo(request.To);
            msg.Text = request.Text;

            // send email
            string apiKey = GetApiKey(request);

            var transportWeb = new Web(apiKey);
            var t            = transportWeb.DeliverAsync(msg);

            t.Wait();

            // process response
            // send grid does not provide any of the information, so set them to be empty
            messageId     = "";
            detailMessage = "";
            return(true);
        }
        /// <summary>
        /// Given a SendMailRequest, return a list of MailServiceProvidersSuitable to process this request
        /// If use has provided an API key in the request, the related provider will be put at the begining of the list
        /// if user did not provided an API key in the request, the provider is put at the end
        /// If no API key is found, the provider won't be used
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static List <MailServiceProvider> GetOrderedMailServiceProviders(SendMailRequest request)
        {
            List <MailServiceProvider> providerList = new List <MailServiceProvider>();

            // Add providers user has specified and provided an API key for
            foreach (ProviderInfo p in request.Providers)
            {
                if (!String.IsNullOrWhiteSpace(p.ApiKey))
                {
                    providerList.Add(MailServiceProvider.GetProvider(p.ProviderType));
                }
            }

            // Add the rest of providers that have an API key in configuration file
            foreach (ProviderType pt in allProviderTypes)
            {
                if (!providerList.Exists(p => p.ProviderType == pt))
                {
                    MailServiceProvider p = MailServiceProvider.GetProvider(pt);
                    string apiKey         = p.GetApiKey(request);
                    if (!String.IsNullOrWhiteSpace(apiKey))
                    {
                        providerList.Add(p);
                    }
                }
            }

            return(providerList);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Get the API key for calling the provider
        /// Will try to get the key from SendMailRequest if it's available; or else it will try to get it from AppConfig file
        /// </summary>
        /// <param name="request">The request which might contain the API Key</param>
        /// <returns>The API Key, or null if not found.</returns>
        public string GetApiKey(SendMailRequest request)
        {
            string apiKey;

            ProviderInfo pi = request.Providers.SingleOrDefault(p => p.ProviderType == ProviderType);

            if (pi != null && !String.IsNullOrWhiteSpace(pi.ApiKey))    // ApiKey is provided in the request
            {
                apiKey = pi.ApiKey;
            }
            else    // ApiKey is not provided in the request, try get it from configuration file
            {
                switch (ProviderType)
                {
                case ProviderType.SendGrid:
                    apiKey = ConfigurationManager.AppSettings["SendGridApiKey"];
                    break;

                case ProviderType.MailGun:
                    apiKey = ConfigurationManager.AppSettings["MailGunApiKey"];
                    break;

                case ProviderType.Mandrill:
                    apiKey = ConfigurationManager.AppSettings["MandrillApiKey"];
                    break;

                default:
                    apiKey = null;
                    break;
                }
            }

            return(apiKey);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Send an email
        /// </summary>
        /// <param name="request">Contains detailed email info and optionally provider info (such as ApiKeys)</param>
        /// <param name="messageId">The message id returned by the service provider</param>
        /// <param name="detailMessage">The message returned by the service provider, e.g. "failed to send message", "Sent", "Message Queued for delivery"</param>
        /// <returns>True if email was sent successfully</returns>
        public override bool SendMail(SendMailRequest request, out string messageId, out string detailMessage)
        {
            // Create request
            string      apiKey = GetApiKey(request);
            MandrillApi api    = new MandrillApi(apiKey);

            // Email details
            EmailMessage msg = new EmailMessage();

            msg.FromEmail = request.From;
            msg.To        = request.To.Select(e => new EmailAddress(e));
            msg.Text      = request.Text;

            // Send email
            SendMessageRequest         smReq = new SendMessageRequest(msg);
            Task <List <EmailResult> > task  = api.SendMessage(smReq);

            task.Wait();

            // process response
            messageId     = "";
            detailMessage = "";

            EmailResult er = null;

            if (task.Result != null && task.Result.Count > 0)
            {
                er = task.Result[0];
            }

            if (er == null)
            {
                detailMessage = "Invalid return result from provider.";
                return(false);
            }

            messageId     = er.Id;
            detailMessage = er.Status.ToString();

            if (er.Status == EmailResultStatus.Queued ||
                er.Status == EmailResultStatus.Scheduled ||
                er.Status == EmailResultStatus.Sent)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 5
0
 public SendMailResult SendMail(SendMailRequest request)
 {
     try
     {
         return(SendMailRequestProcessor.ProcessSendMailRequest(request));
     }
     catch (Exception e)
     {
         SendMailResult result = new SendMailResult();
         result.Status = SendMailResultStatus.Error.ToString();
         result.Messages.Add(e.Message);
         return(result);
     }
 }
 public SendMailResult SendMail(SendMailRequest request)
 {
     try
     {
         return SendMailRequestProcessor.ProcessSendMailRequest(request);
     }
     catch (Exception e)
     {
         SendMailResult result = new SendMailResult();
         result.Status = SendMailResultStatus.Error.ToString();
         result.Messages.Add(e.Message);
         return result;
     }
 }
        /// <summary>
        /// Send an email
        /// </summary>
        /// <param name="request">Contains detailed email info and optionally provider info (such as ApiKeys)</param>
        /// <param name="messageId">The message id returned by the service provider</param>
        /// <param name="detailMessage">The message returned by the service provider, e.g. "failed to send message", "Sent", "Message Queued for delivery"</param>
        /// <returns>True if email was sent successfully</returns>
        public override bool SendMail(SendMailRequest request, out string messageId, out string detailMessage)
        {
            // Create request
            string apiKey = GetApiKey(request);
            MandrillApi api = new MandrillApi(apiKey);

            // Email details
            EmailMessage msg = new EmailMessage();
            msg.FromEmail = request.From;
            msg.To = request.To.Select(e=>new EmailAddress(e));
            msg.Text = request.Text;

            // Send email
            SendMessageRequest smReq = new SendMessageRequest(msg);
            Task<List<EmailResult>> task = api.SendMessage(smReq);
            task.Wait();

            // process response
            messageId = "";
            detailMessage = "";

            EmailResult er = null;
            if (task.Result != null && task.Result.Count >0)
            {
                er = task.Result[0];
            }

            if (er == null)
            {
                detailMessage = "Invalid return result from provider.";
                return false;
            }

            messageId = er.Id;
            detailMessage = er.Status.ToString();

            if (er.Status == EmailResultStatus.Queued
                || er.Status == EmailResultStatus.Scheduled
                || er.Status == EmailResultStatus.Sent)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public void TestLiveSiteSendThroughSendGrid()
        {
            //======================================================
            // Note: set these values before your test
            // =====================================================
            string url = ConfigurationManager.AppSettings["LiveSiteUrl"] + "/SendMail";
            string apiKey = ConfigurationManager.AppSettings["SendGridApiKey"];

            SendMailRequest request = new SendMailRequest()
            {
                From = "*****@*****.**",
                To = new List<string>() { "*****@*****.**" },
                Subject = "Test Subject",
                Text = "My test text.",
                Providers = new List<ProviderInfo>(){
                    new ProviderInfo(){ ProviderType = ProviderType.SendGrid, ApiKey=apiKey}
                }
            };

            MemoryStream stream1 = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(SendMailRequest));
            ser.WriteObject(stream1, request);
            stream1.Position = 0;
            StreamReader sr = new StreamReader(stream1);
            string jsonReqStr = sr.ReadToEnd();
            var content = new StringContent(jsonReqStr, Encoding.UTF8, "application/json");

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var task = client.PostAsync(url, content);
                task.Wait();

                var readStrTask = task.Result.Content.ReadAsStringAsync();
                readStrTask.Wait();

                string response = readStrTask.Result;

                Console.WriteLine(response);
            }
        }
        /// <summary>
        /// Send an email
        /// </summary>
        /// <param name="request">Contains detailed email info and optionally provider info (such as ApiKeys)</param>
        /// <param name="messageId">The message id returned by the service provider</param>
        /// <param name="detailMessage">The message returned by the service provider, e.g. "failed to send message", "Sent", "Message Queued for delivery"</param>
        /// <returns>True if email was sent successfully</returns>
        public override bool SendMail(SendMailRequest request, out string messageId, out string detailMessage)
        {
            // Create the email object
            var msg = new SendGridMessage();

            // email detail
            msg.Subject = request.Subject;
            msg.From = new MailAddress(request.From);
            msg.AddTo(request.To);
            msg.Text = request.Text;

            // send email
            string apiKey = GetApiKey(request);

            var transportWeb = new Web(apiKey);
            var t = transportWeb.DeliverAsync(msg);
            t.Wait();

            // process response
            // send grid does not provide any of the information, so set them to be empty
            messageId = "";
            detailMessage = "";
            return true;
        }
        /// <summary>
        /// Get the API key for calling the provider
        /// Will try to get the key from SendMailRequest if it's available; or else it will try to get it from AppConfig file 
        /// </summary>
        /// <param name="request">The request which might contain the API Key</param>
        /// <returns>The API Key, or null if not found.</returns>
        public string GetApiKey(SendMailRequest request)
        {
            string apiKey;

            ProviderInfo pi = request.Providers.SingleOrDefault(p => p.ProviderType == ProviderType);
            if (pi != null && !String.IsNullOrWhiteSpace(pi.ApiKey))    // ApiKey is provided in the request
            {
                apiKey = pi.ApiKey;
            }
            else    // ApiKey is not provided in the request, try get it from configuration file
            {
                switch (ProviderType)
                {
                    case ProviderType.SendGrid:
                        apiKey = ConfigurationManager.AppSettings["SendGridApiKey"];
                        break;

                    case ProviderType.MailGun:
                        apiKey = ConfigurationManager.AppSettings["MailGunApiKey"];
                        break;

                    case ProviderType.Mandrill:
                        apiKey = ConfigurationManager.AppSettings["MandrillApiKey"];
                        break;

                    default:
                        apiKey = null;
                        break;
                }
            }

            return apiKey;
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Send an email
 /// </summary>
 /// <param name="request">Contains detailed email info and optionally provider info (such as ApiKeys)</param>
 /// <param name="messageId">The message id returned by the service provider</param>
 /// <param name="detailMessage">The message returned by the service provider, e.g. "failed to send message", "Sent", "Message Queued for delivery"</param>
 /// <returns>True if email was sent successfully</returns>
 public abstract bool SendMail(SendMailRequest request, out string messageId, out string detailMessage);
        /// <summary>
        /// Given a SendMailRequest, return a list of MailServiceProvidersSuitable to process this request
        /// If use has provided an API key in the request, the related provider will be put at the begining of the list
        /// if user did not provided an API key in the request, the provider is put at the end
        /// If no API key is found, the provider won't be used
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static List<MailServiceProvider> GetOrderedMailServiceProviders(SendMailRequest request)
        {
            List<MailServiceProvider> providerList = new List<MailServiceProvider>();

            // Add providers user has specified and provided an API key for
            foreach (ProviderInfo p in request.Providers)
            {
                if (!String.IsNullOrWhiteSpace(p.ApiKey))
                {
                    providerList.Add(MailServiceProvider.GetProvider(p.ProviderType));
                }
            }

            // Add the rest of providers that have an API key in configuration file
            foreach (ProviderType pt in allProviderTypes)
            {
                if (!providerList.Exists(p => p.ProviderType == pt))
                {
                    MailServiceProvider p = MailServiceProvider.GetProvider(pt);
                    string apiKey = p.GetApiKey(request);
                    if (!String.IsNullOrWhiteSpace(apiKey))
                    {
                        providerList.Add(p);
                    }
                }
            }

            return providerList;
        }
        /// <summary>
        /// Process a SendMailRequest, send the email and generate proper response 
        /// </summary>
        /// <param name="request">The request containing email details</param>
        /// <returns>The result of the sending email action</returns>
        public static SendMailResult ProcessSendMailRequest(SendMailRequest request)
        {
            SendMailResult result = new SendMailResult();

            var providers = GetOrderedMailServiceProviders(request);

            // if no ApiKeys are found, we can't use any providers
            if (providers.Count == 0)
            {
                result.Status = SendMailResultStatus.Error.ToString();
                result.Messages.Add("No mail service provider available.");
                return result;
            }

            for (int i = 0; i < providers.Count; i++)
            {
                try
                {
                    string messageId;
                    string detailMessage;

                    bool success = providers[i].SendMail(request, out messageId, out detailMessage);

                    // add message returned by the provider, if any
                    if (!String.IsNullOrWhiteSpace(detailMessage))
                    {
                        result.Messages.Add(detailMessage);
                    }

                    if (success)
                    {
                        result.Status = SendMailResultStatus.Success.ToString();
                        result.MessageId = messageId;
                        result.ProviderUsed = providers[i].ProviderType.ToString();
                        return result;
                    }
                    else
                    {
                        // we don't know why it failed, so continue and try next provider
                        result.Status = SendMailResultStatus.Error.ToString();
                        continue;
                    }
                }
                catch (Exception e)
                {
                    result.Status = SendMailResultStatus.Error.ToString();
                    result.Messages.Add(SendMailRequestProcessor.GetErrorStringFromException(e));

                    if (e is FormatException)
                    {
                        // some of the email address is not correctly formated. stop trying and return the error
                        return result;
                    }
                    else
                    {
                        // for other exceptions, ingore and try next provider
                        continue;
                    }
                }
            }

            return result;
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Send an email
        /// </summary>
        /// <param name="request">Contains detailed email info and optionally provider info (such as ApiKeys)</param>
        /// <param name="messageId">The message id returned by the service provider</param>
        /// <param name="detailMessage">The message returned by the service provider, e.g. "failed to send message", "Sent", "Message Queued for delivery"</param>
        /// <returns>True if email was sent successfully</returns>
        public override bool SendMail(SendMailRequest mailRequest, out string messageId, out string detailMessage)
        {
            // create request
            RestClient client = new RestClient();

            client.BaseUrl = new Uri(ConfigurationManager.AppSettings["MailGunBaseUrl"]);

            string apiKey = GetApiKey(mailRequest);

            client.Authenticator = new HttpBasicAuthenticator("api", apiKey);

            RestRequest  request = new RestRequest();
            string       domain;
            ProviderInfo pi = mailRequest.Providers.SingleOrDefault(p => p.ProviderType == ProviderType);

            if (pi != null)
            {
                domain = pi.SenderDomain;
            }
            else
            {
                domain = ConfigurationManager.AppSettings["MailGunDomain"];
            }

            // Email detail
            request.AddParameter("domain", domain, ParameterType.UrlSegment);
            request.Resource = "{domain}/messages";
            request.AddParameter("from", mailRequest.From);

            foreach (string s in mailRequest.To)
            {
                request.AddParameter("to", s);
            }

            request.AddParameter("subject", mailRequest.Subject);
            request.AddParameter("text", mailRequest.Text);
            request.Method = Method.POST;

            // Send email
            var response = client.Execute(request);

            // process response
            messageId     = "";
            detailMessage = "";

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                try
                {
                    dynamic json = JObject.Parse(response.Content);
                    messageId     = json.id;
                    detailMessage = json.message;
                }
                catch
                {
                    detailMessage = "Failed to parse Mailgun response.";
                }

                // If status is OK we assume message is sent
                // Even if the message from MailGun says something else - we have done our job sending the email
                return(true);
            }
            else
            {
                detailMessage = String.Format("Https status code: {0}", response.StatusCode);
                return(false);
            }
        }
 /// <summary>
 /// Send an email
 /// </summary>
 /// <param name="request">Contains detailed email info and optionally provider info (such as ApiKeys)</param>
 /// <param name="messageId">The message id returned by the service provider</param>
 /// <param name="detailMessage">The message returned by the service provider, e.g. "failed to send message", "Sent", "Message Queued for delivery"</param>
 /// <returns>True if email was sent successfully</returns>
 public abstract bool SendMail(SendMailRequest request, out string messageId, out string detailMessage);
        /// <summary>
        /// Process a SendMailRequest, send the email and generate proper response
        /// </summary>
        /// <param name="request">The request containing email details</param>
        /// <returns>The result of the sending email action</returns>
        public static SendMailResult ProcessSendMailRequest(SendMailRequest request)
        {
            SendMailResult result = new SendMailResult();

            var providers = GetOrderedMailServiceProviders(request);

            // if no ApiKeys are found, we can't use any providers
            if (providers.Count == 0)
            {
                result.Status = SendMailResultStatus.Error.ToString();
                result.Messages.Add("No mail service provider available.");
                return(result);
            }

            for (int i = 0; i < providers.Count; i++)
            {
                try
                {
                    string messageId;
                    string detailMessage;

                    bool success = providers[i].SendMail(request, out messageId, out detailMessage);

                    // add message returned by the provider, if any
                    if (!String.IsNullOrWhiteSpace(detailMessage))
                    {
                        result.Messages.Add(detailMessage);
                    }

                    if (success)
                    {
                        result.Status       = SendMailResultStatus.Success.ToString();
                        result.MessageId    = messageId;
                        result.ProviderUsed = providers[i].ProviderType.ToString();
                        return(result);
                    }
                    else
                    {
                        // we don't know why it failed, so continue and try next provider
                        result.Status = SendMailResultStatus.Error.ToString();
                        continue;
                    }
                }
                catch (Exception e)
                {
                    result.Status = SendMailResultStatus.Error.ToString();
                    result.Messages.Add(SendMailRequestProcessor.GetErrorStringFromException(e));

                    if (e is FormatException)
                    {
                        // some of the email address is not correctly formated. stop trying and return the error
                        return(result);
                    }
                    else
                    {
                        // for other exceptions, ingore and try next provider
                        continue;
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Send an email
        /// </summary>
        /// <param name="request">Contains detailed email info and optionally provider info (such as ApiKeys)</param>
        /// <param name="messageId">The message id returned by the service provider</param>
        /// <param name="detailMessage">The message returned by the service provider, e.g. "failed to send message", "Sent", "Message Queued for delivery"</param>
        /// <returns>True if email was sent successfully</returns>
        public override bool SendMail(SendMailRequest mailRequest, out string messageId, out string detailMessage)
        {
            // create request
            RestClient client = new RestClient();
            client.BaseUrl = new Uri(ConfigurationManager.AppSettings["MailGunBaseUrl"]);

            string apiKey = GetApiKey(mailRequest);
            client.Authenticator = new HttpBasicAuthenticator("api", apiKey);

            RestRequest request = new RestRequest();
            string domain;
            ProviderInfo pi = mailRequest.Providers.SingleOrDefault(p => p.ProviderType == ProviderType);
            if (pi != null)
            {
                domain = pi.SenderDomain;
            }
            else
            {
                domain = ConfigurationManager.AppSettings["MailGunDomain"];
            }

            // Email detail
            request.AddParameter("domain", domain, ParameterType.UrlSegment);
            request.Resource = "{domain}/messages";
            request.AddParameter("from", mailRequest.From);

            foreach (string s in mailRequest.To)
            {
                request.AddParameter("to", s);
            }

            request.AddParameter("subject", mailRequest.Subject);
            request.AddParameter("text", mailRequest.Text);
            request.Method = Method.POST;

            // Send email
            var response = client.Execute(request);

            // process response
            messageId = "";
            detailMessage = "";

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                try
                {
                    dynamic json = JObject.Parse(response.Content);
                    messageId = json.id;
                    detailMessage = json.message;
                }
                catch
                {
                    detailMessage = "Failed to parse Mailgun response.";
                }

                // If status is OK we assume message is sent
                // Even if the message from MailGun says something else - we have done our job sending the email
                return true;
            }
            else
            {
                detailMessage = String.Format("Https status code: {0}", response.StatusCode);
                return false;
            }
        }