Skip to content

Mailozaurr is a PowerShell module that aims to provide SMTP, POP3, IMAP and probably some other ways to interact with Email. Underneath it uses MimeKit and MailKit libraries written by Jeffrey Stedfast.

License

Notifications You must be signed in to change notification settings

EvotecIT/Mailozaurr

Repository files navigation

Mailozaurr - PowerShell Module

Mailozaurr is a PowerShell module that aims to provide SMTP, POP3, IMAP and few other ways to interact with Email. Underneath it uses MimeKit and MailKit and EmailValidation libraries written by Jeffrey Stedfast.

This project has 2 branches:

  • v1-legacy - this is the old version of the module. It's working, it's stable and has been around for a while. It's written entirely in PowerShell, and has nice features. It will be maintained until v2 is ready.
  • v2-speedygonzales - this is the new version of the module. It's a complete rewrite. It's written in C#, and slowly all functions from V1 will be replaced by their C# alternative. It's faster, and has couple of new features. It's still in development, but it's already usable.
    • Removed DNS functions as they are moved to DnsClientX module
    • Removed EmailValidation/SPF/DKIM/DMARC/MX/DMARC functions as they are moved to DomainDetective module

This V2 branch uses following libraries:

For oAuth2 it also requires some Microsoft and Google libraries that are also bundled in

Additional dependencies due to features added

This started with a single goal to replace Send-MailMessage which is deprecated/obsolete with something more modern, but since MailKit and MimeKit have lots of options why not build on that?

Support This Project

If you find this project helpful, please consider supporting its development. Your sponsorship will help the maintainers dedicate more time to maintenance and new feature development for everyone.

It takes a lot of time and effort to create and maintain this project. By becoming a sponsor, you can help ensure that it stays free and accessible to everyone who needs it.

To become a sponsor, you can choose from the following options:

Your sponsorship is completely optional and not required for using this project. We want this project to remain open-source and available for anyone to use for free, regardless of whether they choose to sponsor it or not.

If you work for a company that uses our .NET libraries or PowerShell Modules, please consider asking your manager or marketing team if your company would be interested in supporting this project. Your company's support can help us continue to maintain and improve this project for the benefit of everyone.

Thank you for considering supporting this project!

Building project for local use

To build a project and play with the sources you need to:

Install-Module PSPublishModule -Force -Verbose

Once the module is installed - go to Build folder and run: Manage-Mailozaurr.ps1. This will make sure the project has required libraries.

Features

  • Send Email (Send-EmailMessage) using:
    • SMTP with standard password
    • SMTP with oAuth2 Office 365
    • SMTP with oAuth2 Google Mail
    • SMTP with SendGrid
    • SendGrid API
    • Amazon SES API
    • Office 365 Graph API
    • PGP/MIME encryption and signature verification
    • Optional retry logic for Send-EmailMessage via -RetryCount, -RetryDelayMilliseconds, -RetryDelayBackoff and -RetryAlways. Retries are only attempted for transient errors by default, but -RetryAlways forces retries on all errors.
    • Optional SMTP connection pooling via -UseConnectionPool and -ConnectionPoolSize for faster repeated sends. Use Clear-SmtpConnectionPool to reset the pool and Test-SmtpConnection to check if your server keeps connections open.
  • POP3
    • Connect to POP3
    • Get POP3 Emails
    • Save POP3 Emails
    • Delete POP3 Messages with Get-POP3Message -Delete
    • Wait for new POP3 messages with the Wait-POP3Message cmdlet supporting -Until, -StopOnMatch and -TimeoutSeconds
    • Search POP3 mailboxes with Search-POP3Mailbox returning messages (use -Count to limit results)
  • IMAP
    • Connect to IMAP
    • Get IMAP Folder
    • List IMAP root folders with Get-IMAPFolder -Root
    • Get IMAP Messages
    • Delete IMAP Messages with Get-IMAPMessage -Delete
    • Listen for new IMAP messages via ImapIdleListener
    • Wait for new IMAP messages with the Wait-IMAPMessage cmdlet supporting -Until, -StopOnMatch and -TimeoutSeconds
    • Search IMAP mailboxes with Search-IMAPMailbox returning messages (use -Count to limit results)
  • Office 365 Graph API
    • Get Mail Folders via Get-EmailGraphFolder with -Connection or -MgGraphRequest
    • Get Mail Messages
    • Save Mail Messages
    • Mark messages read or unread with Set-GraphMessage
    • Wait for new Graph messages with the Wait-GraphMessage cmdlet
    • Search Graph mailboxes with Search-GraphMailbox returning message info (use -Count to limit results)
    • Message cmdlets output friendly wrappers exposing From, To, Subject, Date and body text
  • Pipeline input is supported for Graph connection objects when retrieving folders or messages:
$graph = Connect-EmailGraph -Credential $cred
$graph | Get-EmailGraphFolder -UserPrincipalName 'user@example.com'
$graph | Get-EmailGraphMessage -UserPrincipalName 'user@example.com' -Limit 10 |
    Save-GraphMessage -Path 'C:\Archive'
  • DNS and email validation functionality is now provided by DomainDetective
  • Convert between EML and MSG message formats

