Closed NotMyself closed 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");
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();
}
Thanks mate - works like a charm
Added this usage example to the readme in 015c95f755a39bbf9f47095310f9fbe71dfefb0a - finally. Thank's again @NotMyself.
Hi could you provide a couple useage examples?