我一直在尝试使用 openpyxl 将 excel 作为电子邮件附件发送,而不在 Django 中保存 [On The Fly]
您可以将工作簿对象保存到 BytesIO 实例(from io import BytesIO)
output = BytesIO()
workbook.save(output)
然后,您可以使用 Django EmailMessage 类创建电子邮件并将 BytesIO 对象作为文件附加为第二个参数。
email = EmailMessage(
'Hello',
'Body goes here',
'[email protected]',
['[email protected]', '[email protected]'],
['[email protected]'],
reply_to=['[email protected]'],
headers={'Message-ID': 'foo'},
)
email.attach('file.xlsx', output.getvalue() , 'application/vnd.ms-excel')
这是通过电子邮件发送 Excel 文件的示例。
from io import BytesIO
import xlwt
from django.core.mail import EmailMessage
def send_excel_email():
excelfile = BytesIO()
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('Sheetname')
ws.write(0, 0, 'Firstname')
ws.write(0, 1, 'Surname')
ws.write(1, 0, 'Hans')
ws.write(1, 1, 'Muster')
wb.save(excelfile)
email = EmailMessage()
email.subject = 'This subject'
email.body = 'This context'
email.from_email = '[email protected]'
email.to = ['[email protected]']
email.attach('test_file.xls', excelfile.getvalue(), 'application/ms-excel')
email.send()
这是我使用 Django 2 、Python 3 和 openxl 的方法
from io import BytesIO
output = BytesIO() # Create a file like object in memory
wb_object.save(output) # Write my workbook object into that memory
# Setup my email
msg = EmailMultiAlternatives(subject, "", from_email, to_email, cc=cc, bcc=bcc)
# Attach the excel file with a name, the actual attachment , and a MIMEtype.
msg.attach('my_invoice.xlsx', output.getvalue(), 'application/vnd.ms-excel')
#The content here is the email content in its body and its type which is just text.
msg.attach_alternative(content, "text/html")
# Now send it .
msg.send()