-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
135 lines (104 loc) · 3.85 KB
/
main.py
File metadata and controls
135 lines (104 loc) · 3.85 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
"""
AI Email Agent — Built with AgentMail + OpenAI
This template creates an AI-powered email agent that can:
1. Create its own email inbox
2. Send emails
3. Receive and process incoming emails
4. Reply intelligently using GPT-4
5. Handle webhooks for real-time email processing
Get your API keys:
- AgentMail: https://console.agentmail.to (free)
- OpenAI: https://platform.openai.com/api-keys
Set AGENTMAIL_API_KEY and OPENAI_API_KEY in Replit Secrets.
"""
import os
import json
from agentmail import AgentMail
from openai import OpenAI
from flask import Flask, request
# Initialize clients
agentmail = AgentMail(api_key=os.environ.get("AGENTMAIL_API_KEY"))
openai_client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
app = Flask(__name__)
# System prompt for your AI agent
SYSTEM_PROMPT = """You are a helpful AI email assistant.
Reply to emails concisely and helpfully.
Keep replies under 3 paragraphs.
Be professional but friendly."""
def create_agent_inbox():
"""Create a new email inbox for the agent."""
inbox = agentmail.inboxes.create(display_name="AI Email Agent")
print(f"✅ Agent inbox created: {inbox.inbox_id}")
return inbox
def send_email(inbox_id: str, to: str, subject: str, text: str):
"""Send an email from the agent's inbox."""
message = agentmail.inboxes.messages.send(
inbox_id=inbox_id,
to=to,
subject=subject,
text=text,
)
print(f"📤 Sent email to {to}: {subject}")
return message
def process_incoming_email(inbox_id: str, message_id: str):
"""Process an incoming email and generate an AI reply."""
# Get the message
msg = agentmail.inboxes.messages.get(
inbox_id=inbox_id, message_id=message_id
)
# Use extracted_text to get clean content (strips quoted text from replies)
customer_message = msg.extracted_text or msg.text
print(f"📥 Received from {msg.from_}: {customer_message[:100]}...")
# Get thread for conversation context
thread = agentmail.inboxes.threads.get(
inbox_id=inbox_id, thread_id=msg.thread_id
)
# Build conversation history
conversation = []
for thread_msg in thread.messages:
role = "assistant" if thread_msg.from_ == inbox_id else "user"
content = thread_msg.extracted_text or thread_msg.text
if content:
conversation.append({"role": role, "content": content})
# Generate reply with GPT-4
response = openai_client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
*conversation,
],
)
reply_text = response.choices[0].message.content
# Send reply
reply = agentmail.inboxes.messages.reply(
inbox_id=inbox_id, message_id=message_id, text=reply_text
)
print(f"💬 Replied: {reply_text[:100]}...")
return reply
# Webhook endpoint for real-time email processing
@app.route("/webhook", methods=["POST"])
def webhook():
"""Handle incoming email events from AgentMail."""
event = request.json
if event.get("type") == "message.received":
data = event["data"]
process_incoming_email(
inbox_id=data["inbox_id"],
message_id=data["message_id"],
)
return "", 200
@app.route("/", methods=["GET"])
def index():
return """
<h1>🤖 AI Email Agent</h1>
<p>Built with <a href="https://agentmail.to">AgentMail</a> + OpenAI</p>
<p>Webhook endpoint: <code>/webhook</code></p>
"""
if __name__ == "__main__":
# Create an inbox on startup
inbox = create_agent_inbox()
print(f"\n🤖 AI Email Agent is running!")
print(f"📧 Send emails to: {inbox.inbox_id}")
print(f"🔗 Webhook URL: Set your Replit URL + /webhook in AgentMail dashboard\n")
# Start the webhook server
app.run(host="0.0.0.0", port=5000)