[英]Django EmailMessage add attachement to an email
在我的 python django 項目中,我使用這兩種方法發送 html Z0C83F57C786A0B4A39EFAB23731C7EBC
def send_html_email(to_list, subject, template_name, context, sender=settings.DEFAULT_FROM_EMAIL):
msg_html = render_to_string(template_name, context)
msg = EmailMessage(subject=subject, body=msg_html,
from_email=sender, to=to_list)
msg.content_subtype = "html" # Main content is now text/html
return msg.send()
def emailsend(l_sender, l_lic, t_name='consok'):
if t_name == 'lavoraok':
templ = 'lavora_ok.html'
ttitle = 'test: Nuova candidatura da sito web'
elif t_name == 'lavoraok_cli':
templ = 'lavora_ok_cli.html'
ttitle = 'test: Nuova candidatura da sito web'
else:
templ = 'cons_del.html'
ttitle = 'test: Appuntamento cancellato'
context = {
'news': 'test consulenza',
'lic': l_lic
}
try:
send_html_email(l_sender, ttitle, templ, context,
sender='test@prova.com')
except Exception as e:
print('Email send error: ', e)
一切都很好,但現在在我的新表單中,我有一個字段用於附加文件以通過 email 發送。 如何實現我的 defs 以將文件附加到 email?
非常感謝提前
根據EmailMessage objects 的文檔,您可以添加attachments
參數:
附件:要放在郵件中的附件列表。 這些可以是 MIMEBase 實例,也可以是(文件名、內容、mimetype)三元組。
因此,使用這種方法的一個示例可能是:
attachments = [] # list of attachments
for filename in filenames: # filenames is the list of filenames corresponding to your attachments
content = open(filename, "rb").read()
attachment = (filename, content, "mimetype") # replace mimetype with actual mimetype
attachments.append(attachment)
# Send the email with attachments
email = EmailMessage("Subject", "Body", "from@email.com", ["to@email.com"], attachments=attachments)
email.send()
您還可以在EmailMessage
object 上調用attach()
function,這將創建一個新的文件附件並將其添加到消息中,或者attach_file()
從文件系統中附加一個文件。
后兩個選項在上述文檔中有更詳細的描述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.