Authenticating to IMAP and POP3

Both Connect-IMAP and Connect-POP3 support a variety of sign-in methods. You can use plain credentials, pass a PSCredential object, or supply an OAuth token.

# Username and password
$imap = Connect-IMAP -Server 'imap.example.com' -UserName 'user@example.com' -Password 'p@ssword'

# Credential object
$cred = Get-Credential
$pop3 = Connect-POP3 -Server 'pop.example.com' -Credential $cred

# OAuth2 token
$oauth = Connect-OAuthGoogle -ClientId 'id' -ClientSecret 'secret' -GmailAccount 'user@example.com' -Scope https://mail.google.com/
$imapOAuth = Connect-IMAP -Server 'imap.gmail.com' -Credential $oauth -OAuth2

Enumerating IMAP folders

After connecting you can list the top-level folders:

$client = Connect-IMAP -Server 'imap.example.com' -Credential $cred
Get-IMAPFolder -Client $client -Root

Using OAuth tokens works the same:

$token = Connect-OAuthGoogle -ClientId 'id' -ClientSecret 'secret' -GmailAccount 'user@example.com' -Scope https://mail.google.com/
$client = Connect-IMAP -Server 'imap.gmail.com' -Credential $token -OAuth2
Get-IMAPFolder -Client $client -Root

You can also open a specific folder by path:

$client = Connect-IMAP -Server 'imap.example.com' -Credential $cred
Get-IMAPFolder -Client $client -Path 'Inbox/Reports'

Listing folder contents

Once a folder is opened you can retrieve its messages using Get-IMAPMessage.

# Inbox messages
$client = Connect-IMAP -Server 'imap.example.com' -Credential $cred
Get-IMAPFolder -Client $client
Get-IMAPMessage -Client $client

# Nested folder
Get-IMAPFolder -Client $client -Path 'Inbox/Reports/2024'
Get-IMAPMessage -Client $client

# Sent and deleted items
Get-IMAPFolder -Client $client -Path 'Sent'
Get-IMAPMessage -Client $client
Get-IMAPFolder -Client $client -Path 'Deleted Items'
Get-IMAPMessage -Client $client

Listening for new IMAP mail

The ImapIdleListener class uses the IMAP IDLE command to raise events whenever new mail arrives. Create an instance with your connected ImapClient, subscribe to MessageArrived, and call StartAsync:

using var client = new ImapClient();
await client.ConnectAsync("imap.example.com", 993, SecureSocketOptions.SslOnConnect);
await client.AuthenticateAsync("user@example.com", "password");

var listener = new Mailozaurr.ImapIdleListener(client);
listener.MessageArrived += (s, msg) =>
    Console.WriteLine($"New message: {msg.Message.Subject}");
await listener.StartAsync();

Call Stop() to end listening. See Sources/Mailozaurr.Examples/ImapIdleListenerExample.cs for a full example.

Alternatively, use the PowerShell cmdlet Wait-IMAPMessage to output new messages directly to the pipeline:

$cred = Get-Credential
$client = Connect-IMAP -Server 'imap.example.com' -Credential $cred
Wait-IMAPMessage -Client $client -Until { $_.Message.From.Mailboxes.Address -contains 'alice@example.com' } -StopOnMatch -TimeoutSeconds 600 -Action { param($m) "New IMAP from Alice: $($m.Message.Subject)" }

Press Ctrl+C to stop waiting for messages.

The same concept applies to POP3, IMAP and Microsoft Graph mailboxes. Wait-POP3Message, Wait-IMAPMessage and Wait-GraphMessage all support -Until, -StopOnMatch and -TimeoutSeconds parameters so you can wait for specific senders or stop after a period of time:

$cred = Get-Credential
$graph = Connect-EmailGraph -Credential $cred
Wait-GraphMessage -Connection $graph -UserPrincipalName 'user@example.com' -Until { $_.from.emailAddress.address -eq 'alice@example.com' } -StopOnMatch -TimeoutSeconds 600 -Action {
    param($m)
    "Graph from Alice: $($m.subject)"
}
$cred = Get-Credential
$client = Connect-POP3 -Server 'pop.example.com' -Credential $cred
Wait-POP3Message -Client $client -Until { $_.Message.From.Mailboxes.Address -contains 'alice@example.com' } -StopOnMatch -TimeoutSeconds 600 -Action {
    param($m)
    "POP3 from Alice: $($m.Message.Subject)"
}

Using OpenPGP

PGP/MIME encryption allows securing messages using public and private keys. To sign and encrypt a message provide paths to the public and secret key files:

$pub = 'Examples/PGPKeys/mimekit.gpg.pub'
$sec = 'Examples/PGPKeys/mimekit.gpg.sec'
Send-EmailMessage -From 'mimekit@example.com' -To 'mimekit@example.com' \ 
    -Server 'smtp.example.com' -Port 25 -Body 'Test' -Subject 'Test' \ 
    -SignOrEncrypt PgpSignAndEncrypt -PublicKeyPath $pub -PrivateKeyPath $sec \ 
    -PrivateKeyPassword 'no.secret'

