66using MailKitSimplified . Receiver . Services ;
77using MailKitSimplified . Sender . Abstractions ;
88using System . Diagnostics ;
9+ using System . Collections . Generic ;
10+ using CommunityToolkit . Common ;
911
1012namespace ExampleNamespace ;
1113
@@ -14,12 +16,14 @@ public class Worker : BackgroundService
1416 private readonly ILogger < Worker > _logger ;
1517 private readonly ISmtpSender _smtpSender ;
1618 private readonly IImapReceiver _imapReceiver ;
19+ private readonly ILoggerFactory _loggerFactory ;
1720
18- public Worker ( ISmtpSender smtpSender , IImapReceiver imapReceiver , ILogger < Worker > logger )
21+ public Worker ( ISmtpSender smtpSender , IImapReceiver imapReceiver , ILoggerFactory loggerFactory )
1922 {
20- _logger = logger ;
23+ _logger = loggerFactory . CreateLogger < Worker > ( ) ;
2124 _smtpSender = smtpSender ;
2225 _imapReceiver = imapReceiver ;
26+ _loggerFactory = loggerFactory ;
2327 }
2428
2529 protected override async Task ExecuteAsync ( CancellationToken cancellationToken = default )
@@ -29,16 +33,29 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken =
2933 //await ReceiveAsync(cancellationToken);
3034 //await QueryAsync(cancellationToken);
3135 //await MonitorAsync(cancellationToken);
32- await DeleteSeenAsync ( cancellationTokenSource ) ;
33- await NotReentrantAsync ( cancellationToken ) ;
36+ //await DeleteSeenAsync(cancellationTokenSource);
37+ //await NotReentrantAsync(cancellationToken);
38+ //await SendAttachmentAsync(500);
39+ //await DownloadAllAttachmentsAsync(cancellationToken);
40+ await TemplateSendAsync ( ) ;
41+ }
42+
43+ private async Task DownloadAllAttachmentsAsync ( CancellationToken cancellationToken = default )
44+ {
45+ var mimeMessage = await GetNewestMimeMessageAsync ( cancellationToken ) ;
46+ string downloadFolder = Path . GetFullPath ( "Downloads" ) ;
47+ _logger . LogInformation ( $ "Downloading attachments from { mimeMessage ? . MessageId } into { downloadFolder } .") ;
48+ var downloads = await MimeMessageReader . Create ( mimeMessage ) . SetLogger ( _loggerFactory )
49+ . DownloadAllAttachmentsAsync ( downloadFolder , createDirectory : true ) ;
50+ _logger . LogInformation ( $ "Downloads ({ downloads . Count } ): { downloads . ToEnumeratedString ( ) } .") ;
3451 }
3552
3653 private async Task MoveSeenToSentAsync ( CancellationTokenSource cancellationTokenSource )
3754 {
3855 var filteredMessages = await _imapReceiver . ReadMail . Query ( SearchQuery . Seen )
3956 . GetMessageSummariesAsync ( cancellationTokenSource . Token ) ;
4057 _logger . LogInformation ( $ "{ _imapReceiver } folder query returned { filteredMessages . Count } messages.") ;
41- var sentFolder = ( ( MailFolderClient ) _imapReceiver . MailFolderClient ) . SentFolder . Value ;
58+ var sentFolder = _imapReceiver . MailFolderClient . SentFolder . Value ;
4259 var messagesDeleted = await _imapReceiver . MailFolderClient
4360 . MoveToAsync ( filteredMessages . Select ( m => m . UniqueId ) , sentFolder , cancellationTokenSource . Token ) ;
4461 _logger . LogInformation ( $ "Deleted { messagesDeleted } messages from { _imapReceiver } { filteredMessages . Count } Seen messages.") ;
@@ -58,7 +75,7 @@ private async Task NotReentrantAsync(CancellationToken cancellationToken = defau
5875 {
5976 using var cancellationTokenSource = CancellationTokenSource . CreateLinkedTokenSource ( cancellationToken ) ;
6077 var sendTask = DelayedSendAsync ( 500 , cancellationToken ) ;
61- var newestEmail = await GetNewestMessageSummaryAsync ( cancellationToken ) ;
78+ var newestEmail = await GetNewestMessageSummaryAsync ( ) ;
6279 await _imapReceiver . MonitorFolder . SetMessageSummaryItems ( )
6380 . SetIgnoreExistingMailOnConnect ( )
6481 . OnMessageArrival ( OnArrivalAsync )
@@ -100,15 +117,27 @@ private async Task ForwardOnArrivalAsync(IMessageSummary messageSummary)
100117 //_smtpSender.Enqueue(mimeForward);
101118 }
102119
103- public async Task < IMessageSummary ? > GetNewestMessageSummaryAsync ( CancellationToken cancellationToken = default )
120+ public async Task < MimeMessage ? > GetNewestMimeMessageAsync ( CancellationToken cancellationToken = default )
104121 {
105122 using var mailFolderClient = _imapReceiver . MailFolderClient ;
123+ var messageSummary = await GetNewestMessageSummaryAsync ( mailFolderClient , cancellationToken ) ;
124+ var mimeMessage = await messageSummary . GetMimeMessageAsync ( cancellationToken ) ;
125+ return mimeMessage ;
126+ }
127+
128+ public async Task < IMessageSummary ? > GetNewestMessageSummaryAsync ( IMailFolderClient ? mailFolderClient = null , CancellationToken cancellationToken = default )
129+ {
130+ bool dispose = mailFolderClient == null ;
131+ mailFolderClient ??= _imapReceiver . MailFolderClient ;
106132 var mailFolder = await mailFolderClient . ConnectAsync ( false , cancellationToken ) . ConfigureAwait ( false ) ;
107133 var index = mailFolder . Count > 0 ? mailFolder . Count - 1 : mailFolder . Count ;
108134 var filter = MessageSummaryItems . UniqueId ;
109135 var messageSummaries = await mailFolder . FetchAsync ( index , index , filter , cancellationToken ) . ConfigureAwait ( false ) ;
110136 await mailFolder . CloseAsync ( false , CancellationToken . None ) . ConfigureAwait ( false ) ;
111- return messageSummaries . FirstOrDefault ( ) ;
137+ var messageSummary = messageSummaries . FirstOrDefault ( ) ;
138+ if ( dispose )
139+ await mailFolderClient . DisposeAsync ( ) ;
140+ return messageSummary ;
112141 }
113142
114143 private async Task GetMessageSummaryRepliesAsync ( CancellationToken cancellationToken = default )
@@ -166,15 +195,45 @@ private async Task QueryAsync(CancellationToken cancellationToken = default)
166195 _logger . LogInformation ( $ "{ _imapReceiver } received { messageSummaries . Count } email(s) in { stopwatch . Elapsed . TotalSeconds : n1} s: { messageSummaries . Select ( m => m . UniqueId ) . ToEnumeratedString ( ) } .") ;
167196 }
168197
169- private async Task DelayedSendAsync ( int millisecondsDelay , CancellationToken cancellationToken = default )
198+ private IEmailWriter GetTemplate ( string from = "me@localhost" )
170199 {
171- await Task . Delay ( millisecondsDelay , cancellationToken ) ;
172- var id = $ "{ Guid . NewGuid ( ) : N} ";
173- bool isSent = await _smtpSender . WriteEmail
174- . From ( "me@localhost" )
200+ if ( ! from . IsEmail ( ) )
201+ _logger . LogWarning ( $ "{ from } is not a valid email.") ;
202+ var id = $ "{ Guid . NewGuid ( ) : N} "[ ..8 ] ;
203+ var template = _smtpSender . WriteEmail
204+ . From ( from )
175205 . To ( $ "{ id } @localhost")
176206 . Subject ( id )
177207 . BodyText ( "text/plain." )
208+ . SaveTemplate ( ) ;
209+ return template ;
210+ }
211+
212+ private async Task TemplateSendAsync ( CancellationToken cancellationToken = default )
213+ {
214+ //var template = await GetTemplate().SaveTemplateAsync();
215+ //var template = await _smtpSender.WithTemplateAsync();
216+ var template = GetTemplate ( ) ;
217+ bool isSent = await template . TrySendAsync ( cancellationToken ) ;
218+ _logger . LogInformation ( $ "Email { ( isSent ? "sent" : "failed to send" ) } .") ;
219+ isSent = await template . TrySendAsync ( cancellationToken ) ;
220+ _logger . LogInformation ( $ "Email { ( isSent ? "sent" : "failed to send" ) } .") ;
221+ }
222+
223+ private async Task SendAttachmentAsync ( int millisecondsDelay , string filePath = "..\\ ..\\ README.md" , CancellationToken cancellationToken = default )
224+ {
225+ bool isSent = await GetTemplate ( )
226+ . TryAttach ( filePath )
227+ . TrySendAsync ( cancellationToken ) ;
228+ _logger . LogInformation ( $ "Email { ( isSent ? "sent" : "failed to send" ) } .") ;
229+ await Task . Delay ( millisecondsDelay , cancellationToken ) ;
230+ }
231+
232+ private async Task DelayedSendAsync ( int millisecondsDelay , CancellationToken cancellationToken = default )
233+ {
234+ await Task . Delay ( millisecondsDelay , cancellationToken ) ;
235+ var id = $ "{ Guid . NewGuid ( ) : N} "[ ..8 ] ;
236+ bool isSent = await GetTemplate ( )
178237 . TrySendAsync ( cancellationToken ) ;
179238 _logger . LogInformation ( $ "Email { ( isSent ? "sent" : "failed to send" ) } .") ;
180239 }
0 commit comments