0

I am trying to use Azure Functions (HttpTrigger) to Read my emails and put them into my Azure Database. To achieve this I developed a python script(readEmail.py and raFunctions.py) which works local under Visual Studio Code in Ubuntu. The next step I tried is to convert this script to an Azure Function. When I try to run the Azure Function locally:

func host start

http://localhost:7071/api/ReadEmail?name=erik

it returns the following error:

Executed 'Functions.ReadEmail' (Failed, Id=4284c861-ce2f-4755-a7e3-94e269a42bc1)
[1/11/20 8:14:43 AM] System.Private.CoreLib: Exception while executing function: Functions.ReadEmail. System.Private.CoreLib: Result: Failure
[1/11/20 8:14:43 AM] Exception: ModuleNotFoundError: No module named 'pyodbc'
[1/11/20 8:14:43 AM] Stack:   File "/usr/lib/azure-functions-core-tools/workers/python/3.6/LINUX/X64/azure_functions_worker/dispatcher.py", line 242, in _handle__function_load_request
[1/11/20 8:14:43 AM]     func_request.metadata.entry_point)
[1/11/20 8:14:43 AM]   File "/usr/lib/azure-functions-core-tools/workers/python/3.6/LINUX/X64/azure_functions_worker/loader.py", line 66, in load_function
[1/11/20 8:14:43 AM]     mod = importlib.import_module(fullmodname)
[1/11/20 8:14:43 AM]   File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
[1/11/20 8:14:43 AM]     return _bootstrap._gcd_import(name[level:], package, level)
[1/11/20 8:14:43 AM]   File "/home/webapp/git/RAFunctions/ReadEmail/__init__.py", line 4, in <module>
[1/11/20 8:14:43 AM]     import pyodbc

I hope you can help me out here! I put the python scripts in the code below.

FOLDER OF THE FUNCTION

  • HttpTrigger (Azure Tutorial)
  • ReadEmail (Azure Function)
    • function.json (default Azure)
    • init.py
    • raFunctions.py (helpers)
    • readEmail.py (helpers)
  • host.json (default Azure)
  • local.settings.json (default Azure)
  • proxies.json (default Azure)
  • requirements.txt

__init__.py

 import logging
import email
import imaplib
import pyodbc
from datetime import datetime
from .readEmail import readEmail
import azure.functions as func


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    responseEmail = readEmail()

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello {responseEmail}!")
    else:
        return func.HttpResponse(
             "Please pass a name on the query string or in the request body",
             status_code=400
        )

readEmail.py

import email
import imaplib
import pyodbc
from datetime import datetime
from .raFunctions import uitvullenDatum

def readEmail():
#Configurations
EMAIL = '[email protected]'
PASSWORD = 'mypassword'
SERVER = 'imap.provider.com'

server = 'myserver.database.windows.net'
database = 'mydatabase'
username = 'mydbusername'
password = 'mypassword'
driver= '{ODBC Driver 17 for SQL Server}'

connectionString = 'DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password +';Authentication=ActiveDirectoryPassword'

# Connection settings to Database and Email Server
mail = imaplib.IMAP4_SSL(SERVER)
mail.login(EMAIL, PASSWORD)
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password +';Authentication=ActiveDirectoryPassword')
cursor = cnxn.cursor()

try:
    mail.select('inbox')
    status, data = mail.search(None, 'ALL')
    mail_ids = []
    for block in data:

        mail_ids += block.split()
    for i in mail_ids:

        status, data = mail.fetch(i, '(RFC822)')
        for response_part in data:
            if isinstance(response_part, tuple):
                message = email.message_from_bytes(response_part[1])
                mail_from = message['From']
                mail_subject = message['Subject']          
                mail_date = message['Date']

                if message.is_multipart():
                    mail_content = ''

                    for part in message.get_payload():

                        if part.get_content_type() == 'text/plain':
                            mail_content += part.get_payload()

                        else:
                            mail_content = part.get_payload()   

                else:
                    mail_content = message.get_payload()

                maildate = email.utils.parsedate(mail_date)
                maildate = uitvullenDatum(str(maildate[0]),str(maildate[1]),str(maildate[2]))

                values = (maildate, mail_from, mail_subject, mail_content)
                sql = "EXEC wp_ra.invoerenmail ?, ?, ?, ?"
                cursor.execute(sql, (values))
                cursor.commit()
                return "Email succesvol ingelezen!"
