Python Email in HTML format mimelib

谁都会走 提交于 2019-12-01 12:48:07

问题


I am trying to send two dataframes created in Pandas Python as a html format in an email sent from the python script.

I want to write a text and the table and repeat this for two more dataframes but the script is not able to attach more than one html block. The code is as follows:

import numpy as np
import pandas as pd
import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

sender = "blabla@gmail.com"
recipients = ['albalb@gmail.com']
msg = MIMEMultipart('alternative')
msg['Subject'] = "This a reminder call " + time.strftime("%c")
msg['From'] = sender
msg['To'] = ", ".join(recipients)

text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
html = df[['SYMBOL','ARBITRAGE BASIS %']].to_html()

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(part1)
msg.attach(part2)

username = 'blabla@gmail.com'
password = 'blahblah'
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(sender, recipients, msg.as_string())
server.quit()        
print("Success")

I am getting an email with just the last part as a formatted html table in the email body. The part 1 text is not appearing. What's wrong?


回答1:


Use yagmail (full disclose: I'm the maintainer/developer):

import time
import yagmail
yag = yagmail.SMTP(username, password)

text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
html = df[['SYMBOL','ARBITRAGE BASIS %']].to_html()

yag.send('albalb@gmail.com', "This a reminder call " + time.strftime("%c"), [text,html])

yagmail exists to make it really easy for us to send emails using attachments, images, and html among other things.

Get started by installing it using

pip install yagmail



回答2:


The problem is that you are marking up the parts as multipart/alternative -- this means, "I have the information in multiple renderings; choose the one you prefer" and your email client is apparently set up to choose the HTML version. Both parts are in fact there, but you have tagged them as either/or where apparently you want both.

The conventional quick fix would be to switch to multipart/related but really, what is the purpose of a text part which simply says the content is elsewhere?

If you want the HTML as an attachment, maybe also set Content-Disposition: attachment (and supply a file name) for the HTML part.



来源:https://stackoverflow.com/questions/33627662/python-email-in-html-format-mimelib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!