无法使用 Python GMAIL IMAP 将电子邮件保存在 DRAFT 文件夹中

Unable to save emails in DRAFT folder using Python GMAIL IMAP

我试图在我的草稿文件夹中保存多封电子邮件,以便我可以在我的网络浏览器中查看并按下“发送”按钮,但我似乎 运行 陷入多个问题。

我花了大约半天时间检查 google 和 Whosebug,但运气不佳:

这里有一些看似相关但没有用的例子

How do I create a draft in Gmail using IMAP using Python

Programmatically Save Draft in Gmail drafts folder

Creating a Draft message in Gmail using the imaplib in Python

Programmatically Save Draft in Gmail drafts folder

下面是我的代码,它执行并以 0 代码完成,但没有任何内容保存到我的草稿文件夹中。有人可以帮忙吗?

import imaplib
import ssl
import email.message
import email.charset
import time


class DraftMailDemo:
    def send(self):

        tls_context = ssl.create_default_context()
        server = imaplib.IMAP4_SSL('imap.gmail.com')
        #server.starttls(ssl_context=tls_context)
        server.login('some.email@gmail.com', 'pass123')

        # Select mailbox
        server.select("INBOX.Drafts")

        # Create message
        new_message = email.message.Message()
        new_message["From"] = "sender@mydomain.com"
        new_message["To"] = "Jimmy <recipient@mydomain.com>"
        new_message["Subject"] = "Your subject"
        new_message.set_payload("""
        This is your message.
        It can have multiple lines and
        contain special characters: äöü.
        """)

        # Fix special characters by setting the same encoding we'll use later to encode the message
        new_message.set_charset(email.charset.Charset("utf-8"))
        encoded_message = str(new_message).encode("utf-8")
        print(encoded_message)
        server.append('INBOX.Drafts', '', imaplib.Time2Internaldate(time.time()), encoded_message)

        # Cleanup
        #server.close()
        server.logout()


if __name__ == '__main__':
    mail = DraftMailDemo()
    mail.send()

程序输出:

/Library/Frameworks/Python.framework/Versions/3.10/bin/python3 /Users/prashanth/PycharmProjects/pythonTools/DraftMailDemo.py
b'From: sender@mydomain.com\nTo: Jimmy <recipient@mydomain.com>\nSubject: Your subject\nMIME-Version: 1.0\nContent-Type: text/plain; charset="utf-8"\nContent-Transfer-Encoding: base64\n\nCiAgICAgICAgVGhpcyBpcyB5b3VyIG1lc3NhZ2UuCiAgICAgICAgSXQgY2FuIGhhdmUgbXVsdGlw\nbGUgbGluZXMgYW5kCiAgICAgICAgY29udGFpbiBzcGVjaWFsIGNoYXJhY3RlcnM6IMOkw7bDvC4K\nICAgICAgICA=\n'

Process finished with exit code 0

我什至尝试了以下代码,它以 0 退出代码执行,但仍未将任何内容保存到 Drafts 文件夹。

import imaplib
import time
import email


def createdraft():
    conn = imaplib.IMAP4_SSL('imap.gmail.com', port=993)
    conn.login('some.email@gmail.com', 'pass123')
    conn.select('[Gmail]/Drafts')
    conn.append("[Gmail]/Drafts", '', imaplib.Time2Internaldate(time.time()), str(email.message_from_string('TEST')).encode('UTF-8'))



class SecondTryDraft:
    pass


if __name__ == '__main__':
    mail = SecondTryDraft()
    createdraft()

我的环境:
Python : 3.10
OS : Mac OS 大苏尔 11.6.5

我知道的所有邮件服务器都将信件添加到收件箱。

这可能取决于服务器设置。

您可以尝试添加后移动它们。

好的,经过多次尝试和调整其他示例后,我终于明白了这一点。我能够创建一个 MultiMime 消息,我可以将其保存到 Drafts 文件夹并且它有效,hurray !!

虽然看起来效率不高(执行大约需要 3-5 秒 - 我可以使用一些建议来提高效率。

import imaplib
import time
from email.message import EmailMessage
from email.headerregistry import Address


def createdraft(lead_name, lead_email):
    msg = EmailMessage()
    msg['Subject'] = "My Introduction"
    msg['From'] = Address("Jane Doe", "Jane.Doe", "gmail.com")
    msg['To'] = Address(lead_name, lead_email.split("@")[0], lead_email.split("@")[1])
    msg.set_type('text/html')
    html_msg = f"""
        <div class="gmail_default" style="color:rgb(0,0,255)"><font size="2">Hello {lead_name.split(" ")[0]},</font></div>
        <div class="gmail_default" style="color:rgb(0,0,255)"><font size="2"><br></font></div>
        <div class="gmail_default" style="color:rgb(0,0,255)"><font size="2">My name is John and I would like to connect with you.
        <div class="gmail_default" style="color:rgb(0,0,255)"><font size="2">Look forward to hearing from you.<br></font></div>
        <div class="gmail_default" style="color:rgb(0,0,255)"><font size="2"><br clear="all"></font></div>
        <div><font size="2"><b><span style="color:rgb(0,0,255)">Jane</span></b></font></div>
        <div><font size="2"><b><span style="color:rgb(0,0,255)">Mobile : 111-222-3333</span></b></font></div>
        <div><font size="2"><b><span style="color:rgb(0,0,255)">Email : <a href="mailto:Jane.Doe@gmail.com" target="_blank">Jane.Doe@gmail.<wbr>com</a></span></b></font></div>
        """
    msg.add_alternative(html_msg, subtype="html")

    conn = imaplib.IMAP4_SSL('imap.gmail.com', port=993)
    conn.login('jane.doe@gmail.com', 'pass123')
    conn.select('[Gmail]/Drafts')
    conn.append("[Gmail]/Drafts", '', imaplib.Time2Internaldate(time.time()), str(msg).encode('UTF-8'))


class CreateDraftMultiMimeText:
    pass


if __name__ == '__main__':
    mail = CreateDraftMultiMimeText()
    createdraft('John Doe', 'John.Doe@gmail.com')

环境:
Python : 3.10
OS : Mac OS 大苏尔 11.6.5