File size: 1,959 Bytes
ef1ad9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
# Library Imports
from fastapi import HTTPException, status
from sqlalchemy.orm import Session
from pathlib import Path

# User Imports
from ...models.email_templates import EmailTemplates
from ...config.env import env
from .send_email_helper import invoke_acs, replace_placeholders


async def send_email(db: Session, recipient_email: str, context_data: dict, template_code: str, file_paths: list = None):
    """

    Calls send email service



    Args:

        db: Session variable

        recipient_email (str): Email address of the recipient.

        context_data (dict): Dictionary containing variables to be used in the template.

        template_code (str): html template code

        file_paths (List(str)): local path of attachments

    """
    try:
        # get template data from db
        template_data = db.query(EmailTemplates).filter_by(
            templateCode=template_code).first()

        if not template_data:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND, detail='Template not found')

        files = []
        # Prepare the files for upload
        if file_paths:
            for file_path in file_paths:
                file_name = Path(file_path).name
                files.append(
                    ('files', (file_name, open(file_path, 'rb'), 'application/pdf')))

        # Extract required template data
        template = template_data.template
        subject = template_data.subject

        # Replace placeholders in the template code amd subject
        html_content = replace_placeholders(template, context_data)
        subject = replace_placeholders(subject, context_data)

        await invoke_acs(recipient_email, html_content, subject, files)

        return

    except Exception as e:
        raise HTTPException(
            detail=str(e),
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )