我正在尝试按照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可以理解,我本质上需要做的是从io.StringIO
的输出文件构造内存scripts/nps.csv
。我该怎么办?
更新
在回答之后,我将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'
,则会收到一封电子邮件:
具有预期的内容:
为什么它不能与简单字符串'foobar'
一起使用,而不能与csvfile.read()
一起使用?我已经在调试器中打印了内容,并且似乎确实包含了内容,这些内容已经上传到https://file.io/kZkNPq(它是加扰的数据)中。
更新2
发送电子邮件实际上是有效的,唯一的区别是GMail将具有较大附件的电子邮件标识为网络钓鱼,并将其发送到我的垃圾文件夹:
答案 0 :(得分:2)
getvalue
方法仅在io.StringIO
上可用。对于io.TextIOWrapper
实例,请使用read
方法。
将csvfile.getvalue()
更改为csvfile.read()
,它应该可以工作。
答案 1 :(得分:1)
由于 csvfile 是 _io.TextIOWrapper
对象,因此您必须使用 .read()
方法而不是 getvalue()
,
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.read(), 'text/csv')])
email_message.send()
print(f"Email sent to {to}!")