skip to Main Content

How to send HTML content in email using Python? I want to sent table content from csv but can’t install package more(in this work). Thank you

Please recommend methods or documents. To solve the problems I encountered and still couldn’t find a solution.

2

Answers


  1. you could convert your data in csv to json and then to HTML.
    I am using json2html to convert the json data to HTML. if you can’t do the pip, you could try to include some useful code into your python project(https://github.com/softvar/json2html)

    for sending email, you could use smtplib with a valid smtp server.

        msg = EmailMessage()
        msg.add_alternative(report_html, subtype="html")
        msg["Subject"] = 'email subject'
        msg["From"] = 'mail_origin'
        msg["To"] = 'mail_recipient'
        s = smtplib.SMTP("your smtp server")
        s.send_message(msg)
        s.quit()
    
    Login or Signup to reply.
  2. This is the method I’m using for one task,

    sendSuccessEmail(dataframe) that sends an email with an attached Excel file containing data from a pandas DataFrame. Let’s break down how the code works:

    1. Email Parameters:

      • from_address: Sender’s email address.
      • to_address: Recipient’s email address.
      • cc_address: List of email addresses for carbon copy (CC).
      • subject: Email subject.
      • message: Email body message.
    2. Email Message Creation:

      • The function creates an email message using the MIMEMultipart class from the email.mime.multipart module.
      • It sets the sender, recipient, CC, date, and subject headers.
      • The email body is set using the MIMEText class.
    3. DataFrame to Excel:

      • The pandas DataFrame (dataframe) is converted to an Excel file (Results YYYY-MM-DD.xlsx).
    4. Attachment Creation:

      • The Excel file is opened and read in binary mode (rb).
      • A MIMEBase object is created to represent the attached file.
      • The payload is set to the content of the Excel file.
      • The payload is encoded using Base64.
      • The attachment’s header is set with the file name.
    5. Attachment Addition:

      • The attachment is added to the email message.
    6. SMTP Connection and Email Sending:

      • The script connects to the SMTP server (smtp.office365.com) on port 587.
      • It starts TLS encryption for a secure connection.
      • It logs in using the sender’s email address and password.
      • The email is sent using the sendmail method with the sender’s address, recipient’s address, and the email message as a string.
      • The SMTP connection is closed.
    7. Error Handling:

      • If an exception occurs during the email sending process, the script waits for 5 seconds, prints the error message, and continues. This helps handle potential issues like network errors or server unavailability.
    8. Success Message:

      • If the email is sent successfully, a success message is printed.
      • A 10-second delay is added, possibly to allow time for the email to be processed or to prevent any immediate repetitive actions.

    Note: The script uses the smtplib library for sending emails and time for introducing delays. Ensure that the sender’s email, password, SMTP server details, and recipients’ email addresses are correctly provided. It’s recommended to use application-specific passwords or other secure methods instead of the actual email password.

    import requests
    import pandas as pd
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.base import MIMEBase
    from email.mime.text import MIMEText
    from email.utils import COMMASPACE, formatdate
    from email import encoders
    from datetime import date
    import time
    
    def sendSuccessEmail(dataframe):
    
        try:
            # Set the email parameters
            from_address = "[email protected]"
            to_address = "[email protected]"
            cc_address = ["[email protected]","[email protected]"]
            subject = "Data"
            message = "Please find the Data"
    
            # Create the email message
            msg = MIMEMultipart()
            msg['From'] = from_address
            msg['To'] = to_address
            msg['Cc'] = ", ".join(cc_address)  # Join the list with commas
            msg['Date'] = formatdate(localtime=True)
            msg['Subject'] = subject
    
            msg.attach(MIMEText(message))
    
            # Convert the DataFrame to Excel
            file_name = f"Results {date.today().strftime('%d-%m-%Y')}.xlsx"
            dataframe.to_excel(file_name, index=False)
    
            # Read the Excel file you want to attach
            excel_file = open(file_name, "rb")
    
            # Create a MIMEBase object to attach the file
            part = MIMEBase("application", "octet-stream")
            part.set_payload((excel_file).read())
    
            # Encode the payload using Base64
            encoders.encode_base64(part)
    
            # Add header with the file name
            part.add_header("Content-Disposition", f"attachment; filename= {file_name}")
    
            # Add the attachment to the email message
            msg.attach(part)
    
            # Connect to the SMTP server and send the email
            smtp_server = smtplib.SMTP('smtp.office365.com', 587)
            smtp_server.ehlo()
            smtp_server.starttls()
            smtp_server.ehlo()
            smtp_server.login(from_address, "your_password")
            smtp_server.sendmail(from_address, to_address, msg.as_string())
            smtp_server.close()
        except Exception as e:
            time.sleep(5)
            print(f"Error in sending mail: {e}")
            pass
        print("Email sent successfully!")
        time.sleep(10)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search