Your IP : 216.73.217.79


Current Path : /var/www/cesa.co.za/python/
Upload File :
Current File : //var/www/cesa.co.za/python/send-mail.py

import sys
import smtplib
from email import policy
from email.parser import BytesParser
from pathlib import Path

def main():
    print(len(sys.argv))
    if len(sys.argv) != 8:
        print("Usage:")
        print("python3 send_raw_email.py <raw_file_path> <from_email> <to_email> <smtp_host> <smtp_port> <smtp_user> <smtp_pass>")
        sys.exit(1)

    raw_file_path, from_email, to_email, smtp_host, smtp_port, smtp_user, smtp_pass = sys.argv[1:]

    # Load raw message from file
    try:
        file_string = Path(raw_file_path).read_text(encoding="utf-8")
        raw_bytes = Path(raw_file_path).read_bytes()
        msg = BytesParser(policy=policy.SMTP).parsebytes(raw_bytes)
    except Exception as e:
        print(f"Failed to read or parse raw message file: {e}")
        sys.exit(1)

    try:
        smtp_port = int(smtp_port)
        with smtplib.SMTP(smtp_host, smtp_port) as server:
            server.ehlo()
            if smtp_port == 587:
                server.starttls()
                server.ehlo()
            server.login(smtp_user, smtp_pass)
            server.sendmail(from_email, [to_email], file_string.encode("utf-8"))
            print("Email sent successfully.")
    except Exception as e:
        print(f"Error sending email: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()