I am trying to use python's imaplib to create an email and send it to a mailbox with specific name, e.g. INBOX. Anyone has some great suggestion :).
Asked
Active
Viewed 2.2k times
4 Answers
11
The IMAP protocol is not designed to send emails. It is designed to manipulate mailboxes.
To create an email and send it you can use SMTP, as in smtplib.
To move an email that is already in a mailbox from one folder to another, you can copy the mail to the needed folder and delete it from the old one using uid
, as in the answer here.

Community
- 1
- 1

Muhammad Alkarouri
- 23,884
- 19
- 66
- 101
-
thk:), but can i create email in specific mailbox using imaplib? – vernomcrp Sep 22 '10 at 16:17
-
@vernomcrp: No, because as I explained imaplib cannot be used to create emails. You can send the email first then move it as above. – Muhammad Alkarouri Sep 22 '10 at 16:31
10
You can use Python's built-in imaplib
module and the append()
command to append a mail message to an IMAP folder:
import imaplib
from email.message import Message
from time import time
connection = imaplib.IMAP4_SSL(HOSTNAME)
connection.login(USERNAME, PASSWORD)
new_message = Message()
new_message["From"] = "hello@itsme.com"
new_message["Subject"] = "My new mail."
new_message.set_payload("This is my message.")
connection.append('INBOX', '', imaplib.Time2Internaldate(time()), str(new_message).encode('utf-8'))

Chris McCormick
- 4,356
- 1
- 21
- 19
-
I have tried your method but I am getting this error: TypeError: cannot use a bytes pattern on a string-like object – Ghost Jan 02 '19 at 23:31
-
-
0
Since I cannot yet comment on user3556956's comment, here is the answer for python3 :
connection.append('INBOX', '', imaplib.Time2Internaldate(time.time()), str(new_message).encode('utf-8'))
In short you have to pass the message as a byte instead of a python string.

marrco
- 128
- 7
-6
No idea how they do it but doesn't Microsoft Outlook let you move an email from a local folder to a remote IMAP folder?

Ben Scherrey
- 329
- 1
- 4
- 6