{"id":21145344,"url":"https://github.com/jsa2/msgraphmail","last_synced_at":"2025-03-14T13:42:34.502Z","repository":{"id":65651416,"uuid":"410990985","full_name":"jsa2/MSGraphMail","owner":"jsa2","description":null,"archived":false,"fork":false,"pushed_at":"2022-12-03T08:26:17.000Z","size":42,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-01-21T07:27:16.086Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jsa2.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-09-27T18:02:35.000Z","updated_at":"2023-02-02T13:45:34.000Z","dependencies_parsed_at":"2023-02-02T14:25:10.835Z","dependency_job_id":null,"html_url":"https://github.com/jsa2/MSGraphMail","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsa2%2FMSGraphMail","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsa2%2FMSGraphMail/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsa2%2FMSGraphMail/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsa2%2FMSGraphMail/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jsa2","download_url":"https://codeload.github.com/jsa2/MSGraphMail/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243589255,"owners_count":20315467,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-20T08:39:37.327Z","updated_at":"2025-03-14T13:42:34.478Z","avatar_url":"https://github.com/jsa2.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Azure Functions  - HTTP mail service based on Graph API \r\n\r\n## Solution description\r\nAn implementation of Graph API  [**Send mail**](https://docs.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0\u0026tabs=http)\r\n\r\nCreates Azure Function based mail service using Graph API with managed identity\r\n- Uses permission Mail.Send for the Azure Function \r\n- Primary Use case is to provide **centralized** simple MAIL API to clients that don't integrate directly with Graph API \r\n\r\n**Example use case:**\r\nProvide REST API endpoint for function to send notifications.\r\n\r\n\r\n___\r\n\r\n## Disclaimer\r\nRead [License](#license)\r\n\r\nNot designed for bulk commercial email. Read: [Sending limits @ Exchange online](https://docs.microsoft.com/en-us/office365/servicedescriptions/exchange-online-service-description/exchange-online-limits)\r\n![img](https://securecloud188323504.files.wordpress.com/2021/09/image-52.png)\r\n\r\n- For commercial bulk email use, see Sendgrid etc.\r\n\r\n___\r\n\r\n### Examples \r\n#### CURL\r\nSend email with CURL\r\n\r\n- \"From\" query param needs to be an actual Exchange Online mailbox\r\n\r\n**Simple_GET**\r\n```bash\r\ncurl \"https://fn-mailer-29375.azurewebsites.net/api/send?code=CODEHERE\u0026from=senderaddress@anyOffice365.com\u0026to=john.doe@example.com\u0026message=ThisIsmessage\u0026subject=Meetforlunch\"\r\n\r\n```\r\n**Advanced options _POST**\r\n- The solution also supports Graph Options for JSON payload as defined [here](https://docs.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0\u0026tabs=http#request)\r\n\r\n- \"From\" url parameter needs to be an actual Exchange Online mailbox\r\n\r\n```bash\r\nrecipient=\"joosua.santasalo@nixu.com\"\r\nuri=\"$mailSvc?code=$keys\u0026from=sendingaccount@thx138.onmicrosoft.com\"\r\nmsg=\"This function calling\"\r\n\r\ncurl --header \"Content-Type: application/json\" \\\r\n--request POST \\\r\n--data \"{\\\"message\\\":{\\\"subject\\\":\\\"Meet for lunch?\\\",\\\"body\\\":{\\\"contentType\\\":\\\"Text\\\",\\\"content\\\":\\\"$msg.\\\"},\\\"toRecipients\\\":[{\\\"emailAddress\\\":{\\\"address\\\":\\\"$recipient\\\"}}]},\\\"saveToSentItems\\\":\\\"false\\\"}\" \\\r\n$uri\r\n```\r\n\r\n#### Powershell\r\n```Powershell\r\n  $data = @'\r\n  {\r\n      \"message\": {\r\n        \"subject\": \"Meet for lunch?\",\r\n        \"body\": {\r\n          \"contentType\": \"Text\",\r\n          \"content\": \"The new cafeteria is open.\"\r\n        },\r\n        \"toRecipients\": [\r\n          {\r\n            \"emailAddress\": {\r\n              \"address\": \"johndoe@example.com\"\r\n            }\r\n          }\r\n        ],\r\n      }\r\n      \"saveToSentItems\": \"false\"\r\n    }\r\n  '@\r\n$uri =\"https://fn-mailer-29375.azurewebsites.net/api/send?code=CODEHERE\u0026from=senderaddress@anyOffice365.com\"\r\nInvoke-RestMethod $uri -Method \"post\" -Body $data\r\n\r\n```\r\n\r\n\r\n## Table of contents\r\n- [Azure Functions  - HTTP mail service based on Graph API](#azure-functions----http-mail-service-based-on-graph-api)\r\n  - [Solution description](#solution-description)\r\n  - [Disclaimer](#disclaimer)\r\n    - [Examples](#examples)\r\n      - [CURL](#curl)\r\n      - [Powershell](#powershell)\r\n  - [Table of contents](#table-of-contents)\r\n  - [Hardening](#hardening)\r\n    - [Place IP limitations on the function](#place-ip-limitations-on-the-function)\r\n    - [Limit App Permissions](#limit-app-permissions)\r\n  - [Prerequisites](#prerequisites)\r\n  - [Installation script (AZ CLI)](#installation-script-az-cli)\r\n  - [Export the AppID for hardening](#export-the-appid-for-hardening)\r\n  - [Test the service after deployment](#test-the-service-after-deployment)\r\n  - [License](#license)\r\n\r\n  \r\n\r\n## Hardening\r\n\r\n### Place IP limitations on the function\r\n```bash\r\naz functionapp config access-restriction add --name $fnName \\\r\n--resource-group $rg \\\r\n--ip-address $IPRestriction \\\r\n--priority 1\r\n```\r\n### Limit App Permissions \r\nReferences and requirements:  [MS Docs - Configure ApplicationAccessPolicy](https://docs.microsoft.com/en-us/graph/auth-limit-mailbox-access#configure-applicationaccesspolicy)\r\n\r\nIt is recommended to set the permissions of the service principal to allow sending with only predefined accounts.\r\nFunction needs mail.send permissions, which is equivalent to typical SMTP permissions and can impersonate any user, unless hardened as per this recommendation.\r\n\r\n- Add the functions [AppID](#export-the-appid-for-hardening) and distrubutionGroupID used for scope limitations here\r\n- Ensure the group includes accounts you want the service can impersonate\r\n```powershell\r\nNew-ApplicationAccessPolicy -AppId \"aa2ad02d-b369-4d5e-95e6-f1391561ddce\" -PolicyScopeGroupId \"functionSenderAcc@thx138.onmicrosoft.com\" -AccessRight RestrictAccess -Description \"Restrict this app to members of distribution group EvenUsers.\"\r\n```\r\nIf you see error: ``The identity of the policy scope is not a security principal`` ensure, that the group was created with  ``New-DistributionGroup`` \r\n\r\n\r\n\r\n## Prerequisites \r\n\r\nRequirement | description | Install\r\n-|-|-\r\n✅ Bash shell script | Tested with WSL2 (Ubuntu) on Windows 10 | [CLI script](#cli-script)\r\n✅ [p7zip](https://www.7-zip.org/) | p7zip is  used to create the zip deployment package for package deployment | ``sudo apt-get install p7zip-full`` \r\n✅ AZCLI | Azure Services installation |``curl -sL https://aka.ms/InstallAzureCLIDeb \\| sudo bash``\r\n✅ Node.js runtime 14 | Used in Azure Function, and to create local function config |[install with NVM](https://github.com/nvm-sh/nvm#install--update-script)\r\n✅ Azure Function Core Tools and VScode with Azure Functions extension  | Only needed if project is initiated locally |[Install the Azure Functions Core Tools](https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=v3%2Clinux%2Ccsharp%2Cportal%2Cbash%2Ckeda#v2)\r\n\r\n\r\n## Installation script (AZ CLI)\r\nThe CLI script below will use current subscription context to setup the solution after user has performed authentication.\r\n\r\nEnsure you have selected a single subscription context\r\n``` AZ LOGIN; az account set --subscription {subscriptionID} ``` \r\n```shell\r\n#  https://docs.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0\u0026tabs=http\r\n\r\nnpm install\r\n#az login --use-device-code\r\n#az account set --subscription 78020cde-0dd8-4ac6-a6d4-21bac00fb343\r\n#Define starting variables\r\nrnd=$RANDOM\r\nfnName=fn-mailer-$rnd\r\nrg=RG-mailer-$rnd\r\nlocation=westeurope\r\n# You can ignore the warning \"command substitution: ignored null byte in input\"\r\nstorageAcc=storage$(shuf -zer -n10  {a..z})\r\n\r\n# Create Resource Group (retention tag is just example, based on another service)\r\naz group create -n $rg \\\r\n-l $location \\\r\n--tags \"svc=func\"\r\n\r\n# Create storageAcc Account \r\nsaId=$(az storage account create -n $storageAcc  -g $rg --kind storageV2 -l $location -t Account --sku Standard_LRS  -o tsv --query \"id\")\r\n\r\nsaConstring=$(az storage account show-connection-string -g $rg  -n  $storageAcc -o tsv --query \"connectionString\")\r\n\r\n## Create Function App\r\naz functionapp create \\\r\n--functions-version 3 \\\r\n--consumption-plan-location $location \\\r\n--name $fnName \\\r\n--os-type linux \\\r\n--resource-group $rg \\\r\n--runtime node \\\r\n--assign-identity \\\r\n--storage-account $storageAcc\r\n#\r\nsleep 10\r\n\r\n# Create Storage and graph Role Assignments\r\nid=$(az functionapp  show -g $rg -n $fnName -o tsv --query \"identity.principalId\")\r\n\r\n# Set to read-only, list variables here you want to be also part of cloud deployment\r\naz functionapp config appsettings set \\\r\n--name $fnName \\\r\n--resource-group $rg \\\r\n--settings WEBSITE_RUN_FROM_PACKAGE=1 \r\n\r\n# Sleep for the AAD propagation delay\r\nsleep 30\r\n## Create permissions for Graph\r\nGraphAppId=00000003-0000-0000-c000-000000000000\r\ngraphspn=$(az rest --method get --url \"https://graph.microsoft.com/v1.0/servicePrincipals?\\$search=\\\"appId:$GraphAppId\\\"\"\"\u0026\\$select=displayName,id\" --resource \"https://graph.microsoft.com\" --headers \"ConsistencyLevel=eventual\" -o tsv --query 'value' |cut -f2)\r\n\r\naz rest --method post --url \"https://graph.microsoft.com/v1.0/servicePrincipals/$id/appRoleAssignments\" --resource \"https://graph.microsoft.com\" \\\r\n--body \"{\\\"principalId\\\": \\\"$id\\\",\\\"resourceId\\\": \\\"$graphspn\\\",\\\"appRoleId\\\": \\\"b633e1c5-b582-4048-a93e-9f11b44c7e96\\\"}\" \r\n\r\n#Create ZIP package \r\n7z a -tzip deploy.zip . -r -mx0 -xr\\!*.git -xr\\!*.vscode \r\n\r\n# Force triggers by deployment and restarts\r\nunset mailSvc\r\ni=0\r\nwhile [ -z \"$mailSvc\" ] ; do\r\n((i++))\r\necho \"attempting to sync triggers $i/6\"\r\naz functionapp deployment source config-zip -g $rg -n $fnName --src deploy.zip\r\nsleep 5\r\naz functionapp restart --name $fnName --resource-group $rg \r\nsleep 20\r\nkeys=$(az functionapp keys list -g $rg -n $fnName -o tsv --query functionKeys) \r\nmailSvc=$(az functionapp function show -g $rg -n $fnName --function-name send -o tsv --query invokeUrlTemplate)\r\necho \"looking for template $mailSvc\"\r\necho \"$mailSvc\"\r\n if [[ $i -eq 6 ]]; then\r\n    break  \r\n    fi\r\ndone\r\n\r\necho uri=\"$mailSvc?code=$keys\u0026from=sendingaccount@thx138.onmicrosoft.com\" \u003e mailservice.txt\r\n\r\n#\r\nrm deploy.zip\r\n```\r\n\r\n**The examples below uses variables declared in the deployment script. If you have new shell session insert the values manually**\r\n## Export the AppID for hardening\r\n```bash\r\nmailFunctionAppId=$(az rest --method get --url https://graph.microsoft.com/v1.0/servicePrincipals/$id --resource \"https://graph.microsoft.com\" -o tsv --query \"appId\")\r\n```\r\n\r\n## Test the service after deployment\r\n**The example below uses variables declared in the deployment script. If you have new shell session insert the values manually**\r\n```bash\r\n\r\nrecipient=\"shantic@thx.dewi.red\"\r\nuri=\"$mailSvc?code=$keys\u0026from=joosua@thx138.onmicrosoft.com\"\r\nmsg=\"This function calling\"\r\n\r\ncurl --header \"Content-Type: application/json\" \\\r\n--request POST \\\r\n--data \"{\\\"message\\\":{\\\"subject\\\":\\\"Meet for lunch?\\\",\\\"body\\\":{\\\"contentType\\\":\\\"Text\\\",\\\"content\\\":\\\"$msg.\\\"},\\\"toRecipients\\\":[{\\\"emailAddress\\\":{\\\"address\\\":\\\"$recipient\\\"}}]},\\\"saveToSentItems\\\":\\\"false\\\"}\" \\\r\n$uri\r\n\r\naz group delete \\\r\n--resource-group $rg \r\n```\r\n\r\n## License\r\nCopyright 2021 Joosua Santasalo\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjsa2%2Fmsgraphmail","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjsa2%2Fmsgraphmail","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjsa2%2Fmsgraphmail/lists"}