在django函数中,我填写了一个docx文档模板
import random
first_arr = [3, 5, 8, 10, 14, 15, 16, 18]
second_arr = [5, 10, 15]
third_arr = [x for x in first_arr if x not in second_arr]
arr_to_add = random.sample(third_arr, 5-len(second_arr))
result = np.array(list(second_arr) + list(arr_to_add))
如何获取文件 static.docx 并将其发送到电子邮件?
我通过 doc = DocxTemplate('template.docx')
dates = date
prices = price
tbl_contents = [{'expirationdate': expirationdate, 'price': price}
for expirationdate, price in zip(dates, prices)]
context = {
'tbl_contents': tbl_contents,
'finalprice': sum(prices),
'startdate': startdate,
'enddate': enddate
}
doc.render(context)
doc.save("static.docx")
发送了普通电子邮件,但如何发送带有附件的电子邮件?
答案 0 :(得分:1)
from io import BytesIO
from django.core.mail import EmailMessage
doc = DocxTemplate('template.docx')
dates = date
prices = price
tbl_contents = [{'expirationdate': expirationdate, 'price': price}
for expirationdate, price in zip(dates, prices)]
context = {
'tbl_contents': tbl_contents,
'finalprice': sum(prices),
'startdate': startdate,
'enddate': enddate
}
doc.render(context)
file_io = BytesIO()
doc.save(file_io)
email = EmailMessage(subject="subject", body="mail Body", from_email="from@example.com", to=["to1@example.com", "to2@example.com"])
email.attach("static.docx", file_io.getvalue(), 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
email.send()