O365 – enable save in mailbox for delegates

See https://docs.microsoft.com/en-us/exchange/troubleshoot/user-and-shared-mailboxes/sent-mail-is-not-saved

Connect to Exchange-Online (Office 365) and set mailbox-features for single mailbox with option to update all mailboxes

# Set execution policy for this process only
Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned

# Define variables
$UserPrincipalName = "admin@example.onmicrosoft.com"
$Mailbox = "office@example.com"
$RunForAllMailboxes = "N" # Default value

# Function to check and log mailbox actions
Function Log-MailboxAction {
    Param (
        [string]$LogPath,
        [string]$Message
    )
    if (!(Test-Path $LogPath)) {
        New-Item -ItemType Directory -Path $LogPath -Force
    }
    Add-Content -Path "$LogPath\${FQDN}_mailbox_set_sent_on_behalf.log" -Value $Message
}

# Validate UserPrincipalName and Mailbox
if ($UserPrincipalName -eq "admin@example.onmicrosoft.com" -or $Mailbox -eq "office@example.com") {
    Write-Error "Error 500 - you are using the variables from the template. Edit them before using :)"
    Start-Sleep -Seconds 60
    exit
}

# Determine FQDN from UserPrincipalName for logging
$FQDN = $UserPrincipalName.Split('@')[1]
$LogPath = "C:\temp"

# Check if ExchangeOnlineManagement module is installed
if (-not (Get-Module -ListAvailable -Name ExchangeOnlineManagement)) {
    Install-Module -Name ExchangeOnlineManagement
} else {
    Update-Module -Name ExchangeOnlineManagement
}

Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -UserPrincipalName $UserPrincipalName

if ($RunForAllMailboxes -eq "Y") {
    # Log and update all mailboxes
    Get-Mailbox | Where-Object { $_.MessageCopyForSentAsEnabled -eq $null } | ForEach-Object {
        Set-Mailbox -Identity $_.Identity -MessageCopyForSendOnBehalfEnabled $true -MessageCopyForSentAsEnabled $true
        Log-MailboxAction -LogPath $LogPath -Message "Updated: $($_.Identity)"
    }
} else {
    # Check if single mailbox is valid
    $validMailbox = Get-Mailbox -Identity $Mailbox -ErrorAction SilentlyContinue
    if ($null -eq $validMailbox) {
        Write-Error "Error 500 - Not a valid mailbox"
        Start-Sleep -Seconds 60
        exit
    } else {
        Set-Mailbox -Identity $Mailbox -MessageCopyForSendOnBehalfEnabled $true -MessageCopyForSentAsEnabled $true
        Log-MailboxAction -LogPath $LogPath -Message "Updated: $Mailbox"
    }
}

Disconnect-ExchangeOnline

Leave a Reply

Your email address will not be published. Required fields are marked *