mailslurp-examples - powershell-imap-smtp

https://github.com/mailslurp/examples

Table of Contents

powershell-imap-smtp/smtp-mailkit.ps1

#!/usr/bin/env pwsh
. .\_helpers.ps1
$scriptPath = Split-Path -Path $script:MyInvocation.MyCommand.Definition -Parent
$apiKey = $env:API_KEY

Load-EnvironmentVariables -filePath ".\.env.inbox"
LoadMailKit($scriptPath)

# assert $env:SMTP_USERNAME and $env:SMTP_PASSWORD are set
if (-not $env:SMTP_USERNAME -or -not $env:SMTP_PASSWORD) {
    Write-Host "Please set SMTP_USERNAME and SMTP_PASSWORD environment variables."
    exit 1
}

# Create a new SMTP inbox and parse JSON response
$response = Invoke-RestMethod -Method Post -Uri "https://api.mailslurp.com/inboxes?inboxType=SMTP_INBOX" -Headers @{ "x-api-key" = $apiKey }
$inboxId = $response.id
$emailAddress = $response.emailAddress

# Set up email parameters
$emailAddress = $emailAddress
$senderAddress = $emailAddress
$recipientName = "Recipient"
$senderName = "Sender name"
$subject = "Test Email from PowerShell"
$body = "This is a test email sent from PowerShell using MailKit/MimeKit."

#<gen>pswh_mailkit_smtp_message
# Create a new MimeMessage
$message = New-Object MimeKit.MimeMessage

# Add sender and recipient
$message.From.Add([MimeKit.MailboxAddress]::new($senderName, $senderAddress))
$message.To.Add([MimeKit.MailboxAddress]::new($recipientName, $emailAddress))

# Set the subject and body
$message.Subject = $subject
$message.Body = [MimeKit.TextPart]::new("plain")
$message.Body.Text = $body
#</gen>

#<gen>pswh_mailkit_smtp_send
# Connect to the SMTP server
$smtpClient = New-Object MailKit.Net.Smtp.SmtpClient
$smtpClient.Connect("mxslurp.click", 2525)

# If authentication is required, provide credentials
$smtpClient.Authenticate([System.Text.Encoding]::UTF8, $env:SMTP_USERNAME, $env:SMTP_PASSWORD)

# Send the message
$smtpClient.Send($message)
$smtpClient.Disconnect($true)
#</gen>

powershell-imap-smtp/imap-mailkit.ps1

#!/usr/bin/env pwsh
# Now load MailKit
. .\_helpers.ps1
$scriptPath = Split-Path -Path $script:MyInvocation.MyCommand.Definition -Parent

LoadMailKit($scriptPath)

try
{
    New-Object MailKit.Net.Imap.ImapClient
    Write-Host "MailKit is loaded properly. ImapClient instance created successfully."
}
catch
{
    Write-Error "Failed to create ImapClient instance. MailKit may not be loaded properly: $_"
}

$apiKey = $env:API_KEY

# Create a new SMTP inbox and parse JSON response
$response = Invoke-RestMethod -Method Post -Uri "https://api.mailslurp.com/inboxes?inboxType=SMTP_INBOX" -Headers @{ "x-api-key" = $apiKey }
$inboxId = $response.id
$emailAddress = $response.emailAddress

Write-Host "Sending email from $inboxId to $emailAddress"
Invoke-RestMethod -Method Post -Uri "https://api.mailslurp.com/sendEmailQuery?inboxId=$inboxId&to=$emailAddress&subject=test" -Headers @{ "x-api-key" = $apiKey }
Write-Host "Waiting for email in inbox $inboxId"
Invoke-RestMethod -Method Get -Uri "https://api.mailslurp.com/waitForLatestEmail?inboxId=$inboxId" -Headers @{ "x-api-key" = $apiKey }

# Fetch environment variables for inbox and account access
Invoke-RestMethod -Method Get -Uri "https://api.mailslurp.com/inboxes/imap-smtp-access/env?inboxId=$inboxId" -Headers @{ "x-api-key" = $apiKey } -OutFile ".env.inbox"
Invoke-RestMethod -Method Get -Uri "https://api.mailslurp.com/inboxes/imap-smtp-access/env" -Headers @{ "x-api-key" = $apiKey } -OutFile ".env.account"

# Load environment variables from downloaded files
Load-EnvironmentVariables -filePath ".\.env.inbox"
Write-Host "Connect insecure"

#<gen>mailkit_connect_insecure
$client = New-Object MailKit.Net.Imap.ImapClient
$client.ServerCertificateValidationCallback = { $true }
$client.Connect("mailslurp.click", 1143, [MailKit.Security.SecureSocketOptions]::None)
$client.Authenticate($env:IMAP_USERNAME, $env:IMAP_PASSWORD)
#</gen>

# Fetch and list all messages' headers
#<gen>mailkit_select
$client.Inbox.Open([MailKit.FolderAccess]::ReadOnly)
Write-Host "Total messages: $( $client.Inbox.Count )"
#</gen>

