(Python) Use IMAP lib to download attachments and email details

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
4
down vote

favorite
3












This is my first approach to programming in Python, so I hope you will "destroy" my coding!



Idea is to use SSL connection to my mailbox and use IMAP to download attachments from emails with particular subject (all have same one for time being). Beside downloading files I want to display given subject and corresponding UID. Next step will be to save that data (specially subject and corresponding UIDS) in XML file and retrieve to download needed files without extra searches and fetching.



import imaplib
import email.header
import os
import sys

# Your IMAP Settings
host = 'imap.host.com'
user = 'email@adrs.com'
password = 'passwd'

# Connect to the server
print('Connecting to ' + host)
mailBox = imaplib.IMAP4_SSL(host)

# Login to our account
mailBox.login(user, password)

boxList = mailBox.list()
# print(boxList)

mailBox.select()
searchQuery = '(SUBJECT "Desired Subject")'

result, data = mailBox.uid('search', None, searchQuery)
ids = data[0]
# list of uids
id_list = ids.split()

i = len(id_list)
for x in range(i):
latest_email_uid = id_list[x]

# fetch the email body (RFC822) for the given ID
result, email_data = mailBox.uid('fetch', latest_email_uid, '(RFC822)')
# I think I am fetching a bit too much here...

raw_email = email_data[0][1]

# converts byte literal to string removing b''
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)

# downloading attachments
for part in email_message.walk():
# this part comes from the snipped I don't understand yet...
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
fileName = part.get_filename()

