sabuhish / fastapi-mail

Fastapi mail system sending mails(individual, bulk) attachments(individual, bulk)
https://sabuhish.github.io/fastapi-mail/
MIT License
673 stars 82 forks source link

ValueError when sending two emails with the same template #198

Open IsNeron opened 1 year ago

IsNeron commented 1 year ago

I've been trying to send two messages with the same body. The code for it is

class MailService:
    def __init__(self, background_tasks: BackgroundTasks) -> None:
        self._background_tasks = background_tasks

    def _send(
        self,
        subject: str,
        recipients: 'list[EmailStr]',
        template: str,
        template_body: dict,
    ) -> None:
        support_email = settings.mail.support_email
        template_body.update(
            app_title=settings.title,
            support_email=support_email,
        )
        self._background_tasks.add_task(mail_sender.send_message,
            MessageSchema(
                subject=f'{settings.title} - {subject}',
                recipients=recipients,
                subtype=MessageType.html,
                reply_to=[settings.mail.support_email],
                template_body=template_body,
            ),
            template,
        )

    def invite_unregistered_to_members(
        self,
        sender_name: str,
        entity_table: 'type[orm.IdNameMixin]',
        entity_name: str,
        receiver_email: 'EmailStr',
    ) -> None:
        public_url = settings.public_url
        self._send(
            'приглашение',
            [receiver_email],
            'invite_unregistered_to_members.jinja2',
            {
                'entity_kind': entity_table.__tablename__,  # type: ignore
                'entity_name': entity_name,
                'sender_name': sender_name,
                'public_url': public_url,
                'login_link': settings.template.login_link,
            },
        )

When I'm trying to call invite_unregistered_to_members, the first sent works OK, but the second letter to another e-mail fails with the ValueError: Unable to build template data dictionary - <class 'str'>is an invalid source data type

I suppose, that the error is caused by Fastmail.py -- def check_data

    @staticmethod
    def check_data(data: Union[Dict[Any, Any], str, None]) -> Dict[Any, Any]:
        if not isinstance(data, dict):
            raise ValueError(
                f"Unable to build template data dictionary - {type(data)}"
                "is an invalid source data type"
            )

        return data

In data there is somehow a jinja2 template...

The only fix that i found is to restart or reload app, then letter will send fine. But another letter after it will fail again.

Can anybody help with this? Please...

DurandA commented 10 months ago

I got the same issue.

cosmofactory commented 2 months ago

Same issue here, any solutions?