社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Steven • 4 年前 • 1971 次点击  

这是我的代码:

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"))

然后我收到了错误-

发生异常:TypeError 应为类似字符串或字节的对象

我也尝试使用常规字符串,但出现了相同的错误。

使用Python 3.8

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130764
文章 [ 1 ]  |  最新文章 4 年前
David Salomon
Reply   •   1 楼
David Salomon    4 年前

这是一个使用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()