【问题标题】:How to put emails in sent folder with django send_mail()?如何使用 django send_mail() 将电子邮件放入已发送文件夹?
【发布时间】:2019-08-03 10:38:03
【问题描述】:

我正在使用 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 email


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以使用此配置将邮件发送到文件:doc

    EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
    EMAIL_FILE_PATH = '/tmp/app-messages' # change this to a proper location
    

    【讨论】:

      猜你喜欢
      • 2020-08-09
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      • 2021-05-15
      • 2022-08-07
      • 1970-01-01
      相关资源
      最近更新 更多