-
Notifications
You must be signed in to change notification settings - Fork 0
/
send_email.py
84 lines (73 loc) · 2.96 KB
/
send_email.py
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
import imaplib
import smtplib
import time
from email.message import EmailMessage
from typing import Type
from pydantic import BaseModel, Field
from helper.imap_email import ImapEmail
from superagi.tools.base_tool import BaseTool
class SendEmailInput(BaseModel):
to: str = Field(..., description="Email Address of the Receiver, default email address is 'example@example.com'")
subject: str = Field(..., description="Subject of the Email to be sent")
body: str = Field(..., description="Email Body to be sent")
class SendEmailTool(BaseTool):
"""
Send an Email tool
Attributes:
name : The name.
description : The description.
args_schema : The args schema.
"""
name: str = "Test Send Email"
args_schema: Type[BaseModel] = SendEmailInput
description: str = "Send an Email"
def _execute(self, to: str, subject: str, body: str) -> str:
"""
Execute the send email tool.
Args:
to : The email address of the receiver.
subject : The subject of the email.
body : The body of the email.
Returns:
success or error message.
"""
email_sender = self.get_tool_config('EMAIL_ADDRESS')
email_password = self.get_tool_config('EMAIL_PASSWORD')
if email_sender == "" or email_sender.isspace():
return "Error: Email Not Sent. Enter a valid Email Address."
if email_password == "" or email_password.isspace():
return "Error: Email Not Sent. Enter a valid Email Password."
message = EmailMessage()
message["Subject"] = subject
message["From"] = email_sender
message["To"] = to
signature = self.get_tool_config('EMAIL_SIGNATURE')
if signature:
body += f"\n{signature}"
message.set_content(body)
send_to_draft = self.get_tool_config('EMAIL_DRAFT_MODE')
if send_to_draft.upper() == "TRUE":
send_to_draft = True
else:
send_to_draft = False
if message["To"] == "example@example.com" or send_to_draft:
draft_folder = self.get_tool_config('EMAIL_DRAFT_FOLDER')
imap_server = self.get_tool_config('EMAIL_IMAP_SERVER')
conn = ImapEmail().imap_open(draft_folder, email_sender, email_password, imap_server)
conn.append(
draft_folder,
"",
imaplib.Time2Internaldate(time.time()),
str(message).encode("UTF-8")
)
return f"Email went to {draft_folder}"
else:
smtp_host = self.get_tool_config('EMAIL_SMTP_HOST')
smtp_port = self.get_tool_config('EMAIL_SMTP_PORT')
with smtplib.SMTP(smtp_host, smtp_port) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.login(email_sender, email_password)
smtp.send_message(message)
smtp.quit()
return f"Email was sent to {to}"