首页 文章

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

提问于
浏览
1

我正在尝试按照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 . 我怎么能这样做?

Update

在答案之后,我已将 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() ?我've printed the contents in the debugger and it does seem to have content, which I'已上传到https://file.io/kZkNPq(这是乱码数据) .

Update 2

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

enter image description here

2 回答

  • 1

    getvalue 方法仅适用于 io.StringIO . 对于 io.TextIOWrapper 实例,请使用 read 方法 .

    csvfile.getvalue() 更改为 csvfile.read() ,它应该有效 .

  • 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}!")
    

相关问题