Documentation

While I didn't spent much time creating WIKI, working on Get-Help documentation, I did write blog articles that should help you get started.

You can also utilize Examples which should help to understand use cases. Of course it would be great having pretty help so if you can help me out feel free to submit PR's.

-Some useful examples:

  • Examples/Example-AcquireO365TokenInteractive.ps1 – demonstrates Connect-OAuthO365, ConvertFrom-OAuth2Credential, and using the token with Send-EmailMessage, IMAP, and POP3.
  • Examples/Example-AcquireGoogleTokenInteractive.ps1 – demonstrates Connect-OAuthGoogle, ConvertFrom-OAuth2Credential, and using the token with Send-EmailMessage, IMAP, and POP3.
  • Sources/Mailozaurr.Examples/AcquireO365TokenInteractive.cs – C# sample for OAuthHelpers.AcquireO365TokenInteractiveAsync.
  • Sources/Mailozaurr.Examples/AcquireGoogleTokenInteractive.cs – C# sample for OAuthHelpers.AcquireGoogleTokenInteractiveAsync.
  • Sources/Mailozaurr.Examples/SendEmailAttachments.cs – C# sample demonstrating attachments and inline resources.

Choosing between -Graph and -MgGraphRequest

The module supports two ways of calling Microsoft Graph. Use -Graph when you connect with Connect-EmailGraph and provide credentials created with ConvertTo-GraphCredential or ConvertTo-GraphCertificateCredential. The -MgGraphRequest switch is meant for scenarios where you authenticate through the Microsoft Graph PowerShell SDK using Connect-MgGraph.

Parameter Connect command When to use
-Graph Connect-EmailGraph Application or certificate authentication handled by Mailozaurr.
-MgGraphRequest Connect-MgGraph Already authenticated via the Microsoft Graph PowerShell SDK.

Example using -Graph

$cred = ConvertTo-GraphCredential -ClientId $ClientId -ClientSecret $ClientSecret -DirectoryId $TenantId
Connect-EmailGraph -Credential $cred
Send-EmailMessage -From 'user@example.com' -To 'user@example.com' -Subject 'Graph Test' -Graph
Disconnect-EmailGraph

Example using -MgGraphRequest

Import-Module Microsoft.Graph.Authentication
Connect-MgGraph -Scopes Mail.Send -NoWelcome
Send-EmailMessage -From 'user@example.com' -To 'user@example.com' -Subject 'Graph Test' -MgGraphRequest

Filtering Graph messages

Get-EmailGraphMessage supports the -Filter parameter for raw OData queries. This value is passed directly to Microsoft Graph's $filter option.

Get-EmailGraphMessage -UserPrincipalName 'user@example.com' -Filter "receivedDateTime ge 2024-01-01T00:00:00Z and contains(subject,'Invoice')"

See the Microsoft Graph query parameters documentation for details.

Keep in mind PSSharedGoods is only required for development. When you use this module from PowerShellGallery it's not installed as everything is merged.

SMTP connection pooling

You can reuse SMTP connections by enabling the connection pool with the -UseConnectionPool switch of Send-EmailMessage. The -ConnectionPoolSize parameter controls how many connections are kept alive. Use Test-SmtpConnection to examine the banner and capabilities and to check whether the connection remains open after a NOOP command. If the returned object has Persistent set to True, you can safely enable pooling. Call Clear-SmtpConnectionPool whenever you need to discard existing pooled clients.

Limiting access to mailboxes (Microsoft Graph API)

Microsoft Graph API requires Send.Mail permission to send emails. In some cases Mail.ReadWrite permission is also required when the size of email is above 4MB. If the application is registered in Azure AD (Entra ID) without any additional configuration, it will have access to all mailboxes in the organization. To limit access to specific mailboxes, you need to use Application Access Policy. This is a feature that allows you to limit access to specific mailboxes. You can read more about it here.

Following permissions (as shown on the screenshot) are required to send emails using Microsoft Graph API.

Microsoft Graph Permissions

The rest of the permissions is not required and is there for other features that Microsoft Graph provides.

To install

Install-Module -Name Mailozaurr -AllowClobber -Force

Force and AllowClobber aren't necessary, but they do skip errors in case some appear.

And to update

Update-Module -Name Mailozaurr

That's it. Whenever there's a new version, you run the command, and you can enjoy it. Remember that you may need to close, reopen PowerShell session if you have already used module before updating it.

The essential thing is if something works for you on production, keep using it till you test the new version on a test computer. I do changes that may not be big, but big enough that auto-update may break your code. For example, a small rename to a parameter, and your code stops working! Be responsible!

About

Mailozaurr is a PowerShell module that aims to provide SMTP, POP3, IMAP and probably some other ways to interact with Email. Underneath it uses MimeKit and MailKit libraries written by Jeffrey Stedfast.

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

  •  

Contributors 4

  •  
  •  
  •  
  •