Tuesday, 12 August 2025

Sending Email from Python


 import smtplib, ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
from datetime import datetime

# Convert DataFrame to HTML
html_table = df_errormessage.to_html(index=False)

# Custom statement
custom_statement = "<p>Please find the below error data:</p>"

# Combine statement and HTML table
email_body = f"{custom_statement}<br>{html_table}"

# Get current date
current_date = datetime.now().strftime("%Y-%m-%d")

smail = 'do.not.reply@company.com'
tmail = ['123@company.com', '456@company.com']
sub = f'Error Report - {current_date}'

def send_mail(send_from, send_to, subject, text, isTls=True):
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = ','.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    # Attach the HTML table to the email body
    msg.attach(MIMEText(email_body, 'html'))

    smtp = smtplib.SMTP('outlook.company.com')
    if isTls:
        smtp.starttls()
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.quit()

# Send the email if the condition is met
send_mail(smail, tmail, sub, text)
print(df_errormessage)

No comments:

Post a Comment