如何发送excel作为电子邮件附件使用openpyxl不保存[在飞行]



我一直在尝试使用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',
    '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')

请复习下次如何请求:)

这是一个通过电子邮件发送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()

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

最新更新