Search code examples
pythonhtmlemailpandasmime

HTML and Text in Python Driven Email


I am using MIMEMultipart to send emails from Python. The code is as follows:

sender = "EMAIL"
recipients = ["EMAIL"]
msg = MIMEMultipart('alternative')
msg['Subject'] = "Subject Text"
msg['From'] = sender
msg['To'] = ", ".join(recipients)

html = PandasDataFrame.to_html()
part2 = MIMEText(html, 'html')
msg.attach(part2)

SERVER = "SERVER"
server = smtplib.SMTP(SERVER)
server.sendmail(sender, recipients, msg.as_string())
server.quit()  

This inserts a Python Pandas dataframe as HTML and works fine. Is it possible to add footnotes as text to the email body as well? How would the code work for doing both? Alternatively, I'm fine adding comments as HTML but more of less need some footnotes added to the email body.

Thanks


Solution

  • This code works:

    First, import:

    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.application import MIMEApplication #Used for attachments
    import smtplib
    

    And the code:

    sender = "EMAIL"
    recipients = ["EMAIL1","EMAIL2"]
    msg = MIMEMultipart('mixed') #use mixed instead of alternative to load multiple things 
    msg['Subject'] = "Subject Text"
    msg['From'] = sender
    msg['To'] = ", ".join(recipients)
    
    html = PandasDataFrame1.to_html() #first dataframe
    
     #insert text as follows
    html += '''
        <br><br>
        This is a new line of random text.
        <br><br>
    '''
    
    html += PandasDataFrame2.to_html() #second dataframe
    
    #put the html into the email body
    html = MIMEText(html, 'html') 
    msg.attach(html)
    

    If you also want to attach a file to the email, use this code

    ATTACHMENT_PATH = 'path\\file.type'
    with open(ATTACHMENT_PATH, 'r') as fileobj:
        attachment = MIMEApplication(fileobj.read(), Name='file.type')
    attachment['Content-Disposition'] = 'attachment; filename="file.type"'
    msg.attach(attachment)
    

    And the code to send using a server

    SERVER = "SERVER"
    server = smtplib.SMTP(SERVER)
    server.sendmail(sender, recipients, msg.as_string())
    server.quit()