Sample code for 30+ languages & platforms
Chilkat2-Python

Fetch an IMAP Message as MIME Text

See more IMAP Examples

Demonstrates the Chilkat Imap.FetchSingleAsMime method, which downloads one message and returns its MIME source as a string. If the second argument (bUid) is true, the first argument is a UID; otherwise it is a sequence number. This example fetches message 1's raw MIME.

Background: Sometimes you want the message exactly as it exists on the server — the raw MIME — rather than a parsed Email object. That is what you save to a .eml file, feed to another parser, or archive verbatim. This method returns the MIME as text; for messages that may contain binary data, the BinData variant FetchSingleBd preserves the exact bytes.

Chilkat Chilkat2-Python Downloads

Chilkat2-Python
import sys
import chilkat2

success = False

# Demonstrates the Imap.FetchSingleAsMime method, which downloads one message and returns
# its MIME source as a string.  If the 2nd argument (bUid) is True, the 1st argument is a
# UID; otherwise it is a sequence number.

imap = chilkat2.Imap()

imap.Ssl = True
imap.Port = 993

success = imap.Connect("imap.example.com")
if (success == False):
    print(imap.LastErrorText)
    sys.exit()

success = imap.Login("user@example.com","myPassword")
if (success == False):
    print(imap.LastErrorText)
    sys.exit()

success = imap.SelectMailbox("Inbox")
if (success == False):
    print(imap.LastErrorText)
    sys.exit()

# Download message sequence number 1 and return its raw MIME.  bUid = False.
mime = imap.FetchSingleAsMime(1,False)
if (imap.LastMethodSuccess == False):
    print(imap.LastErrorText)
    sys.exit()

print(mime)

success = imap.Disconnect()
if (success == False):
    print(imap.LastErrorText)
    sys.exit()