如何像读取内存一样读取本地存储中的文件并将其附加到电子邮件中?

时间:2018-12-14 06:05:34

标签: python django file-handling django-email

此代码段将生成一个xlsx文件,然后将该文件附加到电子邮件中 注意:我没有保存任何文件,它在内存中。

import io
a = io.BytesIO()
from django.core.mail import EmailMessage
import xlsxwriter
workbook = xlsxwriter.Workbook(a, {'in_memory': True})
worksheet_s = workbook.add_worksheet('abcd')
worksheet_s.write(0, 0, 'Hello, world!')
workbook.close()
a.seek(0)
email = EmailMessage('Subject', 'Body', 'sentby@mailinator.com', ['sentto@mailinator.com'])
email.attach('file.xlsx', a.getvalue())
email.send()

与此类似,我想将存储中的文件附加到电子邮件,但首先要在内存中打开它。  正如我在尝试编写通用代码以从一个地方发送电子邮件,无论它是否具有附件(自行生成的文件或存储中的文件)。

类似这样的东西

from django.core.mail import EmailMessage
file = open('file.jpeg')
email = EmailMessage('Subject', 'Body', 'sendedby@mailinator.com', ['sentto@mailinator.com'])
email.attach(file.name, file.getvalue())
email.send()

谢谢。

2 个答案:

答案 0 :(得分:0)

我看到您不想保存文件-只保存在内存中。然后,您可以使用此示例。另外,您需要安装 openpyxl

from openpyxl.writer.excel import save_virtual_workbook
from openpyxl import Workbook
from django.core.mail import EmailMessage
email = EmailMessage('Subject', 'Body', 'sentby@mailinator.com', ['sentto@mailinator.com'])
wb = Workbook()
ws = wb.active
ws['A1'] = 42
file = save_virtual_workbook(wb)
email.attach('file_name.xlsx', file)
email.send()

答案 1 :(得分:0)

您可以编写类似的功能来发送带有附件的电子邮件,无论是磁盘上的文件还是具有内存内容的BytesIO对象:

from django.core.mail import EmailMessage
import io

def send_email_with_attachment(file_name, file_content):
    email = EmailMessage('Subject', 'Body', 'sendedby@mailinator.com', 
        ['sentto@mailinator.com'])
    file_content.seek(0)
    email.attach(file_name, file_content.read())
    email.send()

# use it with a "regular" on-disk file
file = open('file.jpeg', 'rb')
send_email_with_attachment('file.jpeg', file)

# use it with a BytesIO object
a = io.BytesIO()
# do something to populate the BytesIO with content, i.e. create an Excel file in memory
send_email_with_attachment('file.xlsx', a)

还要考虑Django EmailMessage类提供了一种直接从文件系统附加文件的方法:

email.attach_file(filepath)

您可以参考documentation以获得更多信息。