0

I tried sending email using Azure email communication Email, it works fine until I need to implement asyncronous sending email since its used multiple time and the response is really slow

class Email(Configuration):
def __init__(self):
    super().__init__()
    self.logger_file = 'email_exception.log'

async def send_mail(self, email_content: dict, email_recipient: str = None):
    print(f" sending email called")
    error = False
    message = "Success"
    recipient_address = email_recipient
    if email_recipient is None or email_recipient == '':
        recipient_address = os.getenv("RECIPIENT_EMAIL_ADDRESS")

    try:
        content = {
            "senderAddress": sender_address,
            "recipients":  {
                "to": [{"address": recipient_address}, {"address": recipient_address}],
                "cc": [{"address": recipient_address}],
                "bcc": [{"address": recipient_address}]
            },
            "content": email_content
        }
        client = EmailClient.from_connection_string(connection_string)

        poller = client.begin_send(content)

        print(f" polllerrrr {poller}")

        time_elapsed = 0
        while not poller.done():
            await poller.wait(POLLER_WAIT_TIME)
            time_elapsed += POLLER_WAIT_TIME

            if time_elapsed > 18 * POLLER_WAIT_TIME:
                raise RuntimeError("Polling timed out.")

        if poller.result()["status"] == "Succeeded":
            print(
                f"Successfully sent the emails (operation id: {poller.result()['id']})")
            # logging.info(f"Successfully sent the email ")
            return error, message
        else:

            raise RuntimeError(str(poller.result()["error"]))

    except Exception as ex:
        self.logger.error(
            f"exception was thrown when sending email {str(ex)}")
        error = True
        message = str(ex)
        return error, message

However, I got exception object NoneType can't be used in 'await' expression, though its successfully sending email, I think it not acting asyncrounously since its throwing exception, any ideas?

ira
  • 534
  • 1
  • 5
  • 17

1 Answers1

1

How to send Asynchronous email using Azure Communication Email Python SDK

You can use the below sample code to send Asynchronous emails using Azure Communication Email Python SDK.

Code:

import os
from azure.communication.email import EmailClient
import asyncio

async def send_email():
    connection_string = "your-connection string"
    client = EmailClient.from_connection_string(connection_string)

    sender_address ="<sender address>"
    recipient_address = "<recipient address>"

    email_message = {
        "subject": "This is the subject",
        "plainText": "This is the body",
        "html": "<html><h1>This is the body</h1></html>"
    }

    email_content = {
        "senderAddress": sender_address,
        "recipients": {
            "to": [{"address": recipient_address}],
        },
        "content": email_message
    }

    try:
        poller = client.begin_send(email_content)
        result = poller.result()
        if result:
            print(f"Email sent with ID: {result['id']}")
        else:
            print("Error sending email: result is None")
    except Exception as ex:
        print(f"Error sending email: {str(ex)}")

async def main():
    await send_email()

if __name__ == "__main__":
    asyncio.run(main())

Output:

Email sent with ID: 50cfeb24-6660-4cf5-a07e-xxxxxxx

enter image description here

Mail: enter image description here

Reference: Quickstart - How to send an email using Azure Communication Service - An Azure Communication Services Quickstart | Microsoft Learn

Venkatesan
  • 3,748
  • 1
  • 3
  • 15