Python용 Azure Communication Email 클라이언트 라이브러리 - 버전 1.0.0

이 패키지에는 Email Azure Communication Services 위한 Python SDK가 포함되어 있습니다.

주요 개념

Azure Communication Email 패키지는 여러 유형의 받는 사람에게 이메일을 보내는 데 사용됩니다.

시작

필수 조건

활성 도메인이 있는 Azure 구독, Communication Service 리소스Email Communication Resource가 필요합니다.

이러한 리소스를 만들려면 Azure Portal, Azure PowerShell 또는 .NET 관리 클라이언트 라이브러리를 사용할 수 있습니다.

설치

pip를 사용하여 Python용 Azure Communication Email 클라이언트 라이브러리를 설치합니다.

pip install azure-communication-email

예제

EmailClient 에서는 전자 메일 메시지를 보내는 기능을 제공합니다.

인증

Email 클라이언트는 Azure Portal의 Azure Communication Resource에서 가져온 연결 문자열을 사용하여 인증할 수 있습니다.

from azure.communication.email import EmailClient

connection_string = "endpoint=https://<resource-name>.communication.azure.com/;accessKey=<Base64-Encoded-Key>"
client = EmailClient.from_connection_string(connection_string);

또는 DefaultAzureCredential을 사용하여 Active Directory 인증을 사용할 수도 있습니다.

from azure.communication.email import EmailClient
from azure.identity import DefaultAzureCredential

# To use Azure Active Directory Authentication (DefaultAzureCredential) make sure to have AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET as env variables.
endpoint = "https://<resource-name>.communication.azure.com"
client = EmailClient(endpoint, DefaultAzureCredential())

Email 클라이언트는 AzureKeyCredential을 사용하여 인증할 수도 있습니다.

from azure.communication.email import EmailClient
from azure.core.credentials import AzureKeyCredential

credential = AzureKeyCredential("<api_key>")
endpoint = "https://<resource-name>.communication.azure.com/"
client = EmailClient(endpoint, credential);

Email 메시지 보내기

전자 메일 메시지를 보내려면 에서 함수를 begin_send 호출합니다 EmailClient. 그러면 폴러가 반환됩니다. 이 폴러를 사용하여 작업의 상태 검사 작업이 완료되면 결과를 검색할 수 있습니다.

message = {
    "content": {
        "subject": "This is the subject",
        "plainText": "This is the body",
        "html": "<html><h1>This is the body</h1></html>"
    },
    "recipients": {
        "to": [
            {
                "address": "customer@domain.com",
                "displayName": "Customer Name"
            }
        ]
    },
    "senderAddress": "sender@contoso.com"
}

poller = email_client.begin_send(message)
result = poller.result()

여러 받는 사람에게 Email 메시지 보내기

여러 받는 사람에게 전자 메일 메시지를 보내려면 각 받는 사람 유형에 대한 개체와 각 받는 사람에 대한 개체를 추가합니다.

message = {
    "content": {
        "subject": "This is the subject",
        "plainText": "This is the body",
        "html": "<html><h1>This is the body</h1></html>"
    },
    "recipients": {
        "to": [
            {"address": "customer@domain.com", "displayName": "Customer Name"},
            {"address": "customer2@domain.com", "displayName": "Customer Name 2"}
        ],
        "cc": [
            {"address": "ccCustomer@domain.com", "displayName": "CC Customer Name"},
            {"address": "ccCustomer2@domain.com", "displayName": "CC Customer Name 2"}
        ],
        "bcc": [
            {"address": "bccCustomer@domain.com", "displayName": "BCC Customer Name"},
            {"address": "bccCustomer2@domain.com", "displayName": "BCC Customer Name 2"}
        ]
    },
    "senderAddress": "sender@contoso.com"
}

poller = email_client.begin_send(message)
result = poller.result()

첨부 파일을 사용하여 Email 보내기

Azure Communication Services 첨부 파일이 있는 전자 메일 보내기를 지원합니다.

import base64

with open("C://readme.txt", "r") as file:
    file_contents = file.read()

file_bytes_b64 = base64.b64encode(bytes(file_contents, 'utf-8'))

message = {
    "content": {
        "subject": "This is the subject",
        "plainText": "This is the body",
        "html": "<html><h1>This is the body</h1></html>"
    },
    "recipients": {
        "to": [
            {
                "address": "customer@domain.com",
                "displayName": "Customer Name"
            }
        ]
    },
    "senderAddress": "sender@contoso.com",
    "attachments": [
        {
            "name": "attachment.txt",
            "attachmentType": "text/plain",
            "contentInBase64": file_bytes_b64.decode()
        }
    ]
}

poller = email_client.begin_send(message)
result = poller.result()

문제 해결

Email 작업은 서버에 대한 요청이 실패할 경우 예외를 throw합니다. Email 클라이언트는 Azure Core에 정의된 예외를 발생합니다.

from azure.core.exceptions import HttpResponseError

try:
    response = email_client.send(message)
except HttpResponseError as ex:
    print('Exception:')
    print(ex)

다음 단계

참여

이 프로젝트에 대한 기여와 제안을 환영합니다. 대부분의 경우 기여하려면 권한을 부여하며 실제로 기여를 사용할 권한을 당사에 부여한다고 선언하는 CLA(기여자 라이선스 계약)에 동의해야 합니다. 자세한 내용은 cla.microsoft.com.

이 프로젝트에는 Microsoft Open Source Code of Conduct(Microsoft 오픈 소스 준수 사항)가 적용됩니다. 자세한 내용은 Code of Conduct FAQ(규정 FAQ)를 참조하세요. 또는 추가 질문이나 의견은 opencode@microsoft.com으로 문의하세요.