We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
c7n-mailer - azure functions error when using SendGrid
Using a simple policy to queue a notification from the example [here](https://cloudcustodian.io/docs/tools/c7n-mailer.html#using-on-azure).

I see the following two errors:

1. Default Template
```
Invalid template reference default.j2
default.j2
```

2. Fetching contents of an object
```
local variable 'bpayload' referenced before assignment
Traceback (most recent call last):
  File "/home/site/wwwroot/c7n_mailer/azure_mailer/sendgrid_delivery.py", line 129, in _sendgrid_mail_from_email_message
    body = message.get_content()
AttributeError: 'MIMEText' object has no attribute 'get_content'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/site/wwwroot/c7n_mailer/azure_mailer/azure_queue_processor.py", line 137, in _deliver_email
    return sendgrid_delivery.sendgrid_handler(queue_message, email_messages)
  File "/home/site/wwwroot/c7n_mailer/azure_mailer/sendgrid_delivery.py", line 92, in sendgrid_handler
    mail = SendGridDelivery._sendgrid_mail_from_email_message(message)
  File "/home/site/wwwroot/c7n_mailer/azure_mailer/sendgrid_delivery.py", line 132, in _sendgrid_mail_from_email_message
    body = message.get_payload(decode=True).decode('utf-8')
  File "/usr/local/lib/python3.6/email/message.py", line 286, in get_payload
    value, defects = decode_b(b''.join(bpayload.splitlines()))
UnboundLocalError: local variable 'bpayload' referenced before assignment
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `tools/c7n_mailer/c7n_mailer/azure_mailer/deploy.py`
Content:
```
1 # Copyright 2016-2017 Capital One Services, LLC
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 from __future__ import (absolute_import, division, print_function,
15                         unicode_literals)
16 
17 import copy
18 import json
19 import logging
20 import os
21 
22 try:
23     from c7n_azure.function_package import FunctionPackage
24     from c7n_azure.functionapp_utils import FunctionAppUtilities
25     from c7n_azure.policy import AzureFunctionMode
26     from c7n_azure.session import Session
27     from c7n_azure.utils import StringUtils
28     from c7n.utils import local_session
29 except ImportError:
30     FunctionPackage = None
31     pass
32 
33 
34 def cache_path():
35     return os.path.join(os.path.dirname(__file__), 'cache')
36 
37 
38 def build_function_package(config, function_name, sub_id):
39     schedule = config.get('function_schedule', '0 */10 * * * *')
40 
41     cache_override_path = cache_path()
42 
43     function_path = function_name + "_" + sub_id
44 
45     # Build package
46     package = FunctionPackage(
47         function_name,
48         os.path.join(os.path.dirname(__file__), 'function.py'),
49         target_sub_ids=[sub_id],
50         cache_override_path=cache_override_path)
51 
52     package.build(None,
53                   modules=['c7n', 'c7n-azure', 'c7n-mailer'],
54                   non_binary_packages=['pyyaml', 'pycparser', 'tabulate', 'jmespath',
55                                        'datadog', 'MarkupSafe', 'simplejson', 'pyrsistent'],
56                   excluded_packages=['azure-cli-core', 'distlib', 'future', 'futures'])
57 
58     package.pkg.add_contents(
59         function_path + '/function.json',
60         contents=package.get_function_config({'mode':
61                                               {'type': 'azure-periodic',
62                                                'schedule': schedule}}))
63 
64     # Add mail templates
65     for d in set(config['templates_folders']):
66         if not os.path.exists(d):
67             continue
68         for t in [f for f in os.listdir(d) if os.path.splitext(f)[1] == '.j2']:
69             with open(os.path.join(d, t)) as fh:
70                 package.pkg.add_contents(function_path + '/msg-templates/%s' % t, fh.read())
71 
72     function_config = copy.deepcopy(config)
73     function_config['templates_folders'] = [function_path + '/msg-templates/']
74     package.pkg.add_contents(
75         function_path + '/config.json',
76         contents=json.dumps(function_config))
77 
78     package.close()
79     return package
80 
81 
82 def provision(config):
83     log = logging.getLogger('c7n_mailer.azure.deploy')
84 
85     function_name = config.get('function_name', 'mailer')
86     function_properties = config.get('function_properties', {})
87 
88     # service plan is parse first, because its location might be shared with storage & insights
89     service_plan = AzureFunctionMode.extract_properties(function_properties,
90                                                 'servicePlan',
91                                                 {
92                                                     'name': 'cloud-custodian',
93                                                     'location': 'eastus',
94                                                     'resource_group_name': 'cloud-custodian',
95                                                     'sku_tier': 'Dynamic',  # consumption plan
96                                                     'sku_name': 'Y1'
97                                                 })
98 
99     location = service_plan.get('location', 'eastus')
100     rg_name = service_plan['resource_group_name']
101 
102     sub_id = local_session(Session).get_subscription_id()
103     suffix = StringUtils.naming_hash(rg_name + sub_id)
104 
105     storage_account = AzureFunctionMode.extract_properties(function_properties,
106                                                     'storageAccount',
107                                                     {'name': 'mailerstorage' + suffix,
108                                                      'location': location,
109                                                      'resource_group_name': rg_name})
110 
111     app_insights = AzureFunctionMode.extract_properties(function_properties,
112                                                     'appInsights',
113                                                     {'name': service_plan['name'],
114                                                      'location': location,
115                                                      'resource_group_name': rg_name})
116 
117     function_app_name = FunctionAppUtilities.get_function_name(
118         '-'.join([service_plan['name'], function_name]), suffix)
119     FunctionAppUtilities.validate_function_name(function_app_name)
120 
121     params = FunctionAppUtilities.FunctionAppInfrastructureParameters(
122         app_insights=app_insights,
123         service_plan=service_plan,
124         storage_account=storage_account,
125         function_app_resource_group_name=service_plan['resource_group_name'],
126         function_app_name=function_app_name)
127 
128     FunctionAppUtilities.deploy_function_app(params)
129 
130     log.info("Building function package for %s" % function_app_name)
131     package = build_function_package(config, function_name, sub_id)
132 
133     log.info("Function package built, size is %dMB" % (package.pkg.size / (1024 * 1024)))
134 
135     FunctionAppUtilities.publish_functions_package(params, package)
136
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/tools/c7n_mailer/c7n_mailer/azure_mailer/deploy.py b/tools/c7n_mailer/c7n_mailer/azure_mailer/deploy.py
--- a/tools/c7n_mailer/c7n_mailer/azure_mailer/deploy.py
+++ b/tools/c7n_mailer/c7n_mailer/azure_mailer/deploy.py
@@ -70,7 +70,10 @@
                 package.pkg.add_contents(function_path + '/msg-templates/%s' % t, fh.read())
 
     function_config = copy.deepcopy(config)
-    function_config['templates_folders'] = [function_path + '/msg-templates/']
+
+    functions_full_template_path = '/home/site/wwwroot/' + function_path + '/msg-templates/'
+    function_config['templates_folders'] = [functions_full_template_path]
+
     package.pkg.add_contents(
         function_path + '/config.json',
         contents=json.dumps(function_config))

{"golden_diff": "diff --git a/tools/c7n_mailer/c7n_mailer/azure_mailer/deploy.py b/tools/c7n_mailer/c7n_mailer/azure_mailer/deploy.py\n--- a/tools/c7n_mailer/c7n_mailer/azure_mailer/deploy.py\n+++ b/tools/c7n_mailer/c7n_mailer/azure_mailer/deploy.py\n@@ -70,7 +70,10 @@\n                 package.pkg.add_contents(function_path + '/msg-templates/%s' % t, fh.read())\n \n     function_config = copy.deepcopy(config)\n-    function_config['templates_folders'] = [function_path + '/msg-templates/']\n+\n+    functions_full_template_path = '/home/site/wwwroot/' + function_path + '/msg-templates/'\n+    function_config['templates_folders'] = [functions_full_template_path]\n+\n     package.pkg.add_contents(\n         function_path + '/config.json',\n         contents=json.dumps(function_config))\n", "issue": "c7n-mailer - azure functions error when using SendGrid\nUsing a simple policy to queue a notification from the example [here](https://cloudcustodian.io/docs/tools/c7n-mailer.html#using-on-azure).\r\n\r\nI see the following two errors:\r\n\r\n1. Default Template\r\n```\r\nInvalid template reference default.j2\r\ndefault.j2\r\n```\r\n\r\n2. Fetching contents of an object\r\n```\r\nlocal variable 'bpayload' referenced before assignment\r\nTraceback (most recent call last):\r\n  File \"/home/site/wwwroot/c7n_mailer/azure_mailer/sendgrid_delivery.py\", line 129, in _sendgrid_mail_from_email_message\r\n    body = message.get_content()\r\nAttributeError: 'MIMEText' object has no attribute 'get_content'\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n  File \"/home/site/wwwroot/c7n_mailer/azure_mailer/azure_queue_processor.py\", line 137, in _deliver_email\r\n    return sendgrid_delivery.sendgrid_handler(queue_message, email_messages)\r\n  File \"/home/site/wwwroot/c7n_mailer/azure_mailer/sendgrid_delivery.py\", line 92, in sendgrid_handler\r\n    mail = SendGridDelivery._sendgrid_mail_from_email_message(message)\r\n  File \"/home/site/wwwroot/c7n_mailer/azure_mailer/sendgrid_delivery.py\", line 132, in _sendgrid_mail_from_email_message\r\n    body = message.get_payload(decode=True).decode('utf-8')\r\n  File \"/usr/local/lib/python3.6/email/message.py\", line 286, in get_payload\r\n    value, defects = decode_b(b''.join(bpayload.splitlines()))\r\nUnboundLocalError: local variable 'bpayload' referenced before assignment\r\n```\n", "before_files": [{"content": "# Copyright 2016-2017 Capital One Services, LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom __future__ import (absolute_import, division, print_function,\n                        unicode_literals)\n\nimport copy\nimport json\nimport logging\nimport os\n\ntry:\n    from c7n_azure.function_package import FunctionPackage\n    from c7n_azure.functionapp_utils import FunctionAppUtilities\n    from c7n_azure.policy import AzureFunctionMode\n    from c7n_azure.session import Session\n    from c7n_azure.utils import StringUtils\n    from c7n.utils import local_session\nexcept ImportError:\n    FunctionPackage = None\n    pass\n\n\ndef cache_path():\n    return os.path.join(os.path.dirname(__file__), 'cache')\n\n\ndef build_function_package(config, function_name, sub_id):\n    schedule = config.get('function_schedule', '0 */10 * * * *')\n\n    cache_override_path = cache_path()\n\n    function_path = function_name + \"_\" + sub_id\n\n    # Build package\n    package = FunctionPackage(\n        function_name,\n        os.path.join(os.path.dirname(__file__), 'function.py'),\n        target_sub_ids=[sub_id],\n        cache_override_path=cache_override_path)\n\n    package.build(None,\n                  modules=['c7n', 'c7n-azure', 'c7n-mailer'],\n                  non_binary_packages=['pyyaml', 'pycparser', 'tabulate', 'jmespath',\n                                       'datadog', 'MarkupSafe', 'simplejson', 'pyrsistent'],\n                  excluded_packages=['azure-cli-core', 'distlib', 'future', 'futures'])\n\n    package.pkg.add_contents(\n        function_path + '/function.json',\n        contents=package.get_function_config({'mode':\n                                              {'type': 'azure-periodic',\n                                               'schedule': schedule}}))\n\n    # Add mail templates\n    for d in set(config['templates_folders']):\n        if not os.path.exists(d):\n            continue\n        for t in [f for f in os.listdir(d) if os.path.splitext(f)[1] == '.j2']:\n            with open(os.path.join(d, t)) as fh:\n                package.pkg.add_contents(function_path + '/msg-templates/%s' % t, fh.read())\n\n    function_config = copy.deepcopy(config)\n    function_config['templates_folders'] = [function_path + '/msg-templates/']\n    package.pkg.add_contents(\n        function_path + '/config.json',\n        contents=json.dumps(function_config))\n\n    package.close()\n    return package\n\n\ndef provision(config):\n    log = logging.getLogger('c7n_mailer.azure.deploy')\n\n    function_name = config.get('function_name', 'mailer')\n    function_properties = config.get('function_properties', {})\n\n    # service plan is parse first, because its location might be shared with storage & insights\n    service_plan = AzureFunctionMode.extract_properties(function_properties,\n                                                'servicePlan',\n                                                {\n                                                    'name': 'cloud-custodian',\n                                                    'location': 'eastus',\n                                                    'resource_group_name': 'cloud-custodian',\n                                                    'sku_tier': 'Dynamic',  # consumption plan\n                                                    'sku_name': 'Y1'\n                                                })\n\n    location = service_plan.get('location', 'eastus')\n    rg_name = service_plan['resource_group_name']\n\n    sub_id = local_session(Session).get_subscription_id()\n    suffix = StringUtils.naming_hash(rg_name + sub_id)\n\n    storage_account = AzureFunctionMode.extract_properties(function_properties,\n                                                    'storageAccount',\n                                                    {'name': 'mailerstorage' + suffix,\n                                                     'location': location,\n                                                     'resource_group_name': rg_name})\n\n    app_insights = AzureFunctionMode.extract_properties(function_properties,\n                                                    'appInsights',\n                                                    {'name': service_plan['name'],\n                                                     'location': location,\n                                                     'resource_group_name': rg_name})\n\n    function_app_name = FunctionAppUtilities.get_function_name(\n        '-'.join([service_plan['name'], function_name]), suffix)\n    FunctionAppUtilities.validate_function_name(function_app_name)\n\n    params = FunctionAppUtilities.FunctionAppInfrastructureParameters(\n        app_insights=app_insights,\n        service_plan=service_plan,\n        storage_account=storage_account,\n        function_app_resource_group_name=service_plan['resource_group_name'],\n        function_app_name=function_app_name)\n\n    FunctionAppUtilities.deploy_function_app(params)\n\n    log.info(\"Building function package for %s\" % function_app_name)\n    package = build_function_package(config, function_name, sub_id)\n\n    log.info(\"Function package built, size is %dMB\" % (package.pkg.size / (1024 * 1024)))\n\n    FunctionAppUtilities.publish_functions_package(params, package)\n", "path": "tools/c7n_mailer/c7n_mailer/azure_mailer/deploy.py"}], "after_files": [{"content": "# Copyright 2016-2017 Capital One Services, LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom __future__ import (absolute_import, division, print_function,\n                        unicode_literals)\n\nimport copy\nimport json\nimport logging\nimport os\n\ntry:\n    from c7n_azure.function_package import FunctionPackage\n    from c7n_azure.functionapp_utils import FunctionAppUtilities\n    from c7n_azure.policy import AzureFunctionMode\n    from c7n_azure.session import Session\n    from c7n_azure.utils import StringUtils\n    from c7n.utils import local_session\nexcept ImportError:\n    FunctionPackage = None\n    pass\n\n\ndef cache_path():\n    return os.path.join(os.path.dirname(__file__), 'cache')\n\n\ndef build_function_package(config, function_name, sub_id):\n    schedule = config.get('function_schedule', '0 */10 * * * *')\n\n    cache_override_path = cache_path()\n\n    function_path = function_name + \"_\" + sub_id\n\n    # Build package\n    package = FunctionPackage(\n        function_name,\n        os.path.join(os.path.dirname(__file__), 'function.py'),\n        target_sub_ids=[sub_id],\n        cache_override_path=cache_override_path)\n\n    package.build(None,\n                  modules=['c7n', 'c7n-azure', 'c7n-mailer'],\n                  non_binary_packages=['pyyaml', 'pycparser', 'tabulate', 'jmespath',\n                                       'datadog', 'MarkupSafe', 'simplejson', 'pyrsistent'],\n                  excluded_packages=['azure-cli-core', 'distlib', 'future', 'futures'])\n\n    package.pkg.add_contents(\n        function_path + '/function.json',\n        contents=package.get_function_config({'mode':\n                                              {'type': 'azure-periodic',\n                                               'schedule': schedule}}))\n\n    # Add mail templates\n    for d in set(config['templates_folders']):\n        if not os.path.exists(d):\n            continue\n        for t in [f for f in os.listdir(d) if os.path.splitext(f)[1] == '.j2']:\n            with open(os.path.join(d, t)) as fh:\n                package.pkg.add_contents(function_path + '/msg-templates/%s' % t, fh.read())\n\n    function_config = copy.deepcopy(config)\n\n    functions_full_template_path = '/home/site/wwwroot/' + function_path + '/msg-templates/'\n    function_config['templates_folders'] = [functions_full_template_path]\n\n    package.pkg.add_contents(\n        function_path + '/config.json',\n        contents=json.dumps(function_config))\n\n    package.close()\n    return package\n\n\ndef provision(config):\n    log = logging.getLogger('c7n_mailer.azure.deploy')\n\n    function_name = config.get('function_name', 'mailer')\n    function_properties = config.get('function_properties', {})\n\n    # service plan is parse first, because its location might be shared with storage & insights\n    service_plan = AzureFunctionMode.extract_properties(function_properties,\n                                                'servicePlan',\n                                                {\n                                                    'name': 'cloud-custodian',\n                                                    'location': 'eastus',\n                                                    'resource_group_name': 'cloud-custodian',\n                                                    'sku_tier': 'Dynamic',  # consumption plan\n                                                    'sku_name': 'Y1'\n                                                })\n\n    location = service_plan.get('location', 'eastus')\n    rg_name = service_plan['resource_group_name']\n\n    sub_id = local_session(Session).get_subscription_id()\n    suffix = StringUtils.naming_hash(rg_name + sub_id)\n\n    storage_account = AzureFunctionMode.extract_properties(function_properties,\n                                                    'storageAccount',\n                                                    {'name': 'mailerstorage' + suffix,\n                                                     'location': location,\n                                                     'resource_group_name': rg_name})\n\n    app_insights = AzureFunctionMode.extract_properties(function_properties,\n                                                    'appInsights',\n                                                    {'name': service_plan['name'],\n                                                     'location': location,\n                                                     'resource_group_name': rg_name})\n\n    function_app_name = FunctionAppUtilities.get_function_name(\n        '-'.join([service_plan['name'], function_name]), suffix)\n    FunctionAppUtilities.validate_function_name(function_app_name)\n\n    params = FunctionAppUtilities.FunctionAppInfrastructureParameters(\n        app_insights=app_insights,\n        service_plan=service_plan,\n        storage_account=storage_account,\n        function_app_resource_group_name=service_plan['resource_group_name'],\n        function_app_name=function_app_name)\n\n    FunctionAppUtilities.deploy_function_app(params)\n\n    log.info(\"Building function package for %s\" % function_app_name)\n    package = build_function_package(config, function_name, sub_id)\n\n    log.info(\"Function package built, size is %dMB\" % (package.pkg.size / (1024 * 1024)))\n\n    FunctionAppUtilities.publish_functions_package(params, package)\n", "path": "tools/c7n_mailer/c7n_mailer/azure_mailer/deploy.py"}]}