Пример #1
0
        public override void PopulateMessage(EmailRequest request, ISendGrid message)
        {
            var sendgridToken = SendGridTokenManager.GetEmailTemplateTokenForCommunicationToken(CommunicationTokens.EmployerApplicationLinks);

            var applicationLinksJson = request.Tokens.Single(t => t.Key == CommunicationTokens.EmployerApplicationLinks).Value;
            var applicationLinks     = JsonConvert.DeserializeObject <Dictionary <string, string> >(applicationLinksJson) ?? new Dictionary <string, string>();

            var linksStringBuilder = new StringBuilder("<ul>");

            foreach (var applicationLink in applicationLinks)
            {
                linksStringBuilder.Append($"<li><a href=\"https://{_siteDomainName}{applicationLink.Value}\">{applicationLink.Key}</a></li>");
            }
            linksStringBuilder.Append("</ul>");

            message.AddSubstitution(sendgridToken, new List <string> {
                linksStringBuilder.ToString()
            });

            var tokens = new List <CommunicationTokens> {
                CommunicationTokens.ApplicationVacancyTitle, CommunicationTokens.ProviderName, CommunicationTokens.EmployerApplicationLinksExpiry
            };

            foreach (var token in request.Tokens.Where(t => tokens.Contains(t.Key)))
            {
                var sendgridtoken = SendGridTokenManager.GetEmailTemplateTokenForCommunicationToken(token.Key);

                message.AddSubstitution(sendgridtoken,
                                        new List <string>
                {
                    token.Value
                });
            }
        }
 public SendService(IDatabaseAccess databaseAccess)
 {
     _deliveryRepository = databaseAccess.Repository<Delivery>();
     _sendGridMessage = new SendGridMessage();
     _sendGridMessage.From = new MailAddress(ConfigurationManager.AppSettings["SendFrom"]);
     _transport = new Web(ConfigurationManager.AppSettings["SendGridkey"]);
 }
Пример #3
0
        private void PopulateCandidateName(EmailRequest request, ISendGrid message)
        {
            var token = SendGridTokenManager.GetEmailTemplateTokenForCommunicationToken(CommunicationTokens.CandidateFirstName);
            var value = request.Tokens.First(t => t.Key == CommunicationTokens.CandidateFirstName).Value;

            AddSubstitutionTo(message, token, value);
        }
Пример #4
0
		private void AttachFiles(ISendGrid message, MultipartFormDataContent content)
		{
			var files = FetchFileBodies(message);
			foreach (var file in files)
			{
				var fs = new FileStream(file.Key, FileMode.Open, FileAccess.Read);
				var fileContent = new StreamContent(fs);

				fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
				{
					Name = "files[" + Path.GetFileName(file.Key) + "]",
					FileName = Path.GetFileName(file.Key)
				};

				fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
				content.Add(fileContent);
			}

			var streamingFiles = FetchStreamingFileBodies(message);
			foreach (var file in streamingFiles)
			{
				var stream = file.Value;
				var fileContent = new StreamContent(stream);

				fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
				{
					Name = "files[" + Path.GetFileName(file.Key) + "]",
					FileName = Path.GetFileName(file.Key)
				};

				fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
				content.Add(fileContent);
			}
		}
Пример #5
0
 public AccountController(UserManager <ApplicationUser> userManager, SignInManager <ApplicationUser> signInManager, ApplicationDBContext context, ISendGrid sendGrid)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _context       = context;
     _sendGrid      = sendGrid;
 }
Пример #6
0
 public override void PopulateMessage(EmailRequest request, ISendGrid message)
 {
     PopulateCandidateName(request, message);
     PopulateSavedSearchAlerts(request, message);
     PopulateSiteDomainName(message);
     PopulateUnsubscribe(request, message);
 }
Пример #7
0
        internal List <KeyValuePair <String, String> > FetchFormParams(ISendGrid message)
        {
            var result = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <String, String>("api_user", _credentials.UserName),
                new KeyValuePair <String, String>("api_key", _credentials.Password),
                new KeyValuePair <String, String>("headers",
                                                  message.Headers.Count == 0 ? null : Utils.SerializeDictionary(message.Headers)),
                new KeyValuePair <String, String>("replyto",
                                                  message.ReplyTo.Length == 0 ? null : message.ReplyTo.ToList().First().Address),
                new KeyValuePair <String, String>("from", message.From.Address),
                new KeyValuePair <String, String>("fromname", message.From.DisplayName),
                new KeyValuePair <String, String>("subject", message.Subject),
                new KeyValuePair <String, String>("text", message.Text),
                new KeyValuePair <String, String>("html", message.Html),
                new KeyValuePair <String, String>("x-smtpapi", message.Header.JsonString() ?? "")
            };

            if (message.To != null)
            {
                result = result.Concat(message.To.ToList().Select(a => new KeyValuePair <String, String>("to[]", a.Address)))
                         .Concat(message.To.ToList().Select(a => new KeyValuePair <String, String>("toname[]", a.DisplayName)))
                         .ToList();
            }
            if (message.GetEmbeddedImages().Count > 0)
            {
                result = result.Concat(message.GetEmbeddedImages().ToList().Select(x => new KeyValuePair <String, String>(string.Format("content[{0}]", x.Key), x.Value)))
                         .ToList();
            }
            return(result.Where(r => !String.IsNullOrEmpty(r.Value)).ToList());
        }
Пример #8
0
 public AccountCore(AccountManager manager, IConfiguration config, ISendGrid grid, IHostingEnvironment enviroment)
 {
     _manager    = manager;
     _config     = config;
     _send       = grid;
     _enviroment = enviroment;
 }
Пример #9
0
 internal List<KeyValuePair<String, String>> FetchFormParams(ISendGrid message)
 {
     var result = new List<KeyValuePair<string, string>>
     {
         new KeyValuePair<String, String>("api_user", _credentials.UserName),
         new KeyValuePair<String, String>("api_key", _credentials.Password),
         new KeyValuePair<String, String>("headers", message.Headers.Count == 0 ? null :  Utils.SerializeDictionary(message.Headers)),
         new KeyValuePair<String, String>("replyto", message.ReplyTo.Length == 0 ? null : message.ReplyTo.ToList().First().Address),
         new KeyValuePair<String, String>("from", message.From.Address),
         new KeyValuePair<String, String>("fromname", message.From.DisplayName),
         new KeyValuePair<String, String>("subject", message.Subject),
         new KeyValuePair<String, String>("text", message.Text),
         new KeyValuePair<String, String>("html", message.Html),
         new KeyValuePair<String, String>("x-smtpapi", message.Header.AsJson())
     };
     if(message.To != null)
     {
         result = result.Concat(message.To.ToList().Select(a => new KeyValuePair<String, String>("to[]", a.Address)))
             .Concat(message.To.ToList().Select(a => new KeyValuePair<String, String>("toname[]", a.DisplayName)))
             .ToList();
     }
     if(message.Bcc != null)
     {
         result = result.Concat(message.Bcc.ToList().Select(a => new KeyValuePair<String, String>("bcc[]", a.Address)))
                 .ToList();
     }
     if(message.Cc != null)
     {
         result = result.Concat(message.Cc.ToList().Select(a => new KeyValuePair<String, String>("cc[]", a.Address)))
             .ToList();
     }
     return result.Where(r => !String.IsNullOrEmpty(r.Value)).ToList();
 }
Пример #10
0
		private void AttachFormParams(ISendGrid message, MultipartFormDataContent content)
		{
			var formParams = FetchFormParams(message);
			foreach (var keyValuePair in formParams)
			{
				content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
			}
		}
Пример #11
0
 internal List <KeyValuePair <String, FileInfo> > FetchFileBodies(ISendGrid message)
 {
     if (message.Attachments == null)
     {
         return(new List <KeyValuePair <string, FileInfo> >());
     }
     return(message.Attachments.Select(name => new KeyValuePair <String, FileInfo>(name, new FileInfo(name))).ToList());
 }
Пример #12
0
        private static void PopulateFullName(EmailRequest request, ISendGrid message)
        {
            var candidateFirstNameToken = SendGridTokenManager.GetEmailTemplateTokenForCommunicationToken(CommunicationTokens.FullName);

            var substitutionText = request.Tokens.First(t => t.Key == CommunicationTokens.FullName).Value;

            AddSubstitutionTo(message, candidateFirstNameToken, substitutionText);
        }
Пример #13
0
        private async Task SendAsync(ISendGrid message)
        {
            var credentials = new NetworkCredential("Gregorio", "LosAngeles8!");

            var trasportToWeb = new SendGrid.Web(credentials);

            await trasportToWeb.DeliverAsync(message);
        }
 public override void PopulateMessage(EmailRequest request, ISendGrid message)
 {
     PopulateCandidateName(request, message);
     PopulateApplicationStatusAlerts(request, message);
     PopulateExpiringDrafts(request, message);
     PopulateSiteDomainName(message);
     PopulateUnsubscribe(request, message);
 }
        public override void PopulateMessage(EmailRequest request, ISendGrid message)
        {
            PopulateCandidateName(request, message);

            PopulateItemCountData(request, message);

            PopulateHtmlData(request, message);
        }
Пример #16
0
 public EmployeesService(UserManager <Employee> userManger, SignInManager <Employee> signInManager, OmmDbContext context, IDepartmentsService departmentsService, ISendGrid emailSender)
 {
     this.userManger         = userManger;
     this.signInManager      = signInManager;
     this.context            = context;
     this.departmentsService = departmentsService;
     this.emailSender        = emailSender;
 }
Пример #17
0
 /// <summary>
 ///     Asynchronously delivers a message over SendGrid's Web interface
 /// </summary>
 /// <param name="message"></param>
 public async Task DeliverAsync(ISendGrid message)
 {
     var content = new MultipartFormDataContent();
     AttachFormParams(message, content);
     AttachFiles(message, content);
     var response = await _client.PostAsync(Endpoint, content);
     await ErrorChecker.CheckForErrorsAsync(response);
 }
Пример #18
0
        private static async Task SendAsync(ISendGrid message)
        {
            var credentials = new NetworkCredential("xyz", "12345!");

            var trasportToWeb = new SendGrid.Web(credentials);

            await trasportToWeb.DeliverAsync(message);
        }
Пример #19
0
        internal List<KeyValuePair<string, FileInfo>> FetchFileBodies(ISendGrid message)
        {
            if (message.Attachments == null)
            {
                return new List<KeyValuePair<string, FileInfo>>();
            }

            return message.Attachments.Select(name => new KeyValuePair<string, FileInfo>(name, new FileInfo(name))).ToList();
        }
 private static void AddSubstitutionTo(ISendGrid message, string sendgridtoken, string substitutionText)
 {
     message.AddSubstitution(
         sendgridtoken,
         new List <string>
     {
         substitutionText
     });
 }
Пример #21
0
 public Task DeliverAsync(ISendGrid message)
 {
     var client = new SmtpClient();
     var resultObject = new object();
     client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
     client.PickupDirectoryLocation = _settings.EmailFolder;
     client.SendAsync(new MailMessage(message.From.Address, message.To.FirstOrDefault().Address, message.Subject, message.Html), resultObject);
     return Task.FromResult(resultObject);
 }
Пример #22
0
        private void AttachFormParams(ISendGrid message, MultipartFormDataContent content)
        {
            var formParams = FetchFormParams(message);

            foreach (var keyValuePair in formParams)
            {
                content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
            }
        }
Пример #23
0
 /// <summary>
 /// Delivers a message over SendGrid's Web interface
 /// </summary>
 /// <param name="message"></param>
 public void Deliver(ISendGrid message)
 {
     var client = Https ? new RestClient("https://" + BaseURl) : new RestClient("http://" + BaseURl);
     var request = new RestRequest(Endpoint + ".xml", Method.POST);
     AttachFormParams(message, request);
     AttachFiles(message, request);
     var response = client.Execute(request);
     CheckForErrors(response);
 }
