danzuep / MailKitSimplified

Send and receive emails easily, fluently, with one line of code for each operation.
MIT License
79 stars 10 forks source link

Use Flags - Follow up #9 #22

Closed KoalaBear84 closed 1 year ago

KoalaBear84 commented 1 year ago

Follow up question for #9 if this is the 'best' way possible for MailKitSimplified.

Would like to automatically process mails, and then mark them as Seen or Delete them. It looks like the changing of flags isn't implemented in MailKitSimplified, but it's also not possible to retrieve the (possible) underlying ImapClient.

This workaround works, but requires and extra connection.

Is this the best if I would like to use MailKitSimplified?

Proof of concept code:

CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromMinutes(1));

Console.WriteLine("Connecting..");

using ImapReceiver imapReceiver = ImapReceiver.Create(ServerHost, ServerPort)
    .SetCredential(Username, Password)
    .SetProtocolLog("Logs/ImapClient.txt")
    .SetFolder("INBOX");

ImapClient imapClient = new();
imapClient.Connect(ServerHost, ServerPort);
imapClient.Authenticate(Username, Password);
imapClient.Inbox.Open(FolderAccess.ReadWrite);

Console.WriteLine("Connected");

IMailFolderMonitor mailFolderMonitor = imapReceiver.MonitorFolder.SetMessageSummaryItems(MessageSummaryItems.All);

await mailFolderMonitor.OnMessageArrival(m =>
{
    Console.WriteLine($"[{m.UniqueId}] - {m.Envelope.From} {m.NormalizedSubject}");
    imapClient.Inbox.AddFlags(m.UniqueId, MessageFlags.Seen, true);
}).IdleAsync(cancellationTokenSource.Token);
KoalaBear84 commented 1 year ago

I guess I found out myself πŸ˜‚

I'm not sure if I can access the folder before this event so I can move the FolderAccess code outside of this, if that's better.

await mailFolderMonitor.OnMessageArrival(m =>
{
    Console.WriteLine($"[{m.UniqueId}] - {m.Envelope.From} {m.NormalizedSubject}");

    if (m.Folder.Access != FolderAccess.ReadWrite)
    {
        m.Folder.Open(FolderAccess.ReadWrite);
    }

    if (!m.Flags.Value.HasFlag(MessageFlags.Seen))
    {
        m.Folder.AddFlags(m.UniqueId, MessageFlags.Seen, true);
    }
});
danzuep commented 1 year ago

Good question, and great answer! Your question has made me realise I should add FolderAccess.ReadWrite as an overload on SetFolder (the inbox is the default by the way). You can retrieve the folder like this (once I've added ReadWrite it will be opened if set): var mailFolder = await imapReceiver.ConnectMailFolderAsync();

not possible to retrieve the (possible) underlying ImapClient

If you look at the latest pre-release version I've now added this! It wasn't there before as you've discovered there are better ways, but if you do want to check it out, usage is as follows (I've added a generic logger too since you're not using DI, but you'd need to configure some filters as otherwise it's information overload):

var cancellationTokenSource = new CancellationTokenSource();
var loggerFactory = LoggerFactory.Create(_ => _.SetMinimumLevel(LogLevel.Trace).AddDebug().AddConsole());
using var imapReceiver = ImapReceiver.Create(ServerHost, ServerPort)
    .SetCredential(Username, Password).SetLogger(loggerFactory);
var mailFolder = await imapReceiver.ConnectMailFolderAsync();
await imapReceiver.MonitorFolder
    //.SetMessageSummaryItems(MessageSummaryItems.Envelope | MessageSummaryItems.Flags)
    .OnMessageArrival(m => mailFolder.AddFlags(m.UniqueId, MessageFlags.Seen, true))
    .IdleAsync(cancellationTokenSource.Token);

You can also retrieve the IMAP client like this: var imapClient = await imapReceiver.ConnectAuthenticatedImapClientAsync(); // or imapReceiver.GetImapClient();

If you do check out the latest features, please give me some feedback on it so I can do a proper release πŸ˜„

danzuep commented 1 year ago

I've added your code to the wiki, hope you don't mind πŸ™‚ Would you like to take a crack at adding fluent flag setting to the MessageSummaryExtensions?

KoalaBear84 commented 1 year ago

I find it great that this is added to the wiki πŸ‘

Very good improvements! Ah, normally I always install the latest prereleases, but forgot to check the checkbox this time to check it out πŸ˜…πŸ˜‡

I cannot promise anything, because I'm overloaded myself with lots of thins, but I'll try to see if I can do that. It does seem like a small change.

danzuep commented 1 year ago

No worries if you're busy, as you said it should be a small change anyway πŸ™‚

danzuep commented 1 year ago

I was on a video call for two hours so in the background I added this new feature. Now you can add flags much easier, like this:

await imapReceiver.MonitorFolder
    .OnMessageArrival(m => m.AddFlagsAsync(MessageFlags.Seen))
    .IdleAsync();

It checks to make sure the folder is open and all that, and if it's a delete flag then it does the Expunge method for you.

I did it while doing other things and haven't fully tested it, so please check everything in the pre-release is working for you!

KoalaBear84 commented 1 year ago

Haha, well done multitasking πŸ˜‡

Do I need to check out the code and build it, to be same to test it?

danzuep commented 1 year ago

Package Manager Console: --> Install-Package MailKitSimplified.Receiver -Version 2.4.8-tags-v2-4-8-eta0001

.NET CLI Console:

cd ./MailKitSimplified/samples/ConsoleServiceExample
dotnet add package MailKitSimplified.Receiver --version 2.4.8-tags-v2-4-8-eta0001
../MailKitSimplified.ConsoleServiceExample.sln
KoalaBear84 commented 1 year ago

They change works great! Thanks, well done πŸ‘ Much more useful / logical.

It was a bit confusing see the latest version not at the top, just a notice if this could be improved, as if I didn't knew that I know should get the "eta" version, I wouldv'e picked "zeta", because it appears as the 'latest'.

It also still wants me to 'update' to the previous version πŸ˜‚

image

When this version becomes the current release it would be nice to update the wiki to this newer syntax. Including an example of the delete and add a message that it also automatically expunges to the server.

danzuep commented 1 year ago

I've released these changes πŸ™‚