import json
import requests
import os
import smtplib
from dotenv import load_dotenv
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def load_services(file_path):
"""Load the list of URLs from a JSON file."""
with open(file_path, "r") as file:
return json.load(file)
def check_service_status(url):
"""Check the status of a service by sending a GET request."""
try:
response = requests.get(url)
print(f'Url {url} responded with code {response.status_code}')
return {"status": response.status_code, "error": response.status_code >= 400}
except Exception as e:
print(f"{url} was not fetchable: {str(e)}")
return {"status": None, "error": True}
def generate_html_report(status_dict):
"""Generate an HTML report from the status dictionary."""
html_content = """
URL Status Report
URL Status Report
| URL |
Status Code |
Error |
"""
for url, info in status_dict.items():
status = info['status'] if info['status'] is not None else "N/A"
error = "Yes" if info['error'] else "No"
status_class = "status-error" if info['error'] else "status-ok"
html_content += f"""
| {url} |
{status} |
{error} |
"""
html_content += """
"""
return html_content
def send_email(status_dict, server, user, password, receiver):
"""Send an email with the service status report."""
message = MIMEMultipart("alternative")
message["From"] = f"Management - Oceanwave018 <{user}>"
message["To"] = f"Dominik <{receiver}>"
message["Subject"] = "Server Status"
text = "Status deiner Services:\n"
html = generate_html_report(status_dict)
print(html)
message.attach(MIMEText(text, 'plain'))
message.attach(MIMEText(html, 'html'))
try:
with smtplib.SMTP(server, port=os.getenv("MAIL_PORT")) as smtp:
smtp.starttls()
smtp.login(user, password)
smtp.sendmail(user, receiver, message.as_string())
print("Email sent successfully.")
except smtplib.SMTPException as e:
print(f"Failed to send email: {str(e)}")
def main():
print("In Up-Service")
load_dotenv()
# Load environment variables
server = os.getenv("MAIL_SERVER")
user = os.getenv("MAIL_USER")
password = os.getenv("MAIL_PASSWORD")
receiver = os.getenv("EMAIL_RECEIVER")
# Load services and check their status
services = load_services("./services.json")
status_dict = {url: check_service_status(url) for url in services}
print(status_dict)
# Send the email report
send_email(status_dict, server, user, password, receiver)
if __name__ == "__main__":
main()