Home > Mobile >  Unable to save emails in DRAFT folder using Python GMAIL IMAP
Unable to save emails in DRAFT folder using Python GMAIL IMAP

Time:04-19

I am trying to save multiple emails in my drafts folder so I could review and press the SEND button in my web browser but I seem to be running into multiple issues.

I spent about half a day checking google and stackoverflow but didnt get much luck:

Here are a few examples that seemed relevant but didnt work

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

Below is my code, which executes and completes with a 0 code but nothing is saved to my drafts folder. Can anyone please help ?

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

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

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

Output of the program:

/Library/Frameworks/Python.framework/Versions/3.10/bin/python3 /Users/prashanth/PycharmProjects/pythonTools/DraftMailDemo.py
b'From: [email protected]\nTo: Jimmy <[email protected]>\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

I even tried this following code and it executes with a 0 exit code but still doesnt save anything to the Drafts folder.

import imaplib
import time
import email


def createdraft():
    conn = imaplib.IMAP4_SSL('imap.gmail.com', port=993)
    conn.login('[email protected]', '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()

My Environment:
Python : 3.10
OS : Mac OS Big Sur 11.6.5

CodePudding user response:

All mail servers known to me added letters to INBOX.

It probably depends on the server settings.

You can try moving them after adding.

CodePudding user response:

Ok, I finally figured this out after multiple tries and tweaking the other examples. I was able to create a MultiMime message that I can save to the Drafts folder and it works, hurray !!

It doesnt seem very efficient though (execution takes around 3-5 secs - I could use some suggestions on making it more efficient.

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  style="color:rgb(0,0,255)"><font size="2">Hello {lead_name.split(" ")[0]},</font></div>
        <div  style="color:rgb(0,0,255)"><font size="2"><br></font></div>
        <div  style="color:rgb(0,0,255)"><font size="2">My name is John and I would like to connect with you.
        <div  style="color:rgb(0,0,255)"><font size="2">Look forward to hearing from you.<br></font></div>
        <div  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:[email protected]" 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('[email protected]', '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', '[email protected]')

Environment :
Python : 3.10
OS : Mac OS Big Sur 11.6.5

  • Related