(20241126) GMail v2 started with better data handling and feedback.
This commit is contained in:
@@ -97,7 +97,7 @@ from typing import List
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
class MailMessage:
|
||||
class SMTPMessage:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -212,7 +212,7 @@ class MailMessage:
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
class AsyncMailClient:
|
||||
class AsyncSMTPClient:
|
||||
|
||||
# Constants:
|
||||
SMTP_TLS_PORT = 587
|
||||
@@ -336,7 +336,7 @@ class AsyncMailClient:
|
||||
self.__smtp = None
|
||||
return True
|
||||
|
||||
async def send(self, mail: MailMessage):
|
||||
async def send(self, mail: SMTPMessage):
|
||||
|
||||
"""
|
||||
Send out the mail.
|
||||
@@ -395,14 +395,14 @@ if __name__ == "__main__":
|
||||
|
||||
async def test():
|
||||
|
||||
mail_client = AsyncMailClient(
|
||||
mail_client = AsyncSMTPClient(
|
||||
email = "sender@gmail.com",
|
||||
password = "zcaf nmqy ncfz fave",
|
||||
server = "smtp.gmail.com",
|
||||
rate_limiters = None
|
||||
)
|
||||
|
||||
my_mail = MailMessage(
|
||||
my_mail = SMTPMessage(
|
||||
to_email = "orangebhopli@gmail.coms",
|
||||
subject = "Bhopli is the best!",
|
||||
cc_emails = None,
|
||||
@@ -1,268 +0,0 @@
|
||||
"""
|
||||
|
||||
AUTHOR:
|
||||
|
||||
Khushal P Soonderji
|
||||
|
||||
DATE:
|
||||
|
||||
Tuesday, 16th Jul, 2024
|
||||
|
||||
OBJECTIVE:
|
||||
|
||||
To be able to send out mails from code.
|
||||
|
||||
REFERENCES:
|
||||
|
||||
N/A
|
||||
|
||||
DOWNLOADS:
|
||||
|
||||
N/A
|
||||
|
||||
"""
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** IMPORT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# To make sibling directories accessible for imports:
|
||||
import sys
|
||||
sys.path.append(".")
|
||||
sys.path.append("..")
|
||||
|
||||
# For working with mails:
|
||||
import aiosmtplib
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.image import MIMEImage
|
||||
from email.mime.text import MIMEText
|
||||
from email.mime.base import MIMEBase
|
||||
from email import encoders
|
||||
|
||||
# My utils:
|
||||
from utils import rate_limit_utils
|
||||
|
||||
# Common:
|
||||
from shared.statuses import StatusCodes
|
||||
|
||||
# For random strings:
|
||||
import string
|
||||
import random
|
||||
|
||||
# For system-level activities:
|
||||
import os
|
||||
|
||||
# For working with files in RAM:
|
||||
import io
|
||||
|
||||
# For debugging:
|
||||
from icecream import IceCreamDebugger
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MACROS / ONE-TIME INIT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** VARIABLES ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** FUNCTIONS ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** CLASSES ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
class MailMessage:
|
||||
|
||||
def __init__(self, to_email, subject):
|
||||
|
||||
"""
|
||||
Create an instance of the message that you would like to send.
|
||||
:param to_email: The EMail ID of th recipient.
|
||||
:param subject: The subject of the mail.
|
||||
"""
|
||||
|
||||
self.message = MIMEMultipart()
|
||||
self.message["To"] = to_email
|
||||
self.message["Subject"] = subject
|
||||
|
||||
def add_text(self, text):
|
||||
|
||||
"""
|
||||
Add plain-text to the mail body.
|
||||
:param text: The text to add to the mail body.
|
||||
:return: None.
|
||||
"""
|
||||
|
||||
self.message.attach(MIMEText(text, "plain"))
|
||||
|
||||
def add_html(self, html_text):
|
||||
|
||||
"""
|
||||
Add HTML text to the mail body.
|
||||
:param html_text: The HTML text to add to the mail body.
|
||||
:return: None.
|
||||
"""
|
||||
|
||||
self.message.attach(MIMEText(html_text, "html"))
|
||||
|
||||
def add_inline_image(self, image_file, content_id = None):
|
||||
|
||||
"""
|
||||
Add an inline image to the body of the mail.
|
||||
NOTE: This is NOT the same as sending an image as an attachment.
|
||||
:param image_file: The image data to attach to the mail body.
|
||||
:param content_id: Inline images are inserted via HTML bocks. This field identifies the image resource. If not
|
||||
specified, I will generate a random string. You may write a custom value here if you know what you are
|
||||
doing. For most use cases, please ignore this field.
|
||||
:return: None.
|
||||
"""
|
||||
|
||||
# Read the image as bytes:
|
||||
image_bytes = None
|
||||
if type(image_file) is str:
|
||||
with open(image_file, "rb") as opened_image_file:
|
||||
image_bytes = opened_image_file.read()
|
||||
if type(image_file) is io.BytesIO:
|
||||
image_file.seek(0)
|
||||
image_bytes = image_file.getvalue()
|
||||
|
||||
# Declare the part to be attached to the multipart message:
|
||||
if image_bytes is not None:
|
||||
|
||||
# Create the HTML block if the image pointer is blank:
|
||||
if content_id is None:
|
||||
content_id = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8))
|
||||
self.add_html(f"""
|
||||
<html>
|
||||
<body>
|
||||
<p><img src="cid:{content_id}"></p>
|
||||
</body>
|
||||
</html>
|
||||
""")
|
||||
|
||||
# Then add the image:
|
||||
image_part = MIMEImage(image_bytes)
|
||||
image_part.add_header("Content-ID", f"<{content_id}>")
|
||||
self.message.attach(image_part)
|
||||
|
||||
def add_attachment(self, attachment_file, file_name = None):
|
||||
|
||||
# Declare the part to be attached to the multipart message:
|
||||
part = MIMEBase("application", "octet-stream")
|
||||
|
||||
# If the attachment is a file stored in the local disk:
|
||||
if type(attachment_file) is str:
|
||||
file_name = file_name or os.path.split(attachment_file)[-1]
|
||||
with open(attachment_file, "rb") as attachment:
|
||||
part.set_payload(attachment.read())
|
||||
|
||||
# If the file is held in RAM:
|
||||
if type(attachment_file) is io.BytesIO():
|
||||
attachment_file.seek(0)
|
||||
part.set_payload(attachment_file.read())
|
||||
|
||||
# Encode and attach the file:
|
||||
encoders.encode_base64(part)
|
||||
part.add_header(
|
||||
"Content-Disposition",
|
||||
f"attachment; filename= {file_name}",
|
||||
)
|
||||
self.message.attach(part)
|
||||
|
||||
def get_message(self):
|
||||
return self.message
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MAIN PROGRAM ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
import asyncio
|
||||
from utils import json_utils
|
||||
from utils_v2.mail.async_mail import AsyncMailClient
|
||||
|
||||
async def test():
|
||||
|
||||
rate_lim = rate_limit_utils.TokenBucket(
|
||||
rate_limit = 1,
|
||||
seconds = 60.0,
|
||||
)
|
||||
|
||||
mail_client = AsyncMailClient(
|
||||
email = "sender@gmail.com",
|
||||
password = "secret_password",
|
||||
server = "smtp.gmail.com",
|
||||
rate_limiters = rate_lim
|
||||
)
|
||||
|
||||
my_mail = MailMessage(
|
||||
to_email = "recipient@gmail.com",
|
||||
subject = "Bhopli is the best!"
|
||||
)
|
||||
my_mail.add_html(
|
||||
"""
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Sample HTML String</title>
|
||||
<style>
|
||||
.heading {
|
||||
color: #ff9025;
|
||||
}
|
||||
.sub-heading {
|
||||
color: #000000;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1 class="heading">Hello, Bhopli!</h1>
|
||||
<h2 class="sub-heading">Bhopli is the best, most well-behaved cat in the known universe.</h2>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
)
|
||||
my_mail.add_text("This is how you should pet her 👇")
|
||||
my_mail.add_inline_image(r"/path/to/image/cat_petting.png")
|
||||
my_mail.add_attachment(r"/path/to/file/sample_label.pdf")
|
||||
|
||||
await mail_client.login()
|
||||
result = await mail_client.send(my_mail)
|
||||
print("MAIL RESULT:", json_utils.to_json_string(result))
|
||||
await mail_client.logout()
|
||||
|
||||
asyncio.run(test())
|
||||
@@ -0,0 +1,137 @@
|
||||
"""
|
||||
|
||||
AUTHOR:
|
||||
|
||||
Khushal P Soonderji
|
||||
|
||||
DATE:
|
||||
|
||||
Tuesday, 26th Nov., 2024
|
||||
|
||||
OBJECTIVE:
|
||||
|
||||
To parse raw mail bodies and give a structure that is suitable for storing in No-SQL databases like MongoDB. The
|
||||
raw mail's text is expected to be compliant with standard defined in RFC 5322, RFC 2045, and maybe a few more.
|
||||
|
||||
REFERENCES:
|
||||
|
||||
1. GitHub: https://github.com/SpamScope/mail-parser
|
||||
2. RFC 5322: https://datatracker.ietf.org/doc/html/rfc5322
|
||||
3. RFC 2045: https://datatracker.ietf.org/doc/html/rfc2045
|
||||
|
||||
DOWNLOADS:
|
||||
|
||||
N/A
|
||||
|
||||
"""
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** IMPORT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# To make sibling directories accessible for imports:
|
||||
import sys
|
||||
sys.path.append(".")
|
||||
sys.path.append("..")
|
||||
|
||||
# System-level activities:
|
||||
import io
|
||||
|
||||
# My utils:
|
||||
from utils_v2.string import json
|
||||
from utils_v2.string import regex
|
||||
from utils_v2.date_time import date_time
|
||||
|
||||
# To work with mails:
|
||||
import mailparser
|
||||
|
||||
# To work with datatypes:
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MACROS / ONE-TIME INIT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** VARIABLES ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** FUNCTIONS ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
def parse(raw_mail: str | bytes) -> Dict[str, Any]:
|
||||
|
||||
"""
|
||||
To parse the raw mail text to a usable JSON that can even be stored on a No-SQL database like MongoDB.
|
||||
DOCUMENTATION:
|
||||
1. GitHub: https://github.com/SpamScope/mail-parser
|
||||
2. RFC 5322: https://datatracker.ietf.org/doc/html/rfc5322
|
||||
3. RFC 2045: https://datatracker.ietf.org/doc/html/rfc2045
|
||||
:param raw_mail: The raw mail body that adheres to RFC 5322 and RFC 2045 (among others).
|
||||
:return: The parsed JSON format (dict) of the mail.
|
||||
"""
|
||||
|
||||
# Parse the raw format:
|
||||
if isinstance(raw_mail, str): parsed_mail = mailparser.parse_from_string(raw_mail)
|
||||
else: parsed_mail = mailparser.parse_from_bytes(raw_mail)
|
||||
|
||||
# Format the attachments:
|
||||
message_attachments = [
|
||||
{
|
||||
"filename": attachment["filename"],
|
||||
"type": attachment["mail_content_type"],
|
||||
"cid": regex.find_first(text = attachment["content-id"], pattern = r"(?<=<).*(?=>)"),
|
||||
"rawCid": attachment["content-id"],
|
||||
"contentDisposition": (cd := attachment["content-disposition"]),
|
||||
"isInline": True if cd.lower().find("inline") >= 0 else False,
|
||||
"charset": attachment["charset"],
|
||||
"contentTransferEncoding": attachment["content_transfer_encoding"],
|
||||
"payload": attachment["payload"]
|
||||
} for attachment in parsed_mail.attachments
|
||||
]
|
||||
|
||||
# Put everything together:
|
||||
return {
|
||||
"ts": date_time.to_timezone(parsed_mail.date, timezone = date_time.TIMEZONE_UTC),
|
||||
"headers": parsed_mail.headers,
|
||||
"from": [{"name": _[0] or _[1], "email": _[1]} for _ in parsed_mail.headers["From"]],
|
||||
"to": [{"name": _[0] or _[1], "email": _[1]} for _ in parsed_mail.headers["To"]],
|
||||
"cc": [{"name": _[0] or _[1], "email": _[1]} for _ in parsed_mail.headers.get("Cc", [])],
|
||||
"bcc": [{"name": _[0] or _[1], "email": _[1]} for _ in parsed_mail.headers.get("Bcc", [])],
|
||||
"text": parsed_mail.text_plain,
|
||||
"html": parsed_mail.text_html,
|
||||
"attachments": message_attachments,
|
||||
}
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MAIN PROGRAM ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
pass
|
||||
Reference in New Issue
Block a user