Commit ef03be82 authored by Benjamin Krause's avatar Benjamin Krause
Browse files

Set up a simple api

parent 9058e27b
...@@ -3,3 +3,9 @@ install: ...@@ -3,3 +3,9 @@ install:
black: black:
black ./ black ./
start:
uvicorn main:fast_api --reload
increase_file_watches:
sudo sysctl fs.inotify.max_user_watches=500000
...@@ -45,7 +45,7 @@ class MailProvider(BaseModel): ...@@ -45,7 +45,7 @@ class MailProvider(BaseModel):
imap.login(user.mail, user.password) imap.login(user.mail, user.password)
imap.select(mailbox) imap.select(mailbox)
status, messages = imap.search(None, f"Subject {subject_identifier}") status, messages = imap.search(None, f"SUBJECT {subject_identifier}")
if messages[0] == b"": if messages[0] == b"":
print(f"No messages with the subject {subject_identifier} found!") print(f"No messages with the subject {subject_identifier} found!")
return return
...@@ -58,6 +58,7 @@ class MailProvider(BaseModel): ...@@ -58,6 +58,7 @@ class MailProvider(BaseModel):
for response in msg: for response in msg:
if isinstance(response, tuple): if isinstance(response, tuple):
msg = email.message_from_bytes(response[1]) msg = email.message_from_bytes(response[1])
try:
mails.append( mails.append(
Mail( Mail(
date=msg.get("date"), date=msg.get("date"),
...@@ -68,6 +69,8 @@ class MailProvider(BaseModel): ...@@ -68,6 +69,8 @@ class MailProvider(BaseModel):
body=msg.get_payload(decode=True).decode(), body=msg.get_payload(decode=True).decode(),
) )
) )
except Exception as e:
print(e)
imap.close() imap.close()
imap.logout() imap.logout()
return mails return mails
from email.message import EmailMessage
from pprint import pprint from pprint import pprint
import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import RedirectResponse
from app.mail import Mail from app.mail import Mail
from app.mail_provider import MailProvider
from app.user import User from app.user import User
from app.utils import get_mail_formatted_date, subject_identifier from app.utils import get_mail_formatted_date, subject_identifier
from main_programm import mail_providers, create_mail, create_mail_message
mail_providers = dict( class GetMail(BaseModel):
webde=MailProvider( user: User
base_url="web.de", imap_url="imap.web.de", smtp_url="smtp.web.de", smtp_port=587 mailbox: str
)
)
def create_user() -> User: class SendMail(BaseModel):
print("Create a login") from_user: User
mail = input("Type here the mail address: ") to_user: User
password = input("Type here the password to the mail address: ") subject: str
return User(mail=mail, password=password) message: str
def create_receiver() -> User: def init() -> FastAPI:
print("Create a user to receive the email") app = FastAPI()
mail = input("Type here the receiver mail address: ")
return User(mail=mail, password="")
origins = [
"http://localhost",
"http://localhost:8080",
]
def create_mail(from_user: User, to: User) -> Mail: app.add_middleware(
print("Create the a mail.") CORSMiddleware,
date = get_mail_formatted_date() allow_origins=origins,
subject = input("Type here your subject: ") allow_credentials=True,
body = input("Type here your message: ") allow_methods=["*"],
return Mail( allow_headers=["*"],
date=date,
subject=f"{subject} - {subject_identifier}",
mail_from=from_user.mail,
mail_to=to.mail,
cc="",
body=body,
) )
@app.get("/")
def read_root():
return RedirectResponse("/web/dist/index.html")
def create_mail_message(mail: Mail) -> EmailMessage: @app.post("/mails/get")
msg = EmailMessage() def get_mails(data: GetMail):
msg.set_content(mail.body) mails = mail_providers.get("webde").search_relevant_mails(data.user, data.mailbox)
msg["Date"] = mail.date pprint(mails)
msg["Subject"] = mail.subject return mails
msg["From"] = mail.mail_from
msg["To"] = mail.mail_to
msg["CC"] = mail.cc
return msg
def send_mail(): @app.post("/mails/send")
def send_mail(data: SendMail):
print("Send a mail.") print("Send a mail.")
from_user = create_user() from_user = data.from_user
to = create_receiver() to = data.to_user
message = create_mail(from_user, to) message = Mail(
date=get_mail_formatted_date(),
subject=f"{data.subject} - {subject_identifier}",
mail_from=from_user.mail,
mail_to=to.mail,
cc="",
body=data.message,
)
if mail_providers.get("webde").send_mail(from_user, to, create_mail_message(message)): if mail_providers.get("webde").send_mail(from_user, to, create_mail_message(message)):
print("The email was send successfully!") print("The email was send successfully!")
else: else:
print("Failed to send the email!") print("Failed to send the email!")
return app
def get_relevant_mails():
user = create_user() fast_api = init()
mailbox = input("Type here the mailbox, in which you want to search: ")
mails = mail_providers.get("webde").search_relevant_mails(user, mailbox)
pprint(mails)
if __name__ == "__main__": if __name__ == "__main__":
select = input("Type send to 'send' a mail or 'get' to show relevant mails: ") uvicorn.run("main:fast_api", host="0.0.0.0", port=8000, reload=True)
if select == "send":
send_mail()
elif select == "get":
get_relevant_mails()
else:
print("You should type 'send' or 'get'! Try it again.")
from email.message import EmailMessage
from pprint import pprint
from app.mail import Mail
from app.mail_provider import MailProvider
from app.user import User
from app.utils import get_mail_formatted_date, subject_identifier
mail_providers = dict(
webde=MailProvider(
base_url="web.de", imap_url="imap.web.de", smtp_url="smtp.web.de", smtp_port=587
)
)
def create_user() -> User:
print("Create a login")
mail = input("Type here the mail address: ")
password = input("Type here the password to the mail address: ")
return User(mail=mail, password=password)
def create_receiver() -> User:
print("Create a user to receive the email")
mail = input("Type here the receiver mail address: ")
return User(mail=mail, password="")
def create_mail(from_user: User, to: User) -> Mail:
print("Create the a mail.")
date = get_mail_formatted_date()
subject = input("Type here your subject: ")
body = input("Type here your message: ")
return Mail(
date=date,
subject=f"{subject} - {subject_identifier}",
mail_from=from_user.mail,
mail_to=to.mail,
cc="",
body=body,
)
def create_mail_message(mail: Mail) -> EmailMessage:
msg = EmailMessage()
msg.set_content(mail.body)
msg["Date"] = mail.date
msg["Subject"] = mail.subject
msg["From"] = mail.mail_from
msg["To"] = mail.mail_to
msg["CC"] = mail.cc
return msg
def send_mail():
print("Send a mail.")
from_user = create_user()
to = create_receiver()
message = create_mail(from_user, to)
if mail_providers.get("webde").send_mail(from_user, to, create_mail_message(message)):
print("The email was send successfully!")
else:
print("Failed to send the email!")
def get_relevant_mails():
user = create_user()
mailbox = input("Type here the mailbox, in which you want to search: ")
mails = mail_providers.get("webde").search_relevant_mails(user, mailbox)
pprint(mails)
if __name__ == "__main__":
select = input("Type send to 'send' a mail or 'get' to show relevant mails: ")
if select == "send":
send_mail()
elif select == "get":
get_relevant_mails()
else:
print("You should type 'send' or 'get'! Try it again.")
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment