Friday, February 21, 2025

Sending email from Python

 Can setup SMTP inside python itself but for better protection, setup sendmail with SMTP as in other post and then:


import subprocess
import os
import argparse
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

def send_file_as_email(file_path, to, subject):
    """Sends an HTML file as the email body and also as an attachment."""
   
    # If subject is None, use the base file name
    if subject is None:
        subject = os.path.basename(file_path)

    # Create the email with mixed content (text + attachments)
    message = MIMEMultipart("mixed")
    message["Subject"] = subject
    message["To"] = to

    # Read HTML content and attach as email body
    with open(file_path, "r") as file:
        html_content = file.read().strip()

    html_body = MIMEText(html_content, "html")
    message.attach(html_body)

    # Attach the file as an attachment
    with open(file_path, "rb") as file:
        attachment = MIMEBase("application", "octet-stream")
        attachment.set_payload(file.read())

    # Encode to base64
    encoders.encode_base64(attachment)
    attachment.add_header("Content-Disposition", f'attachment; filename="{os.path.basename(file_path)}"')
    message.attach(attachment)

    # Send email using sendmail
    process = subprocess.Popen(["/usr/sbin/sendmail", "-t", "-i"], stdin=subprocess.PIPE)
    process.communicate(message.as_bytes())

    print("Email sent successfully!")

def main():
    """Parses command-line arguments and sends an email."""
   
    parser = argparse.ArgumentParser(description="Send an HTML file as an email body & attachment.")
    parser.add_argument("-f", "--file", required=True, help="Path to the HTML file")
    parser.add_argument("-t", "--to", default="harshal.patil@firl.com", help="Recipient email address (default: harshal.patil@firm.com)")
    parser.add_argument("-s", "--subject", default=None, help="Email subject (default: file name)")

    args = parser.parse_args()

    send_file_as_email(args.file, args.to, args.subject)

if __name__ == "__main__":
    main()

No comments:

Post a Comment