if bool(fileName):
filePath = os.path.join('C:/DownloadPath/', fileName)
if not os.path.isfile(filePath) :
fp = open(filePath, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()

subject = str(email_message).split("Subject: ", 1)[1].split("nTo:", 1)[0]
print('Downloaded "file" from email titled "subject" with UID uid.'.format(file=fileName, subject=subject, uid=latest_email_uid.decode('utf-8')))

mailBox.close()
mailBox.logout()


Thanks in advance!







share|improve this question

























    up vote
    4
    down vote

    favorite
    3












    This is my first approach to programming in Python, so I hope you will "destroy" my coding!



    Idea is to use SSL connection to my mailbox and use IMAP to download attachments from emails with particular subject (all have same one for time being). Beside downloading files I want to display given subject and corresponding UID. Next step will be to save that data (specially subject and corresponding UIDS) in XML file and retrieve to download needed files without extra searches and fetching.



    import imaplib
    import email.header
    import os
    import sys

    # Your IMAP Settings
    host = 'imap.host.com'
    user = 'email@adrs.com'
    password = 'passwd'

    # Connect to the server
    print('Connecting to ' + host)
    mailBox = imaplib.IMAP4_SSL(host)

    # Login to our account
    mailBox.login(user, password)

    boxList = mailBox.list()
    # print(boxList)

    mailBox.select()
    searchQuery = '(SUBJECT "Desired Subject")'

    result, data = mailBox.uid('search', None, searchQuery)
    ids = data[0]
    # list of uids
    id_list = ids.split()

    i = len(id_list)
    for x in range(i):
    latest_email_uid = id_list[x]

    # fetch the email body (RFC822) for the given ID
    result, email_data = mailBox.uid('fetch', latest_email_uid, '(RFC822)')
    # I think I am fetching a bit too much here...

    raw_email = email_data[0][1]

    # converts byte literal to string removing b''
    raw_email_string = raw_email.decode('utf-8')
    email_message = email.message_from_string(raw_email_string)

    # downloading attachments
    for part in email_message.walk():
    # this part comes from the snipped I don't understand yet...
    if part.get_content_maintype() == 'multipart':
    continue
    if part.get('Content-Disposition') is None:
    continue
    fileName = part.get_filename()

    if bool(fileName):
    filePath = os.path.join('C:/DownloadPath/', fileName)
    if not os.path.isfile(filePath) :
    fp = open(filePath, 'wb')
    fp.write(part.get_payload(decode=True))
    fp.close()

    subject = str(email_message).split("Subject: ", 1)[1].split("nTo:", 1)[0]
    print('Downloaded "file" from email titled "subject" with UID uid.'.format(file=fileName, subject=subject, uid=latest_email_uid.decode('utf-8')))

    mailBox.close()
    mailBox.logout()


    Thanks in advance!







    share|improve this question





















      up vote
      4
      down vote

      favorite
      3









      up vote
      4
      down vote

      favorite
      3






      3





      This is my first approach to programming in Python, so I hope you will "destroy" my coding!



      Idea is to use SSL connection to my mailbox and use IMAP to download attachments from emails with particular subject (all have same one for time being). Beside downloading files I want to display given subject and corresponding UID. Next step will be to save that data (specially subject and corresponding UIDS) in XML file and retrieve to download needed files without extra searches and fetching.



      import imaplib
      import email.header
      import os
      import sys

      # Your IMAP Settings
      host = 'imap.host.com'
      user = 'email@adrs.com'
      password = 'passwd'

      # Connect to the server
      print('Connecting to ' + host)
      mailBox = imaplib.IMAP4_SSL(host)

      # Login to our account
      mailBox.login(user, password)

      boxList = mailBox.list()
      # print(boxList)

      mailBox.select()
      searchQuery = '(SUBJECT "Desired Subject")'

      result, data = mailBox.uid('search', None, searchQuery)
      ids = data[0]
      # list of uids
      id_list = ids.split()

      i = len(id_list)
      for x in range(i):
      latest_email_uid = id_list[x]

      # fetch the email body (RFC822) for the given ID
      result, email_data = mailBox.uid('fetch', latest_email_uid, '(RFC822)')
      # I think I am fetching a bit too much here...

      raw_email = email_data[0][1]

      # converts byte literal to string removing b''
      raw_email_string = raw_email.decode('utf-8')
      email_message = email.message_from_string(raw_email_string)

      # downloading attachments
      for part in email_message.walk():
      # this part comes from the snipped I don't understand yet...
      if part.get_content_maintype() == 'multipart':
      continue
      if part.get('Content-Disposition') is None:
      continue
      fileName = part.get_filename()

      if bool(fileName):
      filePath = os.path.join('C:/DownloadPath/', fileName)
      if not os.path.isfile(filePath) :
      fp = open(filePath, 'wb')
      fp.write(part.get_payload(decode=True))
      fp.close()

      subject = str(email_message).split("Subject: ", 1)[1].split("nTo:", 1)[0]
      print('Downloaded "file" from email titled "subject" with UID uid.'.format(file=fileName, subject=subject, uid=latest_email_uid.decode('utf-8')))

      mailBox.close()
      mailBox.logout()


      Thanks in advance!







      share|improve this question











      This is my first approach to programming in Python, so I hope you will "destroy" my coding!



      Idea is to use SSL connection to my mailbox and use IMAP to download attachments from emails with particular subject (all have same one for time being). Beside downloading files I want to display given subject and corresponding UID. Next step will be to save that data (specially subject and corresponding UIDS) in XML file and retrieve to download needed files without extra searches and fetching.



      import imaplib
      import email.header
      import os
      import sys

      # Your IMAP Settings
      host = 'imap.host.com'
      user = 'email@adrs.com'
      password = 'passwd'

      # Connect to the server
      print('Connecting to ' + host)
      mailBox = imaplib.IMAP4_SSL(host)

      # Login to our account
      mailBox.login(user, password)

      boxList = mailBox.list()
      # print(boxList)

      mailBox.select()
      searchQuery = '(SUBJECT "Desired Subject")'

      result, data = mailBox.uid('search', None, searchQuery)
      ids = data[0]
      # list of uids
      id_list = ids.split()

      i = len(id_list)
      for x in range(i):
      latest_email_uid = id_list[x]

      # fetch the email body (RFC822) for the given ID
      result, email_data = mailBox.uid('fetch', latest_email_uid, '(RFC822)')
      # I think I am fetching a bit too much here...

      raw_email = email_data[0][1]

      # converts byte literal to string removing b''
      raw_email_string = raw_email.decode('utf-8')
      email_message = email.message_from_string(raw_email_string)

      # downloading attachments
      for part in email_message.walk():
      # this part comes from the snipped I don't understand yet...
      if part.get_content_maintype() == 'multipart':
      continue
      if part.get('Content-Disposition') is None:
      continue
      fileName = part.get_filename()

      if bool(fileName):
      filePath = os.path.join('C:/DownloadPath/', fileName)
      if not os.path.isfile(filePath) :
      fp = open(filePath, 'wb')
      fp.write(part.get_payload(decode=True))
      fp.close()

      subject = str(email_message).split("Subject: ", 1)[1].split("nTo:", 1)[0]
      print('Downloaded "file" from email titled "subject" with UID uid.'.format(file=fileName, subject=subject, uid=latest_email_uid.decode('utf-8')))

      mailBox.close()
      mailBox.logout()


      Thanks in advance!









      share|improve this question










      share|improve this question




      share|improve this question









      asked Mar 20 at 14:10









      Tomasz Tarnowski

      14815




      14815

























          active

          oldest

          votes











          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f190035%2fpython-use-imap-lib-to-download-attachments-and-email-details%23new-answer', 'question_page');

          );

          Post as a guest



































          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes










           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f190035%2fpython-use-imap-lib-to-download-attachments-and-email-details%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Greedy Best First Search implementation in Rust

          Function to Return a JSON Like Objects Using VBA Collections and Arrays

          C++11 CLH Lock Implementation