I'm trying to send out an email using python's smptlib, which seems to be working fine except the subject key does not get attached. (image [1]: https://i.sstatic.net/XkpLh.png)
I've looked at other solutions but none of them work for me. They are solving mostly for text based additions in the form of headers but my code involves sending a dataframe as a table which gets messed up when I try these solutions.
Posts I've looked at:
Python: "subject" not shown when sending email using smtplib module
Subject line not coming in the smtp mail sent from python
Python smtplib sendmail() not working with subject / body
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from tabulate import tabulate
sender = 'email@email.com'
recipients = 'email@email.com'
subject = "Test Email 1234"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = ", ".join(recipients)
msg['Subject'] = subject
# Create the body of the message (a plain-text and an HTML version).
text = """
text
{table}
text
"""
html = """
<html>
<head>
<style>
table, th, td {{ border: 1px solid black; border-collapse: collapse; text-align: center;}}
th, td {{ padding: 8px; }}
</style>
</head>
<body><p>text </p>
<br><br><br>
{table}
<br><br><br>
<p>Regards,</p>
<p>abc</p>
</body></html>
"""
col_list = list(df.columns.values)
data = df
# above line took every col inside csv as list
text = text.format(table=tabulate(data, headers=col_list, tablefmt="grid"))
html = html.format(table=tabulate(data, headers=col_list, tablefmt="html"))
msg = MIMEMultipart("alternative", None, [MIMEText(text), MIMEText(html,'html')])
# Send the message via local SMTP server.
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("email@gmail.com", "pw")
server.sendmail(sender,recipients, msg.as_string())
server.quit()
Your settings
msg['From'] = sender
msg['To'] = ", ".join(recipients)
msg['Subject'] = subject
will be overwritten, as soon as you do
msg = MIMEMultipart("alternative", None, [MIMEText(text), MIMEText(html,'html')])
later on.
Just switch their order and remove the first msg = MIMEMultipart()
.