简体   繁体   English

如何使用 IMAP 使用 Z7F5F35426B927411FC9231B56382173Z 在 Gmail 中创建草稿

[英]How do I create a draft in Gmail using IMAP using Python

Here is my code:这是我的代码:

import imaplib
import email

con = imaplib.IMAP4_SSL('imap.gmail.com')
con.login("email@eample.com", "password")
con.select("'[Gmail]/Drafts'")
con.append("'[Gmail]/Drafts'", None, None, email.message_from_string("Test"))

Then I receive the error -然后我收到错误 -

Exception has occurred: TypeError expected string or bytes-like object发生异常:TypeError 预期字符串或类似字节的 object

I've tried to use a regular string as well but the same error appeared.我也尝试使用常规字符串,但出现了相同的错误。

Using Python 3.8使用 Python 3.8

This is a useful script to save drafts using IMAP这是使用 IMAP 保存草稿的有用脚本

#!/usr/bin/env python3
import imaplib
import ssl
import email.message
import email.charset
import time

tls_context = ssl.create_default_context()
server = imaplib.IMAP4('imap.gmail.com')
server.starttls(ssl_context=tls_context)
server.login('email@example.com', 'password')

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

# Create message
new_message = email.message.Message()
new_message["From"] = "Your name <sender@mydomain.com>"
new_message["To"] = "Name of Recipient <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")
server.append('INBOX.Drafts', '', imaplib.Time2Internaldate(time.time()), encoded_message)
    
# Cleanup
server.close()

The code below worked for me.下面的代码对我有用。

You might need to create an app password .您可能需要创建应用密码

Enjoy;享受; ;) ;)

from email.message import Message
import imaplib
import time

with imaplib.IMAP4_SSL(host="imap.gmail.com", port=imaplib.IMAP4_SSL_PORT) as imap_ssl:
    print("Logging into mailbox...")
    resp_code, response = imap_ssl.login('you@domain.com', 'your_api_key')

    # Create message
    message = Message()
    message["From"] = "You <you@yourdomain.com>"
    message["To"] = "recipient <recipient@somedomain.com"
    message["Subject"] = "Your subject"
    message.set_payload("Some Body Message")
    utf8_message = str(message).encode("utf-8")
    
    # Send message
    imap_ssl.append("[Gmail]/Drafts", '', imaplib.Time2Internaldate(time.time()), utf8_message)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM