Skip to content

Commit

Permalink
#63 replicated the issues when monitoring multiple mail folders or ad…
Browse files Browse the repository at this point in the history
…ding flags
  • Loading branch information
danzuep committed Aug 8, 2024
1 parent 087f638 commit 287bd47
Show file tree
Hide file tree
Showing 8 changed files with 237 additions and 0 deletions.
31 changes: 31 additions & 0 deletions samples/MailKitSimplified.MonitorMultipleMailFolders.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.35013.160
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MonitorMultipleMailFolders", "MonitorMultipleMailFolders\MonitorMultipleMailFolders.csproj", "{6E927546-30C7-453B-ABCB-6AF01B10BB6B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MailKitSimplified.Receiver", "..\source\MailKitSimplified.Receiver\MailKitSimplified.Receiver.csproj", "{5AC74C78-EC2A-4CB6-A0D1-D16DA2839CD4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6E927546-30C7-453B-ABCB-6AF01B10BB6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6E927546-30C7-453B-ABCB-6AF01B10BB6B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6E927546-30C7-453B-ABCB-6AF01B10BB6B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6E927546-30C7-453B-ABCB-6AF01B10BB6B}.Release|Any CPU.Build.0 = Release|Any CPU
{5AC74C78-EC2A-4CB6-A0D1-D16DA2839CD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5AC74C78-EC2A-4CB6-A0D1-D16DA2839CD4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5AC74C78-EC2A-4CB6-A0D1-D16DA2839CD4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5AC74C78-EC2A-4CB6-A0D1-D16DA2839CD4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B723E076-B5DD-4BD7-B23A-96C69E9D145E}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<WarningsAsErrors>true</WarningsAsErrors>
<UserSecretsId>dotnet-WorkerServiceExample-2C375F9E-E9D0-49D0-BA29-55489DEF9D5F</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="CommunityToolkit.Common" Version="8.2.2" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\source\MailKitSimplified.Receiver\MailKitSimplified.Receiver.csproj" />
<ProjectReference Include="..\..\source\MailKitSimplified.Sender\MailKitSimplified.Sender.csproj" />
</ItemGroup>

</Project>
12 changes: 12 additions & 0 deletions samples/MonitorMultipleMailFolders/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using MailKitSimplified.Receiver;
using ExampleNamespace;

using var host = Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
services.AddHostedService<Worker>();
services.AddScopedMailKitSimplifiedEmailReceiver(context.Configuration);
})
.Build();

