I can't able to figure out why my python code can't attach HTML table (part2) and plain sentence(part1) at a same email. I tried commenting one line message.attach(part2)
and it works vice versa. There's something wrong with the message
object.
port = 587 # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "xyz@gmail.com"
receiver_email = ["abc@qwer.com","def@gmail.com"]
password = getpass.getpass()
message = MIMEMultipart("alternative")
message["From"] = sender_email
message["To"] = ", ".join(receiver_email)
message["Subject"] = "Report"
# Create the plain-text and HTML version of your message
pd.read_csv('tmp.csv').to_html('report_html.html')
html=open('report_html.html').read()
part1=MIMEText("Following are the instances currently running:\n","plain")
part2=MIMEText(html,"html")
message.attach(part1)
message.attach(part2)
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email,password)
server.sendmail(sender_email, receiver_email,
message.as_string())
My separate try with part 1 and part2 output are given below:
You are using the wrong kind of multipart
container. A multipart/alternative
container tells the receiving client "here are multiple variants of the same content; display whichever one suits the user's preferences and your technical capabilities." But you want to say "here are several parts; display all of them, one way or another." A suitable content type for that is multipart/mixed
or possibly multipart/related
instead.