首页 > 解决方案 > 如何使用 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,
)

我如何使用它来将已发送的电子邮件放入邮箱已发送文件夹中?

标签: djangoemail

解决方案


我用下面的方法取得了成功,但我使用的是 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?


推荐阅读