Пример #24
0
        private static async Task SendAsync(ISendGrid message)
        {
            var credentials = new NetworkCredential("xyz", "12345!");

            var trasportToWeb = new SendGrid.Web(credentials);

            await trasportToWeb.DeliverAsync(message);

        }
Пример #25
0
        private void PopulateSavedSearchAlerts(EmailRequest request, ISendGrid message)
        {
            var token = SendGridTokenManager.GetEmailTemplateTokenForCommunicationToken(CommunicationTokens.SavedSearchAlerts);
            var value = request.Tokens.First(t => t.Key == CommunicationTokens.SavedSearchAlerts).Value;

            var json = TransformTokenValueToJson(value);
            var html = TransformJsonToHtml(json);

            AddSubstitutionTo(message, token, html);
        }
Пример #26
0
        private void AttachFiles(ISendGrid message, MultipartEntity multipartEntity)
        {
            var files = FetchFileBodies(message);

            files.ForEach(kvp => multipartEntity.AddBody(new FileBody("files[" + Path.GetFileName(kvp.Key) + "]", Path.GetFileName(kvp.Key), kvp.Value)));

            var streamingFiles = FetchStreamingFileBodies(message);

            streamingFiles.ForEach(kvp => multipartEntity.AddBody(new StreamedFileBody(kvp.Value, kvp.Key)));
        }
        private static void PopulateItemCountData(EmailRequest request, ISendGrid message)
        {
            var itemCountToken = SendGridTokenManager.GetEmailTemplateTokenForCommunicationToken(CommunicationTokens.ExpiringDraftsCount);

            var itemCount = Convert.ToInt32(request.Tokens.First(t => t.Key == CommunicationTokens.ExpiringDraftsCount).Value);

            var substitutionText = itemCount == 1 ? OneSavedApplicationAboutToExpire : MoreThanOneSaveApplicationAboutToExpire;

            AddSubstitutionTo(message, itemCountToken, substitutionText);
        }
Пример #28
0
        public Task DeliverAsync(ISendGrid message)
        {
            var client       = new SmtpClient();
            var resultObject = new object();

            client.DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory;
            client.PickupDirectoryLocation = _config.Get("DevelopmentEmailFolder");
            client.SendAsync(new MailMessage(message.From.Address, message.To.FirstOrDefault().Address, message.Subject, message.Html), resultObject);
            return(Task.FromResult(resultObject));
        }
Пример #29
0
        /// <summary>
        ///     Asynchronously delivers a message over SendGrid's Web interface
        /// </summary>
        /// <param name="message"></param>
        public async Task DeliverAsync(ISendGrid message)
        {
            var content = new MultipartFormDataContent();

            AttachFormParams(message, content);
            AttachFiles(message, content);
            var response = await _client.PostAsync(Endpoint, content);

            await ErrorChecker.CheckForErrorsAsync(response);
        }
Пример #30
0
 public ArtistService(
     IDeletableEntityRepository <Artist> artistRepository,
     ISendGrid emailSender,
     IUserService userService
     )
 {
     this.artistRepository = artistRepository;
     this.emailSender      = emailSender;
     this.userService      = userService;
 }
Пример #31
0
        /// <summary>
        /// Delivers a message over SendGrid's Web interface
        /// </summary>
        /// <param name="message"></param>
        public void Deliver(ISendGrid message)
        {
            var client  = Https ? new RestClient("https://" + BaseURl) : new RestClient("http://" + BaseURl);
            var request = new RestRequest(Endpoint + ".xml", Method.POST);

            AttachFormParams(message, request);
            AttachFiles(message, request);
            var response = client.Execute(request);

            CheckForErrors(response);
        }
        private void PopulateApplicationStatusAlerts(EmailRequest request, ISendGrid message)
        {
            var sendgridToken = SendGridTokenManager.GetEmailTemplateTokenForCommunicationToken(CommunicationTokens.ApplicationStatusAlerts);

            var alertsJson = request.Tokens.First(t => t.Key == CommunicationTokens.ApplicationStatusAlerts).Value;
            var alerts     = JsonConvert.DeserializeObject <List <ApplicationStatusAlert> >(alertsJson) ?? new List <ApplicationStatusAlert>();

            var substitutionText = GetApplicationStatusAlertsInfoSubstitution(alerts);

            AddSubstitutionTo(message, sendgridToken, substitutionText);
        }
