簡體   English   中英

如何像在內存中一樣讀取本地存儲中的文件並將其附加到電子郵件中?

[英]How to read a file in my local storage as in memory and attach it into 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()

提前致謝。

我看到您不想保存文件 - 只保存在內存中。 然后你可以使用這個例子。 你還需要安裝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()

您可以編寫這樣的函數來發送帶有附件的電子郵件,無論是磁盤上的文件還是具有內存內容的 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)

您可以參考文檔了解更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM