0

I was able to successfully use an Mailgun example to send an e-mail, but when converting to a class, the e-mails are not being sent. I am assuming that it has to do with the Asynchronous Response but I am not not sure. This is my first time working with Asynchronous Response and AsyncClient.

This is the class:

class Mail:

     def __init__(self):
         self.base_url = 'https://api.mailgun.net/v3/{url}'
         self.api_key = '{Key}'
         self.lstAttachment = []
         self.built = False
     def BuildMail(self):
         self.build_request_kwargs = {
                "url": "/messages",
                "method": "POST",
                "data": {
                        #"template": "template_name",
                        "from": "[email protected]",
                        "to": ["[email protected]"],
                        "subject": "Python E-mail Send",
                        "html": "<p>Hello from Python</p>"
                        },
                "files": self.lstAttachment
         }

      async def SendMail(self):
    
         if self.built == True:    
             client = httpx.AsyncClient(base_url=self.base_url, auth=("api", self.api_key))       
             return await self.__MsgSend(client)
    
         else:
             return 'Msg Not Built'


     async def __MsgSend(self, client):
         async with client as C: 
             request = C.build_request(**self.build_request_kwargs)
             response = await C.send(request)
             response.raise_for_status()
         return response

Then inside my main script:

Email = M.Mail()
Email.BuildMail()
result = Email.SendMail()

What I would expect is that the message would get sent and the response to be returned to the main script.

1
  • When using async functions, you need to run them using an event loop, e.g. asyncio.run. Are you doing that anywhere? Commented May 15, 2023 at 13:56

1 Answer 1

0

You are not awaiting the async function Mail.SendMail. Also I don't see anywhere you are using asyncio.run Try something like this:

async def main():
    Email = M.Mail()
    Email.BuildMail()
    result = await Email.SendMail()

asyncio.run(main())
Sign up to request clarification or add additional context in comments.

Comments

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.