-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction_app.py
More file actions
55 lines (47 loc) · 1.72 KB
/
function_app.py
File metadata and controls
55 lines (47 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import azure.functions as func
import datetime
import json
import logging
import email
import base64
from email import policy
from io import BytesIO
app = func.FunctionApp()
@app.function_name(name="extract_attachments")
@app.route(route="extract_attachments", methods=["POST"])
def extract_attachments(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processing email file.')
try:
# Get the email file from the request body
email_data = req.get_body()
# Parse the email message
msg = email.message_from_bytes(email_data, policy=policy.default)
# List to store attachments
attachments = []
# Extract attachments
for part in msg.iter_attachments():
filename = part.get_filename()
if filename:
content = part.get_payload(decode=True)
attachments.append({
'filename': filename,
'content': base64.b64encode(content).decode('utf-8'),
'content_type': part.get_content_type()
})
if attachments:
return func.HttpResponse(
body=str({'attachments': attachments}),
mimetype="application/json",
status_code=200
)
else:
return func.HttpResponse(
body="No attachments found in the email file.",
status_code=404
)
except Exception as e:
logging.error(f"Error processing email file: {str(e)}")
return func.HttpResponse(
body=f"Error processing email file: {str(e)}",
status_code=500
)