Emails automatically falls on spam

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.

You mean that the email you send is being filed as SPAM?

If so that would seem to be a problem with the contents of the email or that is sent from an untrusted source. Not something you can fix in python.

In previous it works well with cc also as multiple mail id but now it’s not working…

Note: 1st I’ve run as a python file runs, then I convert into exe also it runs but now not running.

Blockquoteimport smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import ssl

def send_email():
# Email server configuration
smtp_server = ‘smtpout.secureserver.net
smtp_port = 465 # For SSL
smtp_user = ‘personhd@test.com’
smtp_pass = ‘*****************’

# Sender and recipient details
from_addr = 'personhd@test.com'
to_addr = ['person1@test.com', 'person2@test.com','person3@test.com']
cc_addr = [ 'personhd@test.com','person3@test.com']  # Optional

# Email content
subject = 'Subject of your email'
body = """
    <html>
    <head></head>
    <body>
        <p>Hello,<br>
           This is a test email message.<br>
           Regards,<br>
           Sender
        </p>
    </body>
    </html>
    """

# Create MIME message
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = ', '.join(to_addr)
msg['Cc'] = ', '.join(cc_addr) if cc_addr else ''
msg['Subject'] = subject
msg.attach(MIMEText(body, 'html'))

# Create SSL context
context = ssl.create_default_context()

try:
    # Connect to SMTP server securely
    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())
    print("Email sent successfully.")
except Exception as e:
    print(f"Error sending email: {str(e)}")

if name == “main”:
send_email()

now i create a new py file and tried to run it but CC person have fall on spam similar in sometimes even for anyone in to_mail also fall in spam