Пример #33
0
        /// <summary>
        /// Delivers a message over SendGrid's Web interface
        /// </summary>
        /// <param name="message"></param>
        public void Deliver(ISendGrid message)
        {
            MultipartEntity multipartEntity;
            HttpPost postMethod;

            var client = InitializeTransport(out multipartEntity, out postMethod);
            AttachFormParams(message, multipartEntity);
            AttachFiles(message, multipartEntity);
            var response = client.Execute(postMethod);
            CheckForErrors(response);
        }
Пример #34
0
 public override void PopulateMessage(EmailRequest request, ISendGrid message)
 {
     foreach (var token in request.Tokens)
     {
         var sendgridtoken = SendGridTokenManager.GetEmailTemplateTokenForCommunicationToken(token.Key);
         message.AddSubstitution(sendgridtoken,
                                 new List <string>
         {
             token.Value
         });
     }
 }
Пример #35
0
        /// <summary>
        /// Delivers a message over SendGrid's Web interface
        /// </summary>
        /// <param name="message"></param>
        public void Deliver(ISendGrid message)
        {
            MultipartEntity multipartEntity;
            HttpPost        postMethod;

            var client = InitializeTransport(out multipartEntity, out postMethod);

            AttachFormParams(message, multipartEntity);
            AttachFiles(message, multipartEntity);
            var response = client.Execute(postMethod);

            CheckForErrors(response);
        }
Пример #36
0
        /// <summary>
        /// Delivers a message over SendGrid's Web interface
        /// </summary>
        /// <param name="message"></param>
        public void Deliver(ISendGrid message)
        {
            var client = new HttpClient
            {
                BaseAddress = _https ? new Uri("https://" + BaseUrl) : new Uri("http://" + BaseUrl)
            };

            var content = new MultipartFormDataContent();
            AttachFormParams(message, content);
            AttachFiles(message, content);
            var response = client.PostAsync(Endpoint + ".xml", content).Result;
            CheckForErrors(response);
        }
Пример #37
0
		/// <summary>
		///     Asynchronously delivers a message over SendGrid's Web interface
		/// </summary>
		/// <param name="message"></param>
		public async void DeliverAsync(ISendGrid message)
		{
			var client = new HttpClient
			{
				BaseAddress = new Uri("https://" + BaseUrl)
			};

			var content = new MultipartFormDataContent();
			AttachFormParams(message, content);
			AttachFiles(message, content);
			var response = await client.PostAsync(Endpoint + ".xml", content);
			await CheckForErrorsAsync(response);
		}
Пример #38
0
 public void Deliver(ISendGrid message)
 {
     //_serviceManager.LogEvent("Sending an email...");
     try
     {
         _transport.Deliver(message);
         //_serviceManager.LogSucessful("Email sent.");
     }
     catch (Exception ex)
     {
         //_serviceManager.LogFail(ex, "Failed to send email.");
         throw;
     }
 }
Пример #39
0
 public async Task DeliverAsync(ISendGrid message)
 {
     _serviceManager.LogEvent("Sending an email...");
     try
     {
         await _transport.DeliverAsync(message);
         _serviceManager.LogSucessful("Email sent.");
     }
     catch (Exception ex)
     {
         _serviceManager.LogFail(ex, "Failed to send email.");
         throw;
     }
 }
Пример #40
0
 public Task DeliverAsync(ISendGrid message)
 {
     var client = new SmtpClient
     {
         DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
         PickupDirectoryLocation = _settings.EmailFolder
     };
     var toAddress = message.To.FirstOrDefault();
     if (toAddress == null)
     {
         throw new InvalidOperationException("Can't send email without addressee.");
     }
     return client.SendMailAsync(new MailMessage(message.From.Address, toAddress.Address, message.Subject, message.Html));
 }
