django - 如何使用 django send_mail() 将电子邮件放入已发送文件夹?
问题描述
我正在使用 django 的简单邮件发送功能。
from django.core.mail import send_mail
send_mail(
'Subject here',
'Here is the message.',
'from@example.com',
['to@example.com'],
fail_silently=False,
)
我如何使用它来将已发送的电子邮件放入邮箱已发送文件夹中?
解决方案
我用下面的方法取得了成功,但我使用的是 Django 的 EmailMultiAlternatives。基本上,'send_mail' - 功能也应该如此。根据您的电子邮件连接,您可能需要更改 IMAP 的一些详细信息。
pythons imaplib 文档: https ://docs.python.org/3.8/library/imaplib.html
有关使用 django 发送电子邮件的更多信息:https ://docs.djangoproject.com/en/2.2/topics/email/
所需模块:
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
import imaplib, time
发送邮件的代码:
#Send email
email = EmailMultiAlternatives(
subject=subject, body=body_text,
from_email=from_email, to=email_to,
reply_to=['****@****.ch'],
headers={})
#Attaches html version of email
email.attach_alternative(message_html, "text/html")
#Attaches image
email.attach(signature())
#Sends email
email.send()
准备我们刚刚发送的电子邮件。之后将用于复制已发送文件夹中的电子邮件。
#Loads the email message to append it afterwards with IMAP
message = str(email.message())
将电子邮件放在已发送文件夹中。
#Creates a copy of the email in the sent folder
imap = imaplib.IMAP4(settings.EMAIL_HOST)
imap.starttls()
imap.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
imap.append('INBOX.Sent', '\\SEEN', imaplib.Time2Internaldate(time.time()), message.encode())
imap.logout()
在我的一个项目中使用 django 2.2.9 和 python 3.8.1 实现。
我自己的解决方案受到这篇文章的启发:Is it possible to save the sent email into the sent items folder using python?
推荐阅读
- angular - 部署 MEAN Stack 应用程序,托管问题
- java - 来自接收器的奇怪错误与 Sqlite 数据库
- angular - Google Maps JavaScript API 错误:ApiNotActivatedMapError 尽管 Google Maps JavaScript API 已启用
- sql - SQL通过触发器更新两个不同的服务器
- selenium - Robot Framework Selenium Go To 关键字被浏览器弹出窗口阻止
- reactjs - page/Activity/ActivityTable ✖ 找不到包“page/Activity/ActivityTable”。你安装了吗?当我使用雪包开发时
- highcharts - highcharts 瀑布栈仅中级系列
- google-sheets - 突出显示 Google 表格中许多单元格中的重复值
- regex - 除了该模式位于行首的行之外,如何匹配第一次出现的模式(或字符)?
- visual-studio - 修改 edmx 图后 Visual Studio IDE 中的奇怪行为