[Python] Attach picture in e-mail

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have a problem with a Python script. It creates an e-mail with a pandas datasource. I would like to add one or more pictures but I can not. Without the pictures it works properly.

    I ask you to help me in order to fix the problem.

    import cx_Oracle
    import pandas as pd
    import sqlalchemy
    import smtplib
    import matplotlib

    from email.mime.text import MIMEText
    from email.header import Header
    from email.mime.image import MIMEImage

    image_path="C:\\Users\\n.restaino\\PycharmProjects\\pythonProject\\.venv\\barchart1.png"

    def send_simple_email(host, subject, from_addr, to_addr, body, password):
    # Instantiate MIMEText object
    message = MIMEText(body, 'html', 'utf-8')
    message['From'], message['To'] = from_addr, to_addr
    message['Subject'] = Header(subject, "utf-8")
    message = message.as_string() # Because SMTP.sendmail, required bytes-like string. Otherwise you will see error like: Error: expected string or bytes-like object

    try:
    import ssl
    context = ssl.create_default_context()
    server = smtplib.SMTP_SSL(host, 465, context=context)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], message)
    except Exception as e:
    print(f"Error: {e}")
    finally:
    server.quit()
    print("Email Sent!")

    if __name__ == "__main__":
    # Connection details
    user = 'USER'
    pw = 'PWD'
    host = '10.0.0.1'
    port = '1521'
    db = 'DB'

    engine = sqlalchemy.create_engine('oracle+cx_oracle://' + user + ':' + pw + '@' + host + ':' + port + '/?service_name=' + db)
    my_query='SELECT * FROM T_C10'
    df = pd.read_sql(my_query, engine)
    ax = df.plot.bar(x='tipo', y='numero', rot=0)

    fig = ax.get_figure()
    fig.savefig(image_path)

    host = "smtp.gmail.com" # Using Gmail server to send the email
    subject = "[AUTO EMAIL] Report Sales"
    html_body = f"""<h1> Sales Report </h1> {df.to_html()}
    <img src={image_path} alt="The Python logo">
    """

    from_addr, to_addr = "C.D@gmail.com", "A.B@gmail.com"

    # Open the image file in binary mode

    # Get Passwork from user
    import getpass

    password = '1234 5678 ' # getpass.getpass()''

    # Sending Email
    send_simple_email(host, subject, from_addr, to_addr, html_body, password)

    Continue reading...

Compartilhe esta Página