Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move away from using the body var for Jinja2 templates #80

Merged
merged 3 commits into from
Aug 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion docs/example.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ conf = ConnectionConfig(
MAIL_FROM = "your@email.com",
MAIL_PORT = 587,
MAIL_SERVER = "your mail server",
MAIL_FROM_NAME="Desired Name"
MAIL_FROM_NAME="Desired Name",
MAIL_TLS = True,
MAIL_SSL = False,
USE_CREDENTIALS = True,
Expand Down Expand Up @@ -117,6 +117,10 @@ async def send_file(

### Using Jinja2 HTML Templates

You can enable Jinja2 HTML Template emails by setting the `TEMPLATE_FOLDER` configuration option, and supplying a
value (which is just the name of the template file within the `TEMPLATE_FOLDER` dir) for the `template_name` parameter
in `FastMail.send_message()`. You then can pass a Dict as the `template_body` property of your `MessageSchema` object:

```python

class EmailSchema(BaseModel):
Expand Down Expand Up @@ -151,6 +155,37 @@ async def send_with_template(email: EmailSchema) -> JSONResponse:

```

For example, assume we pass a `template_body` of:

```json
{
"first_name": "Fred",
"last_name": "Fredsson"
}
```

We can reference the variables in our Jinja templates as per normal:

```
...
<span>Hello, {{ first_name }}!</span>
...
```

#### Legacy Behaviour (<= 0.4.0)

The original behaviour in <= 0.4.0 was to wrap the Dict you provide in a variable named `body` when it was provided to
Jinja behind the scenes. In these versions, you can then access your dict in your template like so:

```
...
<span>Hello, {{ body.first_name }}!</span>
...
```

As you can see our keys in our dict are no longer the top level, they are part of the `body` variable. Nesting works
as per normal below this level also.

## Guide for email utils

The utility allows you to check temporary email addresses, you can block any email or domain.
Expand Down
17 changes: 13 additions & 4 deletions fastapi_mail/fastmail.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ def _record(message):


class FastMail(_MailMixin):
'''
"""
Fastapi mail system sending mails(individual, bulk) attachments(individual, bulk)

:param config: Connection config to be passed

'''
"""

def __init__(self,
config: ConnectionConfig
Expand All @@ -55,14 +55,23 @@ def __init__(self,
async def get_mail_template(self, env_path, template_name):
return env_path.get_template(template_name)

@staticmethod
def make_dict(data):
try:
return dict(data)
except ValueError:
raise ValueError(f"Unable to build template data dictionary - {type(data)} is an invalid source data type")

async def __prepare_message(self, message: MessageSchema, template=None):
if template is not None:
template_body = message.template_body
if template_body and not message.html:
message.template_body = template.render(body=template_body)
template_data = self.make_dict(template_body)
message.template_body = template.render(**template_data)
message.subtype = "html"
elif message.html:
message.html = template.render(body=message.html)
template_data = self.make_dict(message.html)
message.html = template.render(**template_data)

msg = MailMsg(**message.dict())
if self.config.MAIL_FROM_NAME is not None:
Expand Down