Last active
December 31, 2019 14:38
-
-
Save Wanchai/c4d5467cbe7ed9a901da006c360e30af to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using MailKit.Net.Smtp; | |
using MailKit.Security; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.Logging; | |
using MimeKit; | |
namespace MailerApi.Services | |
{ | |
public class EmailerService | |
{ | |
private readonly ILogger<EmailerService> Logger; | |
IConfigurationSection SMTP { get; } | |
public EmailerService( | |
IConfiguration config, | |
ILogger<EmailerService> logger | |
) | |
{ | |
Logger = logger; | |
try | |
{ | |
// Used to access appsettings.json | |
SMTP = config.GetSection("smtp"); | |
} | |
catch (System.Exception ex) | |
{ | |
Logger.LogError(ex, ex.Message); | |
} | |
} | |
public void Send(string toName, string toMail, string subject, string body, string bodyHtml) | |
{ | |
try | |
{ | |
// Composing the whole email | |
var message = new MimeMessage(); | |
message.From.Add(new MailboxAddress(SMTP["FromName"], SMTP["From"])); | |
message.To.Add(new MailboxAddress(toName, toMail)); | |
message.Subject = subject; | |
var headers = new HeaderId[] { HeaderId.From, HeaderId.Subject, HeaderId.To }; | |
var builder = new BodyBuilder(); | |
builder.TextBody = body; | |
builder.HtmlBody = bodyHtml; | |
message.Body = builder.ToMessageBody(); | |
message.Prepare(EncodingConstraint.SevenBit); | |
// Sending the email | |
using(var client = new SmtpClient()) | |
{ | |
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS) | |
client.ServerCertificateValidationCallback = (s, c, h, e) => | |
{ | |
Console.WriteLine(e); | |
return true; | |
}; | |
client.Connect(SMTP["Url"], Convert.ToInt32(SMTP["Port"]), SecureSocketOptions.SslOnConnect); | |
client.Authenticate(SMTP["Login"], SMTP["Password"]); | |
client.Send(message); | |
client.Disconnect(true); | |
} | |
} | |
catch (System.Exception ex) | |
{ | |
Logger.LogError(ex, ex.Message); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment