How to create draft email on IMAP server using Python

Use this Python script to create a draft email on your IMAP server. The email is not sent automatically but only stored in your draft folder.

#!/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('')
server.login('', 'password')
# Select mailbox"INBOX.Drafts")
# Create message
new_message = email.message.Message()
new_message["From"] = "Your name <>"
new_message["To"] = "Name of Recipient <>"
new_message["Subject"] = "Your subject"
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
encoded_message = str(new_message).encode("utf-8")
server.append('INBOX.Drafts', '', imaplib.Time2Internaldate(time.time()), encoded_message)
# Cleanup

Also see Minimal Python IMAP over TLS example