Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
24c7342
Adding python SDK
Jun 17, 2022
484a233
Updating sdk tests
Jun 23, 2022
abe693c
Updating constructor and fixing linting errors
Jun 23, 2022
3fbdcdf
Adding python SDK
Jun 23, 2022
248980f
Updating sdk tests
Jun 23, 2022
d91f795
Updating constructor and fixing linting errors
Jun 23, 2022
e6a4172
Merge branch 'feature/communication-email' of https://github.com/Azur…
Jun 23, 2022
d40c8fc
Removing pytest from dev_requirements.txt
Jun 23, 2022
47913ed
Updating azure core dependency
Jun 24, 2022
db859f1
Updating azure core version
Jun 24, 2022
a0f8f52
Adding policy file back into sms module
Jun 24, 2022
6eb6c46
Adding newline to policy file
Jun 24, 2022
1fc0256
Adding python SDK
Jun 24, 2022
cae0ce6
Updating sdk tests
Jun 24, 2022
fb90751
Updating constructor and fixing linting errors
Jun 24, 2022
cee2e08
Adding dev requirements
Jun 24, 2022
50f955e
Removing pytest from dev_requirements.txt
Jun 24, 2022
e98b324
Adding policy file back into sms module
Jun 24, 2022
b298973
Adding newline to policy file
Jun 24, 2022
728ca63
Merge branch 'feature/communication-email' of https://github.com/Azur…
Jun 24, 2022
d3af526
Updating tests with message id
Jun 24, 2022
519795a
Packaging update of azure-communication-email
AutorestCI Jun 27, 2022
dc1d09f
Fixing spelling errors
Jun 27, 2022
a3a0428
Merge branch 'feature/communication-email' of https://github.com/Azur…
Jun 27, 2022
46ed5c2
Fixing spelling
Jun 27, 2022
2abf446
Including samples and fixing README.md
Jun 27, 2022
42f8da6
Packaging update of azure-communication-email
AutorestCI Jun 27, 2022
235eb4f
Updating packaging file
Jun 27, 2022
9cfda32
Merge branch 'local/non-pr/main' into feature/communication-email
Jun 27, 2022
651a88b
Merge remote-tracking branch 'non-pr/feature/communication-email' int…
Jun 27, 2022
cb14df5
Update README and MANIFEST
Jun 27, 2022
d9fca05
Addressing PR comments
Jul 7, 2022
0fae0b4
Addressing PR comments
Jul 11, 2022
e887acf
Fixing comment error
Jul 11, 2022
2a70bea
Updating imports
Jul 12, 2022
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
8 changes: 8 additions & 0 deletions sdk/communication/azure-communication-email/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Release History

## 1.0.0b1 (Unreleased)

The first preview of the Azure Communication Email Client has the following features:

- send emails to multiple recipients with attachments
- get the status of a sent message
21 changes: 21 additions & 0 deletions sdk/communication/azure-communication-email/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation.

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
8 changes: 8 additions & 0 deletions sdk/communication/azure-communication-email/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
include _meta.json
recursive-include tests *.py *.yaml
recursive-include samples *.py *.md
include *.md
include azure/__init__.py
include azure/communication/__init__.py
include LICENSE
include azure/communication/email/py.typed
193 changes: 193 additions & 0 deletions sdk/communication/azure-communication-email/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
# Azure Communication Email client library for Python

This package contains a Python SDK for Azure Communication Services for Email.

## Key concepts

The Azure Communication Email package is used to do following:
- Send emails to multiple types of recipients
- Query the status of a sent email message

## Getting started

### Prerequisites

You need an [Azure subscription][azure_sub], a [Communication Service Resource][communication_resource_docs], and an [Email Communication Resource][email_resource_docs] with an active [Domain][domain_overview].

To create these resource, you can use the [Azure Portal][communication_resource_create_portal], the [Azure PowerShell][communication_resource_create_power_shell], or the [.NET management client library][communication_resource_create_net].

### Installing

Install the Azure Communication Email client library for Python with [pip](https://pypi.org/project/pip/):

```bash
pip install azure-communication-email
```

## Examples

`EmailClient` provides the functionality to send email messages .

## Authentication
Comment thread
yogeshmo marked this conversation as resolved.

Email clients can be authenticated using the connection string acquired from an Azure Communication Resource in the [Azure Portal][azure_portal].

```python
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);
```

Email clients can also be authenticated using an [AzureKeyCredential][azure-key-credential].

```python
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);
```

### Send an Email Message

To send an email message, call the `send` function from the `EmailClient`.

```python
content = EmailContent(
subject="This is the subject",
plain_text="This is the body",
html= "<html><h1>This is the body</h1></html>",
)

address = EmailAddress(email="customer@domain.com", display_name="Customer Name")

message = EmailMessage(
sender="sender@contoso.com",
content=content,
recipients=EmailRecipients(to=[address])
)

response = client.send(message)
```

### Send an Email Message to Multiple Recipients

To send an email message to multiple recipients, add a object for each recipient type and an object for each recipient.

```python
content = EmailContent(
subject="This is the subject",
plain_text="This is the body",
html= "<html><h1>This is the body</h1></html>",
)

recipients = EmailRecipients(
to=[
EmailAddress(email="customer@domain.com", display_name="Customer Name"),
EmailAddress(email="customer2@domain.com", display_name="Customer Name 2"),
],
cc=[
EmailAddress(email="ccCustomer@domain.com", display_name="CC Customer Name"),
EmailAddress(email="ccCustomer2@domain.com", display_name="CC Customer Name 2"),
],
bcc=[
EmailAddress(email="bccCustomer@domain.com", display_name="BCC Customer Name"),
EmailAddress(email="bccCustomer2@domain.com", display_name="BCC Customer Name 2"),
]
)

message = EmailMessage(sender="sender@contoso.com", content=content, recipients=recipients)
response = client.send(message)
```

### Send Email with Attachments

Azure Communication Services support sending email with attachments.

```python
import base64

content = EmailContent(
subject="This is the subject",
plain_text="This is the body",
html= "<html><h1>This is the body</h1></html>",
)

address = EmailAddress(email="customer@domain.com", display_name="Customer Name")

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

file_bytes_b64 = base64.b64encode(bytes(file_contents, 'utf-8'))
Comment thread
yogeshmo marked this conversation as resolved.

attachment = EmailAttachment(
name="attachment.txt",
attachment_type="txt",
content_bytes_base64=file_bytes_b64.decode()
)

message = EmailMessage(
sender="sender@contoso.com",
content=content,
recipients=EmailRecipients(to=[address]),
attachments=[attachment]
)

response = client.send(message)
```

### Get Email Message Status

The result from the `send` call contains a `message_id` which can be used to query the status of the email.

```python
response = client.send(message)
status = client.get_sent_status(response.message_id)
```

## Troubleshooting

Email operations will throw an exception if the request to the server fails. The Email client will raise exceptions defined in [Azure Core](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md).

```Python
from azure.core.exceptions import HttpResponseError

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

## Next steps

- [Read more about Email in Azure Communication Services][nextsteps]

## Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit [cla.microsoft.com][cla].

This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For more information see the [Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments.

<!-- LINKS -->

[azure_sub]: https://azure.microsoft.com/free/dotnet/
[azure_portal]: https://portal.azure.com
[azure-key-credential]: https://aka.ms/azsdk-python-core-azurekeycredential
[cla]: https://cla.microsoft.com
[coc]: https://opensource.microsoft.com/codeofconduct/
[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
[coc_contact]: mailto:opencode@microsoft.com
[communication_resource_docs]: https://docs.microsoft.com/azure/communication-services/quickstarts/create-communication-resource?tabs=windows&pivots=platform-azp
[email_resource_docs]: https://aka.ms/acsemail/createemailresource
[communication_resource_create_portal]: https://docs.microsoft.com/azure/communication-services/quickstarts/create-communication-resource?tabs=windows&pivots=platform-azp
[communication_resource_create_power_shell]: https://docs.microsoft.com/powershell/module/az.communication/new-azcommunicationservice
[communication_resource_create_net]: https://docs.microsoft.com/azure/communication-services/quickstarts/create-communication-resource?tabs=windows&pivots=platform-net
[package]: https://www.nuget.org/packages/Azure.Communication.Common/
[product_docs]: https://aka.ms/acsemail/overview
[nextsteps]: https://aka.ms/acsemail/overview
[nuget]: https://www.nuget.org/
[source]: https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/communication
[domain_overview]: https://aka.ms/acsemail/domainsoverview
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

from ._email_client import EmailClient
Comment thread
yogeshmo marked this conversation as resolved.

from ._generated.models import (
EmailMessage,
EmailCustomHeader,
EmailContent,
EmailImportance,
EmailRecipients,
EmailAddress,
EmailAttachment,
EmailAttachmentType,
SendEmailResult,
SendStatus,
SendStatusResult
)

__all__ = [
'EmailClient',
'EmailMessage',
'EmailCustomHeader',
'EmailContent',
'EmailImportance',
'EmailRecipients',
'EmailAddress',
'EmailAttachment',
'EmailAttachmentType',
'SendEmailResult',
'SendStatus',
'SendStatusResult',
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

from typing import Union
from uuid import uuid4
from azure.core.credentials import AzureKeyCredential
from azure.core.credentials import TokenCredential
from azure.core.tracing.decorator import distributed_trace
from ._shared.utils import parse_connection_str, get_current_utc_time
from ._shared.policy import HMACCredentialsPolicy
from ._generated._azure_communication_email_service import AzureCommunicationEmailService
from ._version import SDK_MONIKER
from ._generated.models import SendEmailResult, SendStatusResult, EmailMessage

class EmailClient(object): # pylint: disable=client-accepts-api-version-keyword
"""A client to interact with the AzureCommunicationService Email gateway.

This client provides operations to send an email and monitor its status.

:param str endpoint:
The endpoint url for Azure Communication Service resource.
:param Union[TokenCredential, AzureKeyCredential] credential:
The credential we use to authenticate against the service.
"""
def __init__(
self,
endpoint: str,
credential: Union[TokenCredential, AzureKeyCredential],
**kwargs
) -> None:
if endpoint.endswith("/"):
endpoint = endpoint[:-1]

authentication_policy = HMACCredentialsPolicy(endpoint, credential)

self._generated_client = AzureCommunicationEmailService(
endpoint,
authentication_policy=authentication_policy,
sdk_moniker=SDK_MONIKER,
**kwargs
)

@classmethod
def from_connection_string(
cls,
conn_str: str,
**kwargs
) -> 'EmailClient':
"""Create EmailClient from a Connection String.

:param str conn_str:
A connection string to an Azure Communication Service resource.
:returns: Instance of EmailClient.
:rtype: ~azure.communication.EmailClient
"""
endpoint, access_key = parse_connection_str(conn_str)

return cls(endpoint, AzureKeyCredential(access_key), **kwargs)

@distributed_trace
def send(
self,
email_message: EmailMessage,
**kwargs
) -> SendEmailResult:
"""Queues an email message to be sent to one or more recipients.

:param email_message: The message payload for sending an email.
:type email_message: ~azure.communication.email.models.EmailMessage
:return: SendEmailResult
:rtype: ~azure.communication.email.models.SendEmailResult
"""

return self._generated_client.email.send(
repeatability_request_id=uuid4(),
Comment thread
yogeshmo marked this conversation as resolved.
repeatability_first_sent=get_current_utc_time(),
email_message=email_message,
**kwargs
)

@distributed_trace
def get_send_status(
self,
message_id: str,
**kwargs
) -> SendStatusResult:
"""Gets the status of a message sent previously.

:param message_id: System generated message id (GUID) returned from a previous call to send email
:type message_id: str
:return: SendStatusResult
:rtype: ~azure.communication.email.models.SendStatusResult
"""

return self._generated_client.email.get_send_status(
message_id=message_id,
**kwargs
)

def __enter__(self) -> "EmailClient":
self._generated_client.__enter__()
return self

def __exit__(self, *args) -> None:
self._generated_client.__exit__(*args)
Loading