Blockquotefrom email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import ssl
import smtplib
def fetch_data_and_send_email(self, conn):
try:
# Fetch mail configuration data
sql_query_mailconfig = ‘EXEC [GetData_mailconfig]’
df_config = pd.read_sql(sql_query_mailconfig, conn)
if df_config.empty:
print(“No mail configuration data found.”)
return None
# Extract mail configuration details
mail_config = df_config.iloc[0]
from_addr = mail_config['From_Mail']
to_addr = mail_config['To_Mail'].split(',') if mail_config['To_Mail'] else []
cc_addr = mail_config['CC_Mail'].split(',') if mail_config['CC_Mail'] else []
smtp_server = mail_config['Server_Name']
smtp_user = mail_config['From_Mail']
smtp_pass = mail_config['Password']
smtp_port = mail_config['Port']
mail_type = mail_config['Mail_Type']
# Execute SQL query to get summary data
sql_query_summary = 'EXEC Getdata_Summary_Ramp_website'
summary_df = pd.read_sql(sql_query_summary, conn)
if summary_df.empty:
print("No data returned from Getdata_Summary.")
return None
summary_html = summary_df.to_html(index=False)
print(summary_html)
# Prepare email body
body = f"""
<html>
<head></head>
<body>
<p>Please find the summary data below:</p>
<h3>Summary Data from Getdata_Summary_Mail:</h3>
{summary_html}
<p>Regards,<br> Ecosoft Zolutions</p>
</body>
</html>
"""
# Send email based on Mail_Type
if mail_type in ['MOL', 'All']:
self.send_email(from_addr, to_addr, cc_addr, smtp_server, smtp_port, smtp_user, smtp_pass, 'Subject', body)
print("Email sent successfully.")
return summary_df # Return the DataFrame if email sent successfully
else:
print("Unsupported Mail_Type:", mail_type)
return None
except pyodbc.Error as e0:
print(f"Database connection error: {str(e0)}")
log_error_to_db(r'N\A', 'Error for Fetch Email and Send Email', e0, server)
return None
except pd.errors.EmptyDataError as e1:
print("No data returned from Getdata_Summary.")
log_error_to_db(r'N\A', 'Error for Fetch Email and Send Email', e1, server)
return None
except smtplib.SMTPException as e2:
print(f"SMTP error occurred: {str(e2)}")
log_error_to_db(r'N\A', 'Error Fetch Email and Send Email', e2, server)
return None
except Exception as e3:
print(f"Error occurred: {str(e3)}")
log_error_to_db(r'N\A', 'Error for Fetch Email and Send Email', e3, server)
return None
def send_email(self, from_addr, to_addr, cc_addr, smtp_server, smtp_port, smtp_user, smtp_pass, subject, body):
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = ', '.join(to_addr) if to_addr else ''
msg['Cc'] = ', '.join(cc_addr) if cc_addr else ''
subject = 'Last one day data of Ramp'
msg['Subject'] = subject
msg.attach(MIMEText(body, 'html'))
# Create SSL context
context = ssl.create_default_context()
try:
# Send email using SMTP with SSL/TLS
with smtplib.SMTP_SSL(smtp_server, smtp_port, context=context) as server:
server.login(smtp_user, smtp_pass)
server.sendmail(from_addr, to_addr + cc_addr, msg.as_string())
server.quit()
except smtplib.SMTPException as error_message:
print(f"SMTP error occurred: {str(e)}")
log_error_to_db(r'N\A', 'SMTP error occurred', error_message, server)
raise # Re-raise exception for higher-level handling
except Exception as e:
print(f"Error occurred while sending email: {str(e)}")
Blockquote when I run my code in earlier days the mail received in inbox and it’s fine but now it’s falls on spam, I can’t find a reason. thanks in advance. suggestions are always welcome.