如何使用openpyxl发送excel作为电子邮件附件而不保存[On The Fly]

时间:2016-11-17 08:49:19

标签: python linux django email-attachments openpyxl

我一直在尝试使用openpyxl将excel作为电子邮件附件发送,而不在Django中保存[On The Fly]

3 个答案:

答案 0 :(得分:4)

您可以将工作簿对象保存到BytesIO实例(从io import BytesIO)

output = BytesIO()
workbook.save(output)

然后,您可以使用Django EmailMessage类创建电子邮件,并将BytesIO对象作为文件作为第二个参数附加。

email = EmailMessage(
    'Hello',
    'Body goes here',
    'from@example.com',
    ['to1@example.com', 'to2@example.com'],
    ['bcc@example.com'],
    reply_to=['another@example.com'],
    headers={'Message-ID': 'foo'},
)

email.attach('file.xlsx', output.getvalue() , 'application/vnd.ms-excel')

请查看下次如何询问:)

答案 1 :(得分:1)

这是通过电子邮件发送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 = 'from@example.com'
    email.to = ['your_email@gmail.com']
    email.attach('test_file.xls', excelfile.getvalue(), 'application/ms-excel')
    email.send()

答案 2 :(得分:0)

这是我使用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()