You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
79 lines
2.9 KiB
79 lines
2.9 KiB
import base64 |
|
import os |
|
from time import sleep |
|
from mailersend import emails |
|
import dotenv |
|
|
|
class MailSender: |
|
def __init__(self): |
|
dotenv.load_dotenv() |
|
self.mailersend_api_key = os.getenv("MAILERSEND_API_KEY") |
|
self.mailer = emails.NewEmail(mailersend_api_key=self.mailersend_api_key) |
|
self.mail_body = {} |
|
self.set_mail_to(recipients=input("Enter recipient email: ")) |
|
self.set_mail_from() |
|
self.set_reply_to("No Reply", "noreply@assistant.fish") |
|
self.set_subject(input("Enter subject: ")) |
|
plaintext_content = input("Enter plaintext content: ") |
|
self.set_plaintext_content(plaintext_content) |
|
html_content = input("Enter HTML content: ") |
|
if html_content == "": |
|
html_content = plaintext_content |
|
self.set_html_content(html_content) |
|
attachment_path = input("Path to image: ") |
|
if attachment_path != "": |
|
self.set_attachments(attachment_path) |
|
# TODO: Add support for multiple attachments and other types of attachments |
|
|
|
self.send_mail() |
|
|
|
def set_mail_from(self): |
|
mail_from = {"name": "SCI Fish", "email": 'sci@assistant.fish'} |
|
self.mailer.set_mail_from(mail_from, self.mail_body) |
|
|
|
def set_mail_to(self, recipients): |
|
if isinstance(recipients, str): |
|
recipients = [{"name": recipients, "email": recipients}] |
|
elif isinstance(recipients, list): |
|
recipients = [{"name": i, "email": i} for i in recipients] |
|
self.mailer.set_mail_to(recipients, self.mail_body) |
|
|
|
def set_subject(self, subject): |
|
self.mailer.set_subject(subject, self.mail_body) |
|
|
|
def set_html_content(self, html_content): |
|
self.mailer.set_html_content(html_content, self.mail_body) |
|
|
|
def set_plaintext_content(self, plaintext_content): |
|
self.mailer.set_plaintext_content(plaintext_content, self.mail_body) |
|
|
|
def set_reply_to(self, name, email): |
|
reply_to = {"name": name, "email": email} |
|
self.mailer.set_reply_to(reply_to, self.mail_body) |
|
|
|
def set_attachments(self, file_path): |
|
with open(file_path, "rb") as attachment: |
|
att_read = attachment.read() |
|
att_base64 = base64.b64encode(bytes(att_read)) |
|
attachments = [ |
|
{ |
|
"id": os.path.basename(file_path), |
|
"filename": os.path.basename(file_path), |
|
"content": f"{att_base64.decode('ascii')}", |
|
"disposition": "attachment", |
|
} |
|
] |
|
self.mailer.set_attachments(attachments, self.mail_body) |
|
|
|
def send_mail(self): |
|
r = self.mailer.send(self.mail_body) |
|
sleep(4) # wait for email to be sent |
|
if r.split("\n")[0].strip() != "202": |
|
print("Error sending email") |
|
else: |
|
print("Email sent successfully") |
|
|
|
# Example usage |
|
if __name__ == "__main__": |
|
mail_sender = MailSender() |
|
|