Пример #41
0
        public Task DeliverAsync(ISendGrid message)
        {
            var client = new SmtpClient
            {
                DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                PickupDirectoryLocation = _settings.EmailFolder
            };
            var toAddress = message.To.FirstOrDefault();

            if (toAddress == null)
            {
                throw new InvalidOperationException("Can't send email without addressee.");
            }
            return(client.SendMailAsync(new MailMessage(message.From.Address, toAddress.Address, message.Subject, message.Html)));
        }
Пример #42
0
        public async Task DeliverAsync(ISendGrid message)
        {
            _serviceManager.LogEvent("Sending an email...");
            try
            {
                await _transport.DeliverAsync(message);

                _serviceManager.LogSucessful("Email sent.");
            }
            catch (Exception ex)
            {
                _serviceManager.LogFail(ex, "Failed to send email.");
                throw;
            }
        }
Пример #43
0
        /// <summary>
        ///     Asynchronously delivers a message over SendGrid's Web interface
        /// </summary>
        /// <param name="message"></param>
        public async Task DeliverAsync(ISendGrid message)
        {
            var client = new HttpClient
            {
                BaseAddress = new Uri("https://" + BaseUrl)
            };

            var content = new MultipartFormDataContent();

            AttachFormParams(message, content);
            AttachFiles(message, content);
            var response = await client.PostAsync(Endpoint + ".xml", content);

            await CheckForErrorsAsync(response);
        }
Пример #44
0
        private static void CheckForErrors(HttpResponseMessage response, ISendGrid message)
        {
            var content = response.Content.ReadAsStreamAsync().Result;
            var errors  = GetErrorsInResponse(content);

            //// API error
            //if (errors.Any())
            //    throw new InvalidApiRequestException(response.StatusCode, errors, response.ReasonPhrase);

            //// Other error
            //if (response.StatusCode != HttpStatusCode.OK)
            //    FindErrorsInResponse(content);

            CheckForErr((int)response.StatusCode, message);
        }
Пример #45
0
		/// <summary>
		///     Asynchronously delivers a message over SendGrid's Web interface
		/// </summary>
		/// <param name="message"></param>
		public async Task DeliverAsync(ISendGrid message)
		{
		    var client = new HttpClient();
            
		    client.BaseAddress = new Uri("https://" + BaseUrl);
		    client.Timeout = _timeout;

            var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "sendgrid/" + version + ";csharp");

			var content = new MultipartFormDataContent();
			AttachFormParams(message, content);
			AttachFiles(message, content);
			var response = await client.PostAsync(Endpoint + ".xml", content);
			await CheckForErrorsAsync(response);
		}
 private void SetMessageBody(ProjectSubmission project, ISendGrid email)
 {
     email.Html = @"<html>
     <body>
     <h1>A new project was submitted! Yay!</h1>
     <table style='border-collapse: collapse;'>
     <tr>
     <td style='border: 1px solid #CCC; padding: 5px;'><b>Project name:</b></td>
     <td style='border: 1px solid #CCC; padding: 5px;'>" + project.ProjectName + @"</td>
     </tr>
     <tr>
     <td style='border: 1px solid #CCC; padding: 5px;'><b>Requested by:</b></td>
     <td style='border: 1px solid #CCC; padding: 5px;'>" + project.RequestedBy + @"</td>
     </tr>
     <tr>
     <td style='border: 1px solid #CCC; padding: 5px;'><b>Details and dimensions:</b></td>
     <td style='border: 1px solid #CCC; padding: 5px;'>" + project.DetailsAndDimensions + @"</td>
     </tr>
     <tr>
     <td style='border: 1px solid #CCC; padding: 5px;'><b>Deadline:</b></td>
     <td style='border: 1px solid #CCC; padding: 5px;'>" + project.Deadline.ToShortDateString() + @"</td>
     </tr>
     <tr>
     <td style='border: 1px solid #CCC; padding: 5px;'><b>First proof due:</b></td>
     <td style='border: 1px solid #CCC; padding: 5px;'>" + project.FirstProofDate.ToShortDateString() + @"</td>
     </tr>
     <tr>
     <td style='border: 1px solid #CCC; padding: 5px;'><b>Key objective/Call to action:</b></td>
     <td style='border: 1px solid #CCC; padding: 5px;'>" + project.KeyObjective + @"</td>
     </tr>
     <tr>
     <td style='border: 1px solid #CCC; padding: 5px;'><b>Key graphics needed:</b></td>
     <td style='border: 1px solid #CCC; padding: 5px;'>" + project.KeyGraphicsNeeded + @"</td>
     </tr>
     <tr>
     <td style='border: 1px solid #CCC; padding: 5px;'><b>Target audience:</b></td>
     <td style='border: 1px solid #CCC; padding: 5px;'>" + project.TargetAudience + @"</td>
     </tr>
     <tr>
     <td style='border: 1px solid #CCC; padding: 5px;'><b>Additional comments:</b></td>
     <td style='border: 1px solid #CCC; padding: 5px;'>" + project.AdditionalComments + @"</td>
     </tr>
     </table>
     </body>
     </html>";
 }
