gpt4 book ai didi

python - 如何将现有 CSV 文件附加到电子邮件?

转载 作者:行者123 更新时间:2023-11-30 22:10:41 28 4
gpt4 key购买 nike

我正在尝试按照 Attach generated CSV file to email and send with Django 中的示例进行操作生成 CSV 文件并通过电子邮件发送。然而,就我而言,我还想保存实际文件,而不仅仅是像示例中那样发送我的电子邮件。 (另外,我使用的是 Python 3,而该示例似乎适用于 Python 2)。

这是我尝试运行的 Django 脚本:

import csv
from collections import OrderedDict
from datetime import datetime
from django.conf import settings
from django.core.mail import EmailMessage
from lucy_web.models import Family

# Path of the CSV file to generate and send by email (relative to lucy-web)
FILENAME = 'scripts/nps.csv'


def get_row(family):
"""
Return a row for the spreadsheet, including the corresponding headers.
(The actual argument to csv.write.writerow() should be the .values(); the
.keys() are for the header row). (An OrderedDict is easier to
read/add to than two separate lists).
"""
return OrderedDict([
("Employee Name", family.employee_name),
("Employee Email", family.employee_email),
("Employee Alternate Email", family.employee_alternate_email),
("Partner Name", family.partner_name),
("Partner Email", family.partner_email),
("Partner Alternate Email", family.partner_alternate_email),
])


def run():
write_csv_file()
send_results_by_email(to=['kurt@hicleo.com'])


def write_csv_file(filename=FILENAME):
"""Generate a CSV file with NPS data"""
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)

# Header row; we need to specify an arbitrary family
writer.writerow(
get_row(Family.objects.first()).keys())

for family in Family.objects.all():
row = get_row(family).values()
writer.writerow(row)
print(f"Wrote a CSV file at {filename}")


def send_results_by_email(to, filename=FILENAME):
"""Send an email with the NPS data attached"""
with open(filename, 'r') as csvfile:
now = datetime.now().strftime("%m-%d-%Y %H:%M")
email_message = EmailMessage(
subject=f"NPS data (collected {now})",
body=f"Script run with the following settings module: '{settings.SETTINGS_MODULE}'",
to=to,
attachments=[('nps.csv', csvfile.getvalue(), 'text/csv')])
email_message.send()
print(f"Email sent to {to}!")

但是,当我运行 python manage.py runscript nps 时,我收到以下错误消息(其中 scripts/nps.py 是脚本的位置) :

Wrote a CSV file at scripts/nps.csv
Exception while running run() in 'scripts.nps'
Traceback (most recent call last):
File "manage.py", line 28, in <module>
execute_from_command_line(sys.argv)
File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django_extensions/management/email_notifications.py", line 65, in run_from_argv
super(EmailNotificationCommand, self).run_from_argv(argv)
File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django_extensions/management/email_notifications.py", line 77, in execute
super(EmailNotificationCommand, self).execute(*args, **options)
File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/core/management/base.py", line 335, in execute
output = self.handle(*args, **options)
File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django_extensions/management/utils.py", line 59, in inner
ret = func(self, *args, **kwargs)
File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django_extensions/management/commands/runscript.py", line 238, in handle
run_script(mod, *script_args)
File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django_extensions/management/commands/runscript.py", line 148, in run_script
mod.run(*script_args)
File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/scripts/nps.py", line 58, in run
send_results_by_email(to=['kurt@hicleo.com'])
File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/scripts/nps.py", line 84, in send_results_by_email
attachments=[('nps.csv', csvfile.getvalue(), 'text/csv')])
AttributeError: '_io.TextIOWrapper' object has no attribute 'getvalue'

据我从https://docs.python.org/3/library/io.html#text-i-o了解,我基本上需要做什么,是根据 scripts/nps.csv 的输出文件构建内存中 io.StringIO。我该怎么办?

更新

根据答案,我已将 csvfile.getvalue() 替换为 csvfile.read()。经过一些重构,这就是我的 send_results_by_email() 函数:

def send_results_by_email(to, filename=FILENAME):
"""Send an email with the NPS data attached"""
now = datetime.now().strftime("%m-%d-%Y %H:%M")
email_message = EmailMessage(
subject=f"NPS data (collected {now})",
body=f"Script run with the following settings module: '{settings.SETTINGS_MODULE}'",
to=to)

with open(filename, newline='') as csvfile:
email_message.attach('nps.csv', csvfile.read(), 'text/csv')
email_message.send()
print(f"Email sent to {to}!")

问题是它没有发送电子邮件。但是,如果我将 csvfile.read() 替换为字符串 'foobar',我会收到一封电子邮件:

enter image description here

预期内容:

enter image description here

为什么它适用于简单的字符串'foobar',而不适用于csvfile.read()?我已经在调试器中打印了内容,它似乎确实有内容,我已将其上传到 https://file.io/kZkNPq (这是扰乱的数据)。

更新2

电子邮件的发送实际上是有效的,唯一的区别是 GMail 将带有较大附件的电子邮件识别为网络钓鱼并将它们发送到我的垃圾邮件文件夹:

enter image description here

最佳答案

getvalue 方法仅在 io.StringIO 上可用。对于 io.TextIOWrapper 实例,请使用 read 方法。

csvfile.getvalue() 更改为 csvfile.read() 它应该可以工作。

关于python - 如何将现有 CSV 文件附加到电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51644454/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com