catch:
    return "Fout bij het inlezen van de mail!"

** requirements.txt **

azure-functions
azure-functions-worker
re
datetime
pyodbc
imaplib
email
logging

After some help i also tried to create an virtual enviroment in python and install all the necessarily modules and run the func host again

python -m venv .venv
source .venv/bin/activate
pip3 install azure, re, pyodbc, imaplib, email, logging
pip3 freeze > requirements.txt
func host start

I now get the error:

[1/12/20 7:02:34 AM] Executed 'Functions.ReadEmail' (Failed, Id=583e1234-9ad4-477b-b23f-56f53493579d)
[1/12/20 7:02:34 AM] System.Private.CoreLib: Exception while executing function: Functions.ReadEmail. System.Private.CoreLib: Result: Failure
[1/12/20 7:02:34 AM] Exception: SyntaxError: invalid syntax (readEmail.py, line 67)
[1/12/20 7:02:34 AM] Stack:   File "/usr/lib/azure-functions-core-tools/workers/python/3.6/LINUX/X64/azure_functions_worker/dispatcher.py", line 242, in _handle__function_load_request
[1/12/20 7:02:34 AM]     func_request.metadata.entry_point)
[1/12/20 7:02:34 AM]   File "/usr/lib/azure-functions-core-tools/workers/python/3.6/LINUX/X64/azure_functions_worker/loader.py", line 66, in load_function
[1/12/20 7:02:34 AM]     mod = importlib.import_module(fullmodname)
[1/12/20 7:02:34 AM]   File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
[1/12/20 7:02:34 AM]     return _bootstrap._gcd_import(name[level:], package, level)
[1/12/20 7:02:34 AM]   File "<frozen importlib._bootstrap>", line 994, in _gcd_import
[1/12/20 7:02:34 AM]   File "<frozen importlib._bootstrap>", line 971, in _find_and_load
[1/12/20 7:02:34 AM]   File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked
[1/12/20 7:02:34 AM]   File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
[1/12/20 7:02:34 AM]   File "<frozen importlib._bootstrap>", line 994, in _gcd_import
[1/12/20 7:02:34 AM]   File "<frozen importlib._bootstrap>", line 971, in _find_and_load
[1/12/20 7:02:34 AM]   File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
[1/12/20 7:02:34 AM]   File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
[1/12/20 7:02:34 AM]   File "<frozen importlib._bootstrap_external>", line 678, in exec_module
[1/12/20 7:02:34 AM]   File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
[1/12/20 7:02:34 AM]   File "/home/webapp/git/RAFunctions/ReadEmail/__init__.py", line 6, in <module>
[1/12/20 7:02:34 AM]     from .readEmail import readEmail

1 Answer 1

1

Can you try creating a Python virtual environment and running the function from within the same environment.

Sign up to request clarification or add additional context in comments.

6 Comments

which is a good things, so we can proceed with troubleshooting other error.
I described the error and the steps in the original question, manny thanks for you help Mohit
This clearly says "SyntaxError: invalid syntax (readEmail.py, line 67) " Please correct the error and execute it. Additionally , Correct the indentation is it is not correct in your file.
Also add finally block in reademail.py . return "Email succesvol ingelezen!" finally: return "Fout bij het inlezen van de mail!"
Thanks, that works. CATCH is not a valid statement in python. I realy thankfull. Can you also deploy it like this?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.