Skip to content

Commit 2c73eea

Browse files
Add E2E example for metadata field functionality
Co-Authored-By: Aaron de Mello <[email protected]>
1 parent da7c1ee commit 2c73eea

File tree

2 files changed

+178
-0
lines changed

2 files changed

+178
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Metadata Field Example
2+
3+
This example demonstrates how to use metadata fields when creating drafts and sending messages using the Nylas Python SDK.
4+
5+
## Features
6+
7+
- Create drafts with custom metadata fields
8+
- Send messages with custom metadata fields
9+
- Error handling and environment variable configuration
10+
- Clear output and status messages
11+
12+
## Prerequisites
13+
14+
1. A Nylas account with API access
15+
2. Python 3.x installed
16+
3. The Nylas Python SDK installed (`pip install nylas`)
17+
18+
## Setup
19+
20+
1. Set your environment variables:
21+
```bash
22+
export NYLAS_API_KEY="your_api_key"
23+
export NYLAS_GRANT_ID="your_grant_id"
24+
export TEST_EMAIL="[email protected]" # Optional
25+
```
26+
27+
2. Run the example:
28+
```bash
29+
python metadata_example.py
30+
```
31+
32+
## Example Output
33+
34+
```
35+
Demonstrating Metadata Field Usage
36+
=================================
37+
38+
1. Creating draft with metadata...
39+
✓ Created draft with ID: draft-abc123
40+
Request ID: req-xyz789
41+
42+
2. Sending message with metadata...
43+
✓ Sent message with ID: msg-def456
44+
Request ID: req-uvw321
45+
46+
Example completed successfully!
47+
```
48+
49+
## Error Handling
50+
51+
The example includes proper error handling for:
52+
- Missing environment variables
53+
- API authentication errors
54+
- Draft creation failures
55+
- Message sending failures
56+
57+
## Documentation
58+
59+
For more information about the Nylas Python SDK and its features, visit:
60+
- [Nylas Python SDK Documentation](https://developer.nylas.com/docs/sdks/python/)
61+
- [Nylas API Reference](https://developer.nylas.com/docs/api/)
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Nylas SDK Example: Using Metadata Fields with Drafts and Messages
4+
5+
This example demonstrates how to use metadata fields when creating drafts
6+
and sending messages using the Nylas Python SDK.
7+
8+
Required Environment Variables:
9+
NYLAS_API_KEY: Your Nylas API key
10+
NYLAS_GRANT_ID: Your Nylas grant ID
11+
TEST_EMAIL: Email address for sending test messages (optional)
12+
13+
Usage:
14+
export NYLAS_API_KEY="your_api_key"
15+
export NYLAS_GRANT_ID="your_grant_id"
16+
export TEST_EMAIL="[email protected]"
17+
python metadata_example.py
18+
"""
19+
20+
import os
21+
import sys
22+
from typing import Dict, Any, Optional
23+
from nylas import Client
24+
from nylas.models.errors import NylasAPIError
25+
26+
27+
def get_env_or_exit(var_name: str, required: bool = True) -> Optional[str]:
28+
"""Get an environment variable or exit if required and not found."""
29+
value = os.getenv(var_name)
30+
if required and not value:
31+
print(f"Error: {var_name} environment variable is required")
32+
sys.exit(1)
33+
return value
34+
35+
36+
def create_draft_with_metadata(
37+
client: Client, grant_id: str, metadata: Dict[str, Any], recipient: str
38+
) -> str:
39+
"""Create a draft message with metadata fields."""
40+
try:
41+
draft_request = {
42+
"subject": "Test Draft with Metadata",
43+
"to": [{"email": recipient}],
44+
"body": "This is a test draft with metadata fields.",
45+
"metadata": metadata
46+
}
47+
48+
draft, request_id = client.drafts.create(
49+
identifier=grant_id,
50+
request_body=draft_request
51+
)
52+
print(f"✓ Created draft with ID: {draft.id}")
53+
print(f" Request ID: {request_id}")
54+
return draft.id
55+
except NylasAPIError as e:
56+
print(f"✗ Failed to create draft: {e}")
57+
sys.exit(1)
58+
59+
60+
def send_message_with_metadata(
61+
client: Client, grant_id: str, metadata: Dict[str, Any], recipient: str
62+
) -> None:
63+
"""Send a message directly with metadata fields."""
64+
try:
65+
message_request = {
66+
"subject": "Test Message with Metadata",
67+
"to": [{"email": recipient}],
68+
"body": "This is a test message with metadata fields.",
69+
"metadata": metadata
70+
}
71+
72+
message, request_id = client.messages.send(
73+
identifier=grant_id,
74+
request_body=message_request
75+
)
76+
print(f"✓ Sent message with ID: {message.id}")
77+
print(f" Request ID: {request_id}")
78+
except NylasAPIError as e:
79+
print(f"✗ Failed to send message: {e}")
80+
sys.exit(1)
81+
82+
83+
def main():
84+
"""Main function demonstrating metadata field usage."""
85+
# Get required environment variables
86+
api_key = get_env_or_exit("NYLAS_API_KEY")
87+
grant_id = get_env_or_exit("NYLAS_GRANT_ID")
88+
recipient = get_env_or_exit("TEST_EMAIL", required=False) or "[email protected]"
89+
90+
# Initialize Nylas client
91+
client = Client(
92+
api_key=api_key,
93+
)
94+
95+
# Example metadata
96+
metadata = {
97+
"campaign_id": "example-123",
98+
"user_id": "user-456",
99+
"custom_field": "test-value"
100+
}
101+
102+
print("\nDemonstrating Metadata Field Usage")
103+
print("=================================")
104+
105+
# Create a draft with metadata
106+
print("\n1. Creating draft with metadata...")
107+
draft_id = create_draft_with_metadata(client, grant_id, metadata, recipient)
108+
109+
# Send a message with metadata
110+
print("\n2. Sending message with metadata...")
111+
send_message_with_metadata(client, grant_id, metadata, recipient)
112+
113+
print("\nExample completed successfully!")
114+
115+
116+
if __name__ == "__main__":
117+
main()

0 commit comments

Comments
 (0)