-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathmetadata_example.py
More file actions
137 lines (110 loc) · 4.17 KB
/
Copy pathmetadata_example.py
File metadata and controls
137 lines (110 loc) · 4.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#!/usr/bin/env python3
"""
Nylas SDK Example: Using Metadata Fields with Drafts and Messages
This example demonstrates how to use metadata fields when creating drafts
and sending messages using the Nylas Python SDK.
Required Environment Variables:
NYLAS_API_KEY: Your Nylas API key
NYLAS_GRANT_ID: Your Nylas grant ID
TEST_EMAIL: Email address for sending test messages (optional)
Usage:
First, install the SDK in development mode:
cd /path/to/nylas-python
pip install -e .
Then set environment variables and run:
export NYLAS_API_KEY="your_api_key"
export NYLAS_GRANT_ID="your_grant_id"
export TEST_EMAIL="recipient@example.com"
python examples/metadata_field_demo/metadata_example.py
"""
import os
import sys
from typing import Dict, Any, Optional
# Import from local nylas package
from nylas import Client
from nylas.models.errors import NylasApiError
def get_env_or_exit(var_name: str, required: bool = True) -> Optional[str]:
"""Get an environment variable or exit if required and not found."""
value = os.getenv(var_name)
if required and not value:
print(f"Error: {var_name} environment variable is required")
sys.exit(1)
return value
def create_draft_with_metadata(
client: Client, grant_id: str, metadata: Dict[str, Any], recipient: str
) -> str:
"""Create a draft message with metadata fields."""
try:
draft_request = {
"subject": "Test Draft with Metadata",
"to": [{"email": recipient}],
"body": "This is a test draft with metadata fields.",
"metadata": metadata
}
draft, request_id = client.drafts.create(
identifier=grant_id,
request_body=draft_request
)
print(f"✓ Created draft with ID: {draft.id}")
print(f" Request ID: {request_id}")
return draft.id
except NylasApiError as e:
print(f"✗ Failed to create draft: {e}")
sys.exit(1)
def send_message_with_metadata(
client: Client, grant_id: str, metadata: Dict[str, Any], recipient: str
) -> str:
"""Send a message directly with metadata fields."""
try:
message_request = {
"subject": "Test Message with Metadata",
"to": [{"email": recipient}],
"body": "This is a test message with metadata fields.",
"metadata": metadata
}
message, request_id = client.messages.send(
identifier=grant_id,
request_body=message_request
)
print(f"✓ Sent message with ID: {message.id}")
print(f" Request ID: {request_id}")
return message.id
except NylasApiError as e:
print(f"✗ Failed to send message: {e}")
sys.exit(1)
def main():
"""Main function demonstrating metadata field usage."""
# Get required environment variables
api_key = get_env_or_exit("NYLAS_API_KEY")
grant_id = get_env_or_exit("NYLAS_GRANT_ID")
recipient = get_env_or_exit("TEST_EMAIL", required=False) or "recipient@example.com"
# Initialize Nylas client
client = Client(
api_key=api_key,
)
# Example metadata
metadata = {
"campaign_id": "example-123",
"user_id": "user-456",
"custom_field": "test-value"
}
print("\nDemonstrating Metadata Field Usage")
print("=================================")
# Create a draft with metadata
print("\n1. Creating draft with metadata...")
draft_id = create_draft_with_metadata(client, grant_id, metadata, recipient)
# Send a message with metadata
print("\n2. Sending message with metadata...")
message_id = send_message_with_metadata(client, grant_id, metadata, recipient)
print("\nExample completed successfully!")
# Get the draft and message to demonstrate metadata retrieval
draft = client.drafts.find(identifier=grant_id, draft_id=draft_id)
message = client.messages.find(identifier=grant_id, message_id=message_id)
print("\nRetrieved Draft Metadata:")
print("-------------------------")
print(draft.data)
print("\nRetrieved Message Metadata:")
print("---------------------------")
print(message.data)
if __name__ == "__main__":
main()