Пример #47
0
        /// <summary>
        ///     Delivers a message over SendGrid's Web interface
        /// </summary>
        /// <param name="message"></param>
        public void Deliver(ISendGrid message)
        {
            RestClient client = this.Https ? new RestClient("https://" + BaseURl) : new RestClient("http://" + BaseURl);

            if (this.Proxy != null)
            {
                client.Proxy = this.Proxy;
            }

            RestRequest request = new RestRequest(Endpoint + ".xml", Method.POST);

            this.AttachFormParams(message, request);
            this.AttachFiles(message, request);

            IRestResponse response = client.Execute(request);
            this.CheckForErrors(response);
        }
Пример #48
0
        internal List<KeyValuePair<String, String>> FetchFormParams(ISendGrid message)
        {
            var result = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<String, String>("headers",
                    message.Headers.Count == 0 ? null : Utils.SerializeDictionary(message.Headers)),
                new KeyValuePair<String, String>("replyto",
                    message.ReplyTo.Length == 0 ? null : message.ReplyTo.ToList().First().Address),
                new KeyValuePair<String, String>("from", message.From.Address),
                new KeyValuePair<String, String>("fromname", message.From.DisplayName),
                new KeyValuePair<String, String>("subject", message.Subject),
                new KeyValuePair<String, String>("text", message.Text),
                new KeyValuePair<String, String>("html", message.Html),
                new KeyValuePair<String, String>("x-smtpapi", message.Header.JsonString() ?? "")
            };

            //If the API key is not specified, use the username and password
            if (_credentials != null)
            {
                var creds = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("api_user", _credentials.UserName),
                    new KeyValuePair<string, string>("api_key", _credentials.Password)
                };
                result.AddRange(creds);
            }

            if (message.To != null)
            {
                result = result.Concat(message.To.ToList().Select(a => new KeyValuePair<String, String>("to[]", a.Address)))
                    .Concat(message.To.ToList().Select(a => new KeyValuePair<String, String>("toname[]", a.DisplayName)))
                    .ToList();
            }

            if (message.Cc != null)
            {
                result.AddRange(message.Cc.Select(c => new KeyValuePair<string, string>("cc[]", c.Address)));
            }

            if (message.Bcc != null)
            {
                result.AddRange(message.Bcc.Select(c => new KeyValuePair<string, string>("bcc[]", c.Address)));
            }

            if (message.GetEmbeddedImages().Count > 0) {
                result = result.Concat(message.GetEmbeddedImages().ToList().Select(x => new KeyValuePair<String, String>(string.Format("content[{0}]", x.Key), x.Value)))
                    .ToList();
            }
            return result.Where(r => !String.IsNullOrEmpty(r.Value)).ToList();
        }
Пример #49
0
 private void AttachFormParams(ISendGrid message, RestRequest request)
 {
     List<KeyValuePair<string, string>> formParams = this.FetchFormParams(message);
     formParams.ForEach(kvp => request.AddParameter(kvp.Key, kvp.Value));
 }
