1+ namespace NET6CustomLibrary . MailKit . Services ;
2+
3+ public class MailKitEmailSender : IEmailClient
4+ {
5+ private readonly ILoggerService loggerService ;
6+ private readonly IOptionsMonitor < SmtpOptions > smtpOptionsMonitor ;
7+
8+ public MailKitEmailSender ( ILoggerService loggerService , IOptionsMonitor < SmtpOptions > smtpOptionsMonitor )
9+ {
10+ this . loggerService = loggerService ;
11+ this . smtpOptionsMonitor = smtpOptionsMonitor ;
12+ }
13+
14+ public Task SendEmailAsync ( string email , string subject , string htmlMessage )
15+ {
16+ return SendEmailAsync ( email , string . Empty , subject , htmlMessage ) ;
17+ }
18+
19+ public async Task < bool > SendEmailAsync ( string recipientEmail , string replyToEmail , string subject ,
20+ string htmlMessage , CancellationToken token = default )
21+ {
22+ try
23+ {
24+ var options = smtpOptionsMonitor . CurrentValue ;
25+
26+ using SmtpClient client = new ( ) ;
27+
28+ await client . ConnectAsync ( options . Host , options . Port , options . Security , token ) ;
29+
30+ if ( ! string . IsNullOrEmpty ( options . Username ) )
31+ {
32+ await client . AuthenticateAsync ( options . Username , options . Password , token ) ;
33+ }
34+
35+ MimeMessage message = new ( ) ;
36+
37+ message . From . Add ( MailboxAddress . Parse ( options . Sender ) ) ;
38+ message . To . Add ( MailboxAddress . Parse ( recipientEmail ) ) ;
39+
40+ if ( replyToEmail is not ( null or "" ) )
41+ {
42+ message . ReplyTo . Add ( MailboxAddress . Parse ( replyToEmail ) ) ;
43+ }
44+
45+ message . Subject = subject ;
46+ message . Body = new TextPart ( "html" )
47+ {
48+ Text = htmlMessage
49+ } ;
50+
51+ await client . SendAsync ( message , token ) ;
52+ await client . DisconnectAsync ( true , token ) ;
53+
54+ loggerService . SaveLogInformation ( $ "Message successfully sent to the email address { recipientEmail } ") ;
55+ return true ;
56+ }
57+ catch
58+ {
59+ loggerService . SaveLogError ( $ "Couldn't send email to { recipientEmail } with message { htmlMessage } ") ;
60+ return false ;
61+ }
62+ }
63+ }
0 commit comments