0xdeafcafe / sendgrid-dotnet

Other
15 stars 1 forks source link

Usage Examples? #1

Closed NotMyself closed 8 years ago

NotMyself commented 8 years ago

Hi could you provide a couple useage examples?

0xdeafcafe commented 8 years ago

Here you go:

var connection = new ApiKeyConnection("sendgrid api key");
var client = new SendGridClient(connection);
await client.MailClient.SendAsync("alex@github.com", "Alex Forbes-Reed", "Test Subject", "<h1>body</h1>", "body", "info@github.com", "Github Account");
NotMyself commented 8 years ago

Yeah, my question really wasn't that clear. When I submitted it, I was trying to figure out how to register it with IoC. This is what I came up with eventually.

The Service

    public class ContactUsOptions
    {
        public string ApiKey { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Subject { get; } = "Kiehl NW Website Contact Form Submission";
    }

    public class ContactUsService
    {
        private readonly ContactUsOptions options;
        private readonly ILogger<ContactUsService> logger;

        public ContactUsService(IOptions<ContactUsOptions> accessor,
            ILogger<ContactUsService> logger)
        {
            this.logger = logger;
            this.options = accessor.Value;
        }

        public Task SendAsync(ContactViewModel vm)
        {
            logger?.LogInformation($"Sending Contact Us Message From {vm.Email}");

            return GetClient()?.SendAsync(
                     from: vm.Email
                    , fromName: vm.Name
                    , to: options.Email
                    , toName: options.Name
                    , subject: options.Subject
                    , htmlBody: vm.Message
                    , textBody: vm.Message);
        }

        private IMailClient GetClient()
        {
            if (string.IsNullOrWhiteSpace(options.ApiKey))
            {
                logger?.LogError("API Key Not Found: Unable to create SendGrid Client");
                return null;
            }

            var key = new ApiKeyConnection(options.ApiKey);
            var client = new SendGridClient(key);
            return client.MailClient;
        }
    }

The Registration

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<ContactUsOptions>(o =>
            {
                o.ApiKey = Configuration["SENDGRID_API_KEY"];
                o.Name = Configuration["ContactUs:Name"];
                o.Email = Configuration["ContactUs:Email"];
            });

            services.AddScoped<ContactUsService>();

            services.AddMvc();
        }
ilanc commented 8 years ago

Thanks mate - works like a charm

0xdeafcafe commented 8 years ago

Added this usage example to the readme in 015c95f755a39bbf9f47095310f9fbe71dfefb0a - finally. Thank's again @NotMyself.