Пример #50
0
        private void AttachFiles(ISendGrid message, RestRequest request)
        {
            //TODO: think the files are being sent in the POST data... but we need to add them as params as well

            var files = FetchFileBodies (message);
            files.ForEach (kvp => request.AddFile ("files[" + Path.GetFileName (kvp.Key) + "]", kvp.Value.FullName));

            var streamingFiles = FetchStreamingFileBodies(message);
            foreach (KeyValuePair<string, MemoryStream> file in streamingFiles) {
                var name = file.Key;
                var stream = file.Value;
                var writer = new Action<Stream>(
                    delegate(Stream s)
                    {
                        stream.CopyTo(s);
                    }
                );

                request.AddFile("files[" + name + "]", writer, name);
            }
        }
Пример #51
0
 private void AttachFormParams(ISendGrid message, RestRequest request)
 {
     var formParams = FetchFormParams(message);
     formParams.ForEach(kvp => request.AddParameter(kvp.Key, kvp.Value));
 }
Пример #52
0
		internal IEnumerable<KeyValuePair<string, MemoryStream>> FetchStreamingFileBodies(ISendGrid message)
		{
			return message.StreamedAttachments.Select(kvp => kvp).ToList();
		}
Пример #53
0
 /// <summary>
 ///     Deliver an email using SMTP protocol
 /// </summary>
 /// <param name="message"></param>
 public void Deliver(ISendGrid message)
 {
     MailMessage mime = message.CreateMimeMessage();
     this.client.Send(mime);
 }
Пример #54
0
 private void AttachFiles(ISendGrid message, MultipartEntity multipartEntity)
 {
     var files = FetchFileBodies(message);
     files.ForEach(kvp => multipartEntity.AddBody(new FileBody("files[" + kvp.Key + "]", kvp.Key, kvp.Value)));
 }
Пример #55
0
 private void AttachFormParams(ISendGrid message, MultipartEntity multipartEntity)
 {
     var formParams = FetchFormParams(message);
     formParams.ForEach(kvp => multipartEntity.AddBody(new StringBody(Encoding.UTF8, kvp.Key, kvp.Value)));
 }
Пример #56
0
        private void AttachFiles(ISendGrid message, MultipartEntity multipartEntity)
        {
            var files = FetchFileBodies(message);
            files.ForEach(kvp => multipartEntity.AddBody(new FileBody("files[" + Path.GetFileName(kvp.Key) + "]", Path.GetFileName(kvp.Key), kvp.Value)));

            var streamingFiles = FetchStreamingFileBodies(message);
            streamingFiles.ForEach(kvp => multipartEntity.AddBody(new StreamedFileBody(kvp.Value, kvp.Key)));
        }
Пример #57
0
        private async Task SendAsync(ISendGrid message)
        {
            var credentials = new NetworkCredential("Gregorio", "LosAngeles8!");

            var trasportToWeb = new SendGrid.Web(credentials);

            await trasportToWeb.DeliverAsync(message);

        }
Пример #58
0
        private static void CreateMail(MailAddress sender, IEnumerable<string> recipients,
                                       IEnumerable<string> recipientsCc, string mailObject,
                                       string body, ISendGrid newMessage, [Optional]string attachementPath)
        {
            newMessage.From = sender;

            foreach (var recipient in recipients)
            {
                newMessage.AddTo(recipient);
            }

            foreach (var recipient in recipientsCc)
            {
                newMessage.AddTo(recipient);
            }

            // Add a message body in HTML format.
            newMessage.Html = body;

            // Add the subject.
            newMessage.Subject = mailObject;

            // Add a footer to the message.
            newMessage.EnableFooter(Footer, string.Format("<p><em>{0}</em></p>", FooterHTML));

            //Add attachement
            if (!string.IsNullOrEmpty(attachementPath))
                newMessage.AddAttachment(attachementPath);
        }
Пример #59
0
 /// <summary>
 /// Deliver an email using SMTP protocol
 /// </summary>
 /// <param name="message"></param>
 public void Deliver(ISendGrid message)
 {
     var mime = message.CreateMimeMessage();
     _client.Send(mime);
 }