|
| 1 | +# MailKit configuration |
| 2 | + |
| 3 | + |
| 4 | +## Configuration to add to the appsettings.json file |
| 5 | + |
| 6 | +```json |
| 7 | +"Smtp": { |
| 8 | + "Host": "example.org", |
| 9 | + "Port": 25, |
| 10 | + "Security": "StartTls", |
| 11 | + "Username": "Username SMTP", |
| 12 | + "Password": "Password SMTP", |
| 13 | + "Sender": "MyName <[email protected]>" |
| 14 | +} |
| 15 | +``` |
| 16 | + |
| 17 | + |
| 18 | +## Registering services at Startup |
| 19 | + |
| 20 | +```csharp |
| 21 | +public Startup(IConfiguration configuration) |
| 22 | +{ |
| 23 | + Configuration = configuration; |
| 24 | +} |
| 25 | + |
| 26 | +public IConfiguration Configuration { get; } |
| 27 | + |
| 28 | +public void ConfigureServices(IServiceCollection services) |
| 29 | +{ |
| 30 | + services.AddMailKitEmailSenderService(Configuration); |
| 31 | +} |
| 32 | +``` |
| 33 | + |
| 34 | + |
| 35 | +## Example of the InputMailSender class |
| 36 | +```csharp |
| 37 | +public class InputMailSender |
| 38 | +{ |
| 39 | + public string RecipientEmail { get; set; } |
| 40 | + public string ReplyToEmail { get; set; } |
| 41 | + public string Subject { get; set; } |
| 42 | + public string HtmlMessage { get; set; } |
| 43 | +} |
| 44 | +``` |
| 45 | + |
| 46 | + |
| 47 | +## Example of use in a web api controller |
| 48 | +```csharp |
| 49 | +[ApiController] |
| 50 | +[Route("api/[controller]")] |
| 51 | +public class EmailController : ControllerBase |
| 52 | +{ |
| 53 | + private readonly IEmailClient emailClient; |
| 54 | + |
| 55 | + public EmailController(IEmailClient emailClient) |
| 56 | + { |
| 57 | + this.emailClient = emailClient; |
| 58 | + } |
| 59 | + |
| 60 | + [HttpPost("InvioEmail")] |
| 61 | + public async Task<IActionResult> InvioEmail([FromForm] InputMailSender model) |
| 62 | + { |
| 63 | + try |
| 64 | + { |
| 65 | + var result = await emailClient.SendEmailAsync(model.RecipientEmail, model.ReplyToEmail, model.Subject, model.HtmlMessage); |
| 66 | + |
| 67 | + if (!result) |
| 68 | + { |
| 69 | + return BadRequest(); |
| 70 | + } |
| 71 | + |
| 72 | + return Ok(); |
| 73 | + } |
| 74 | + catch |
| 75 | + { |
| 76 | + //OMISSIS |
| 77 | + } |
| 78 | + } |
| 79 | +} |
| 80 | +``` |
0 commit comments