我正在和熊猫一起工作,但是我希望Dataframe使用df.to_csv创建csv文件并将其附加到电子邮件中,这样收件人就可以将它作为附件使用,而html、df.to_html也能很好地工作。
如何将df.to_csv附加到电子邮件中,以便在其中输入html视图。
下面是我用来发送电子邮件的代码部分示例。
import smtplib
import pandas as pd
from tabulate import tabulate
from email.message import EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
# mail vars
SMTP_SERVER = 'smtp_server@example.com'
FROM = 'some_address@example.com'
TO = ['address@example.com']
SUBJECT = 'test attachment e-mail'
EMAIL_TEMPLATE = """\
<html>
<head>
<style>
table, th, td {{font-size:9pt; border:1px solid black; border-collapse:collapse; text-align:left; background-color:LightGray;}}
th, td {{padding: 5px;}}
</style>
</head>
<body>
Dear Team,<br><br>
Please Find the Project-wise Report with their respectove Owners ID and e-mail address.!<br><br>
{} <br><br>
Kind regards.<br>
STR TEAM.
</body>
</html>"""DataFrame:
df = pd.DataFrame("/tmp/fix.txt")函数到sen邮件:
def send_email():
server = smtplib.SMTP(SMTP_SERVER)
msg = EmailMessage()
msg['Subject'], msg['From'], msg['To'] = SUBJECT, FROM, TO
msg.set_content("Text version of your html template")
msg.add_alternative(
EMAIL_TEMPLATE.format(df.to_html(index=False)),
subtype='html'
)
server.send_message(msg)
if __name__ == '__main__':
send_email()审判:
我试过用下面的东西但没用..。
msg.add_alternative(EMAIL_TEMPLATE.format(df.to_csv(index=False)),subtype='csv')
发布于 2022-09-27 18:26:58
您需要使用,以便可以将数据作为.csv附加。
试试这个:
import smtplib
import pandas as pd
from tabulate import tabulate
from email.message import EmailMessage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
import io
# mail vars
SMTP_SERVER = 'smtp_server@example.com'
FROM = 'some_address@example.com'
TO = ['address@example.com']
SUBJECT = 'test attachment e-mail'
EMAIL_TEMPLATE = """\
<html>
<head>
<style>
table, th, td {{font-size:9pt; border:1px solid black; border-collapse:collapse; text-align:left; background-color:LightGray;}}
th, td {{padding: 5px;}}
</style>
</head>
<body>
Dear Team,<br><br>
Please Find the Project-wise Report with their respectove Owners ID and e-mail address.!<br><br>
{} <br><br>
Kind regards.<br>
STR TEAM.
</body>
</html>"""
def df_to_csv(df):
with io.StringIO() as buffer:
df.to_csv(buffer)
return buffer.getvalue()
def send_email():
multipart = MIMEMultipart()
multipart['Subject'], multipart['From'], multipart['To'] = SUBJECT, FROM, TO
attachment = MIMEApplication(df_to_csv(df))
attachment['Content-Disposition'] = 'attachment; filename="dataframe.csv"'
multipart.attach(attachment)
multipart.attach(MIMEText(EMAIL_TEMPLATE, 'html'))
server = smtplib.SMTP(SMTP_SERVER)
server.sendmail(FROM, TO, multipart.as_string())
server.quit()
if __name__ == '__main__':
send_email()https://stackoverflow.com/questions/73870825
复制相似问题