#<gen>mailkit_fetch_messages
$fetchRequest = New-Object MailKit.FetchRequest
$messages = $client.Inbox.Fetch(0, -1, $fetchRequest)
foreach ($message in $messages)
{
    $from = $message.Envelope.From.ToString()
    $subject = $message.Envelope.Subject
    Write-Host "From: $from Subject: $subject"
}
#</gen>

# Search for unseen messages
#<gen>mailkit_search_search_unseen
$client.Inbox.Open([MailKit.FolderAccess]::ReadOnly)
$unseenIds = $client.Inbox.Search([MailKit.Search.SearchQuery]::NotSeen)
Write-Host "Unseen IDs: $unseenIds"
#</gen>

$client.Disconnect($true)

powershell-imap-smtp/_helpers.ps1

[console]::TreatControlCAsInput = $false
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
function ErrorHandling
{
    Write-Host "ERROR occurred"
    exit 1
}
trap
{
    ErrorHandling
}
function Load-EnvironmentVariables
{
    param(
        [string]$filePath
    )

    if (-Not (Test-Path $filePath))
    {
        Write-Error "File not found: $filePath"
        return
    }

    Get-Content $filePath | ForEach-Object {
        $keyValue = $_.Split('=', 2)
        if ($keyValue.Count -eq 2)
        {
            $envName = $keyValue[0].Trim()
            $envValue = $keyValue[1].Trim()

            # Remove leading and trailing double quotes from the value
            if ($envValue.StartsWith('"') -and $envValue.EndsWith('"'))
            {
                $envValue = $envValue.Substring(1, $envValue.Length - 2)
            }

            [Environment]::SetEnvironmentVariable($envName, $envValue, [System.EnvironmentVariableTarget]::Process)
            Write-Host "Set $envName = ***"
        }
    }
}

function LoadMailKit($scriptPath)
{
    # Function to download and extract packages
    function DownloadAndExtractPackage($packageName, $packageVersion)
    {
        $packageUrl = "https://www.nuget.org/api/v2/package/$packageName/$packageVersion"
        $downloadPath = Join-Path -Path $scriptPath -ChildPath "$packageName.$packageVersion.nupkg"
        $zipPath = Join-Path -Path $scriptPath -ChildPath "$packageName.$packageVersion.zip"
        $extractPath = Join-Path -Path $scriptPath -ChildPath "$packageName.$packageVersion"
        $dllPath = Join-Path -Path $extractPath "lib\netstandard2.0\$packageName.dll"  # Adjust the path if necessary

        # Check if the extracted DLL already exists
        if (Test-Path $dllPath)
        {
            Write-Host "$packageName DLL already exists at $dllPath. Skipping download and extraction."
            return $extractPath
        }
        Write-Host "Downloading $packageName package..."
        Invoke-WebRequest -Uri $packageUrl -OutFile $downloadPath

        Rename-Item -Path $downloadPath -NewName $zipPath
        Write-Host "Extracting $packageName package..."
        Expand-Archive -Path $zipPath -DestinationPath $extractPath -Force

        Remove-Item -Path $zipPath
        return $extractPath
    }

    # Download and extract MimeKit and MailKit
    $mimeKitPath = DownloadAndExtractPackage "MimeKit" "4.5.0"  # Ensure you have the right version
    $mailKitPath = DownloadAndExtractPackage "MailKit" "4.5.0"  # Ensure you have the right version

    # Load MimeKit DLL
    $mimeKitDllPath = Join-Path -Path $mimeKitPath "lib\netstandard2.0\MimeKit.dll"
    if (Test-Path $mimeKitDllPath)
    {
        Add-Type -Path $mimeKitDllPath
        Write-Host "MimeKit has been loaded successfully."
    }
    else
    {
        Write-Error "MimeKit DLL not found in the expected location."
    }

    # Load MailKit DLL
    $mailKitDllPath = Join-Path -Path $mailKitPath "lib\netstandard2.0\MailKit.dll"
    if (Test-Path $mailKitDllPath)
    {
        Add-Type -Path $mailKitDllPath
        Write-Host "MailKit has been loaded successfully and is ready to use!"
    }
    else
    {
        Write-Error "MailKit DLL not found in the expected location."
    }
}

powershell-imap-smtp/README.md

# Powershell IMAP and SMTP examples using MailKit/MimeKit
Ensure you have the [`MailKit`](https://www.nuget.org/packages/MailKit/) and [`MimeKit`](https://www.nuget.org/packages/MimeKit/) libraries installed. You can install them using the `NuGet` package manager.

Then ensure you have a MailSlurp API_KEY variable set. You can get one from the [MailSlurp dashboard](https://app.mailslurp.com).

```ps1
$env:API_KEY = "your-api-key"
```

Then run the examples:

```ps1
./imap-mailkit.ps1
./smtp-mailkit.ps1
```

powershell-imap-smtp/Makefile

-include ../.env

test:
	API_KEY=$(API_KEY) pwsh imap-mailkit.ps1