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