Send-FileViaEmail.psm1

function Send-FileViaEmail ($file, $cfg, $contentType = "application/octet-stream", $bodyType) {

    $path = (resolve-path $file).path

    $tokenParams = @{
        "URI"    = "https://login.microsoftonline.com/{0}/oauth2/v2.0/token" -f $cfg.msgraph.tenant_id
        "Method" = "POST"
        "Body"   = @{
            client_id     = $cfg.msgraph.client_id
            scope         = "https://graph.microsoft.com/.default"
            client_secret = $cfg.msgraph.client_secret
            grant_type    = "client_credentials"
        }
    }
    $tokenresponse = Invoke-RestMethod @tokenParams

    $message = @{
        "subject"      = $cfg.mail.subject
        "toRecipients" = @(
            $cfg.mail.to | ForEach-Object {
                @{
                    "emailAddress" = @{"address" = $_ }
                }
            }
        )
    }
    # bodyType (Html or Text) sends the file's text as the message itself, with no attachment
    if ($bodyType) {
        $message.body = @{
            "contentType" = $bodyType
            "content"     = [system.io.file]::readalltext($path)
        }
    }
    else {
        $message.attachments = @(
            @{
                "@odata.type"  = "#microsoft.graph.fileAttachment"
                "name"         = $file
                "contentType"  = $contentType
                "contentBytes" = [convert]::ToBase64String( [system.io.file]::readallbytes($path) )
            })
    }

    $emailParams = @{
        "URI"         = "https://graph.microsoft.com/v1.0/users/{0}/sendMail" -f $cfg.mail.from
        "Headers"     = @{
            'Content-Type'  = "application\json"
            'Authorization' = "Bearer {0}" -f $tokenresponse.access_token
        }
        "Method"      = "POST"
        "ContentType" = 'application/json'
        "Body"        = (@{ "message" = $message }) | ConvertTo-JSON -Depth 6
    }

    Invoke-RestMethod @emailParams
}
Export-ModuleMember -Function Send-FileViaEmail