Steven
Steven

Reputation: 21

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 protected]", "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

I've tried to use a regular string as well but the same error appeared.

Using Python 3.8

Upvotes: 2

Views: 2057

Answers (2)

madjaoue
madjaoue

Reputation: 5224

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('[email protected]', 'your_api_key')

    # Create message
    message = Message()
    message["From"] = "You <[email protected]>"
    message["To"] = "recipient <[email protected]"
    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)

Upvotes: 2

David Salomon
David Salomon

Reputation: 849

This is a useful script to save drafts using 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 protected]', 'password')

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

# Create message
new_message = email.message.Message()
new_message["From"] = "Your name <[email protected]>"
new_message["To"] = "Name of Recipient <[email protected]>"
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()

Upvotes: 0

Related Questions