(20250120) Mail sending API ready.
This commit is contained in:
@@ -59,6 +59,7 @@ from models.message.mail.send import MailSendOneResult
|
||||
|
||||
# Mail Client(s):
|
||||
from utils_v2.goog.controllers.gmail.gmail_client import AsyncGmailClient
|
||||
from utils_v2.goog.controllers.gmail.gmail_message import GmailMessage
|
||||
|
||||
# To work with datatypes:
|
||||
from typing import List, Any
|
||||
@@ -303,7 +304,20 @@ class AllMailController(MailController):
|
||||
# ┛ ┗┗┻┗┗ ┗┛┗ ┛┗┗┻┗┛┗┗┫
|
||||
# ┛
|
||||
|
||||
pass
|
||||
async def send_mail(
|
||||
self,
|
||||
sql_conn: AsyncMySQL,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
mail_client: AsyncGmailClient,
|
||||
mail_message: GmailMessage,
|
||||
auth_token: CoreAuthTokenModel,
|
||||
client_thread_id: str | None,
|
||||
user_info: CoreUserInfoModel | None,
|
||||
llm: CoreLLMController = None,
|
||||
session_token: str = None
|
||||
) -> MailSendOneResult:
|
||||
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
|
||||
@@ -59,6 +59,7 @@ from models.message.mail.send import MailSendOneResult
|
||||
|
||||
# Mail Client(s):
|
||||
from utils_v2.goog.controllers.gmail.gmail_client import AsyncGmailClient
|
||||
from utils_v2.goog.controllers.gmail.gmail_message import GmailMessage
|
||||
|
||||
# To work with datatypes:
|
||||
from typing import List, Any
|
||||
@@ -151,7 +152,7 @@ class MailController(CoreMessageController, ABC):
|
||||
role = "system",
|
||||
content = (
|
||||
"You're an expert mail summary assistant. That summarizes sent mails in 150 chars or less. "
|
||||
"The objective of your user is to be able to recollect what a mail they sent was about from a brief "
|
||||
"The objective of your user is to be able to recollect what the mail they sent was about from a brief "
|
||||
"summary. Reply in a simple string, no formatting is allowed except emojis. Good luck :)"
|
||||
)
|
||||
)
|
||||
@@ -523,7 +524,21 @@ class MailController(CoreMessageController, ABC):
|
||||
# ┛ ┗┗┻┗┗ ┗┛┗ ┛┗┗┻┗┛┗┗┫
|
||||
# ┛
|
||||
|
||||
pass
|
||||
@abstractmethod
|
||||
async def send_mail(
|
||||
self,
|
||||
sql_conn: AsyncMySQL,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
mail_client: AsyncGmailClient,
|
||||
mail_message: GmailMessage,
|
||||
auth_token: CoreAuthTokenModel,
|
||||
client_thread_id: str | None,
|
||||
user_info: CoreUserInfoModel | None,
|
||||
llm: CoreLLMController = None,
|
||||
session_token: str = None
|
||||
) -> MailSendOneResult:
|
||||
|
||||
pass
|
||||
|
||||
# ┳┳┓ •┓ ┳┳ ┓ •
|
||||
# ┃┃┃┏┓┓┃ ┃┃┏┓┏┫┏┓╋┓┏┓┏┓
|
||||
|
||||
@@ -36,6 +36,8 @@ sys.path.append(".")
|
||||
sys.path.append("..")
|
||||
|
||||
# My async utils:
|
||||
from utils_v2.string import json
|
||||
from utils_v2.mail import mail_parser
|
||||
from utils_v2.date_time import date_time
|
||||
from utils_v2.database.async_mysql_v2 import AsyncMySQL
|
||||
from utils_v2.database.async_mongo_v2 import AsyncMongo
|
||||
@@ -58,6 +60,7 @@ from models.message.mail.send import MailSendOneResult
|
||||
|
||||
# Mail Client(s):
|
||||
from utils_v2.goog.controllers.gmail.gmail_client import AsyncGmailClient, SCOPES_GMAIL_MAIL_MANAGEMENT
|
||||
from utils_v2.goog.controllers.gmail.gmail_message import GmailMessage
|
||||
from utils_v2.goog.models.auth_tokens import GoogleAuthTokens
|
||||
|
||||
# To work with datatypes:
|
||||
@@ -719,7 +722,120 @@ class GmailController(MailController):
|
||||
# ┛ ┗┗┻┗┗ ┗┛┗ ┛┗┗┻┗┛┗┗┫
|
||||
# ┛
|
||||
|
||||
pass
|
||||
async def send_mail(
|
||||
self,
|
||||
sql_conn: AsyncMySQL,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
mail_client: AsyncGmailClient,
|
||||
mail_message: GmailMessage,
|
||||
auth_token: CoreAuthTokenModel,
|
||||
client_thread_id: str | None,
|
||||
user_info: CoreUserInfoModel | None,
|
||||
llm: CoreLLMController = None,
|
||||
session_token: str = None
|
||||
) -> MailSendOneResult:
|
||||
|
||||
# Start by assuming failure:
|
||||
send_result = MailSendOneResult()
|
||||
now = date_time.get_current_utc_date_time(as_string = False)
|
||||
|
||||
# Refresh the access token(s) if needed:
|
||||
auth_token = await self.refresh_authorization(
|
||||
sql_conn = sql_conn,
|
||||
mongo_data_conn = mongo_data_conn,
|
||||
mail_client = mail_client,
|
||||
http_client = mail_client.http_client,
|
||||
auth_token = auth_token,
|
||||
force_refresh = False,
|
||||
session_token = session_token
|
||||
)
|
||||
|
||||
# If the user info was not given, take it from the token model:
|
||||
if user_info is None: user_info = auth_token.user
|
||||
|
||||
# Extract the client's tokens from the full token model,
|
||||
# and check if they are valid (not expired):
|
||||
google_tokens = GoogleAuthTokens(**auth_token.token)
|
||||
if google_tokens.expired:
|
||||
send_result.message = "Gmail token(s) have expired."
|
||||
return send_result
|
||||
|
||||
# Try sending the message:
|
||||
client_response = await mail_client.send_message(
|
||||
tokens = google_tokens,
|
||||
message = mail_message
|
||||
)
|
||||
|
||||
# If the attempt failed:
|
||||
if not client_response.success:
|
||||
send_result.message = f"Gmail: {client_response.message}"
|
||||
return send_result
|
||||
|
||||
# Parse the mail to save it to the database:
|
||||
mail_json = mail_parser.parse(mail_message.get_raw_message(as_base64 = False))
|
||||
mail_json["labels"] = client_response.data.get("labelIds", [])
|
||||
mail_json["messageId"] = client_response.data["id"]
|
||||
mail_json["threadId"] = client_response.data["threadId"]
|
||||
mail_json["historyId"] = client_response.data.get("historyId")
|
||||
mail_json["snippet"] = client_response.data.get("snippet", mail_message.subject)
|
||||
mail_json["sizeEstimate"] = client_response.data.get("sizeEstimate")
|
||||
|
||||
# HANDLE ATTACHMENTS HERE:
|
||||
mail_json["payload"] = self.drop_attachments(mail_json["payload"])
|
||||
|
||||
# Now we structure the message into the model:
|
||||
all_recipients = []
|
||||
for field in ["to", "cc", "bcc"]: all_recipients += [item["email"] for item in mail_json[field]]
|
||||
mail_message = CoreMessageModel(
|
||||
ts = mail_json["ts"] or now,
|
||||
syncTs = now,
|
||||
tokenId = auth_token.authTokenId,
|
||||
serviceType = auth_token.serviceType,
|
||||
client = auth_token.client,
|
||||
clientMessageId = client_response.data["id"],
|
||||
clientThreadId = client_response.data["threadId"],
|
||||
isSent = True,
|
||||
isBroadcast = False,
|
||||
sentSuccessfully = True,
|
||||
sender = [mail_json["from"][0]["name"]],
|
||||
recipient = all_recipients,
|
||||
chat = None,
|
||||
message = mail_json,
|
||||
snippet = mail_json["subject"],
|
||||
aiSnippet = None,
|
||||
tags = ["Email", "Gmail", "Sent"]
|
||||
)
|
||||
|
||||
# Invoke the LLM:
|
||||
try:
|
||||
ai_snippet = await self.summarize_mail_with_ai(
|
||||
mongo_data_conn = mongo_data_conn,
|
||||
user_info = user_info,
|
||||
llm = llm,
|
||||
message = mail_message,
|
||||
prompt_template = self.SENT_MAIL_SUMMARIZATION_PROMPT_TEMPLATE
|
||||
)
|
||||
mail_message.aiSnippet = ai_snippet.summary
|
||||
except Exception as exception:
|
||||
self._printer(exception)
|
||||
|
||||
# Save the message to the database:
|
||||
success = await mongo_data_conn.replace_one(
|
||||
collection = self.MESSAGES_COLLECTION,
|
||||
filter = {
|
||||
"tokenId": ObjectId(auth_token.authTokenId),
|
||||
"serviceType": auth_token.serviceType,
|
||||
"client": auth_token.client,
|
||||
"clientMessageId": mail_message.clientMessageId
|
||||
},
|
||||
replacement = mail_message.model_dump(),
|
||||
upsert = True
|
||||
)
|
||||
|
||||
# Done here:
|
||||
send_result.success = True
|
||||
send_result.message = f"Mail sent successfully."
|
||||
return send_result
|
||||
|
||||
# ┳┳┓ •┓ ┳┳ ┓ •
|
||||
# ┃┃┃┏┓┓┃ ┃┃┏┓┏┫┏┓╋┓┏┓┏┓
|
||||
|
||||
Reference in New Issue
Block a user