await host.RunAsync();
11 changes: 11 additions & 0 deletions samples/MonitorMultipleMailFolders/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"profiles": {
"WorkerServiceExample": {
"commandName": "Project",
"dotnetRunMessages": true,
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}
72 changes: 72 additions & 0 deletions samples/MonitorMultipleMailFolders/Worker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using MailKit;
using MailKitSimplified.Receiver.Abstractions;

namespace ExampleNamespace;

public class Worker : BackgroundService
{
private readonly IServiceScope _serviceScope;
private readonly IImapReceiver _imapReceiver;
private readonly ILogger<Worker> _logger;

public Worker(IServiceScopeFactory serviceScopeFactory, ILogger<Worker> logger)
{
_serviceScope = serviceScopeFactory.CreateScope();
_imapReceiver = _serviceScope.ServiceProvider.GetRequiredService<IImapReceiver>();
_logger = logger;
}

protected override async Task ExecuteAsync(CancellationToken cancellationToken = default)
{
using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
//await AddFlagsToNewestMessageSummaryAsync(cancellationToken);
await ImapReceiverFactoryAsync(cancellationToken);
}

private async Task ImapReceiverFactoryAsync(CancellationToken cancellationToken = default)
{
var imapReceiverFactory = _serviceScope.ServiceProvider.GetRequiredService<IImapReceiverFactory>();
var receivers = imapReceiverFactory.GetAllImapReceivers();
foreach (var receiver in receivers)
{
cancellationToken.ThrowIfCancellationRequested();
var messageSummaries = await receiver.ReadMail.GetMessageSummariesAsync(cancellationToken);
int count = 0;
foreach (var messageSummary in messageSummaries)
{
if (++count > 10) break;
_logger.LogInformation($"{receiver} message #{count}: {messageSummary.UniqueId}");
}
}
}

private async Task MailFolderMonitorFactoryAsync(CancellationToken cancellationToken = default)
{
var mailFolderMonitorFactory = _serviceScope.ServiceProvider.GetRequiredService<IMailFolderMonitorFactory>();
void LogUniqueIdArrived(IMessageSummary messageSummary) =>
_logger.LogInformation($"Message #{messageSummary.UniqueId} arrived.");
await mailFolderMonitorFactory.MonitorAllMailboxesAsync(LogUniqueIdArrived, cancellationToken);
}

public async Task<int?> AddFlagsToNewestMessageSummaryAsync(CancellationToken cancellationToken = default)
{
using var mailFolderClient = _serviceScope.ServiceProvider.GetRequiredService<IMailFolderClient>();
var messageSummary = await GetTopMessageSummaryAsync(cancellationToken);
var uniqueId = await mailFolderClient.AddFlagsAsync([messageSummary.UniqueId], MessageFlags.Seen);
return uniqueId;
}

private async Task<IMessageSummary> GetTopMessageSummaryAsync(CancellationToken cancellationToken = default)
{
using var mailFolderReader = _serviceScope.ServiceProvider.GetRequiredService<IMailFolderReader>();
var messageSummaries = await mailFolderReader.Top(1).GetMessageSummariesAsync(cancellationToken);
_logger.LogInformation($"{mailFolderReader} top message summary returned");
return messageSummaries.Single();
}

public override void Dispose()
{
_serviceScope.Dispose();
base.Dispose();
}
}
53 changes: 53 additions & 0 deletions samples/MonitorMultipleMailFolders/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"EmailSender": {
"SmtpHost": "localhost",
"SmtpPort": 25
},
"EmailReceiver": {
"ImapHost": "localhost",
"ImapPort": 143
},
"EmailWorker": {
"DefaultFromAddress": "[email protected]",
"DefaultToAddress": "[email protected]"
},
"Mailbox": {
"EmailReceivers": [
{
"ImapHost": "localhost"
}
],
"FolderMonitors": [
{
"EmailReceiver": {
"ImapHost": "localhost"
},
"IgnoreExistingMailOnConnect": false
}
]
},
"Logging": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Warning"
},
"Debug": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Trace",
"MailKitSimplified.Sender.Services.SmtpSender": "Trace",
"MailKitSimplified.Receiver.Services.ImapReceiver": "Trace",
"MailKitSimplified.Receiver.Services.MailFolderClient": "Trace",
"MailKitSimplified.Receiver.Services.MailFolderMonitor": "Trace",
"MailKitSimplified.Receiver.Services.MailKitProtocolLogger": "Debug",
"MailKitSimplified.Receiver.Services.LogFileWriterQueue": "Debug"
}
},
"Console": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Debug"
}
}
}
}
34 changes: 34 additions & 0 deletions samples/MonitorMultipleMailFolders/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"EmailSender": {
"SmtpHost": "smtp.example.com",
"SmtpPort": 587,
"SmtpCredential": {
"UserName": "",
"Password": ""
},
"ProtocolLog": "Logs\\SmtpClient.txt"
},
"EmailReceiver": {
"MailFolderNames": [],
"MailFolderAccess": "ReadOnly",
"ImapHost": "imap.example.com",
"ImapPort": 993,
"ImapCredential": {
"UserName": "",
"Password": ""
},
"ProtocolLog": "Logs\\ImapClient.txt"
},
"FolderMonitor": {
"IgnoreExistingMailOnConnect": false,
"MessageSummaryItems": "None",
"IdleMinutes": 29,
"MaxRetries": 3
},
"Logging": {
"LogLevel": {
"Default": "Information",
"MailKitSimplified.Receiver.Services.MailKitProtocolLogger": "Debug"
}
}
}
3 changes: 3 additions & 0 deletions scripts/delete-bin-obj-folders.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
$foldersToDelete = @('bin', 'obj')
$foldersToDelete | %{ Get-ChildItem -Path '..' -Filter $_ -Recurse } | Where-Object {$_.PSIsContainer -eq $true} | Remove-Item -Recurse
Write-Output "Deleted all local " | %{$_ + $foldersToDelete + " folders"}

0 comments on commit 287bd47

Please sign in to comment.