0

I have a program that will pull file attachments into a network share. I have this working in both single part and multi-part email messages.

I have recently received a mutlipart that is showing as :

Content-Type: application/pdf Content-Disposition: attachment; filename="=?utf-8?B?SW52b2ljZShzKS5wZGY=?=" Content-Transfer-Encoding: base64

This is failing at the file write due to the filename.

Here is the code where I'm writing the PDF:

fp = open(os.path.join(path, filename), 'wb') fp.write(part.get_payload(decode=True)) fp.close()

However I think that part is working properly and it's failing on the file write... I'm not sure how to translate that filename into readable text. Here is the code I'm using to determine the filename:

filename = part.get_filename() filename_zero, fileext =os.path.splitext(filename)
filename = str(var_seq) + "_" + filename_zero + fileext

Any insight into what I'm missing is greatly appreciated.

martineau
  • 99,260
  • 22
  • 139
  • 249
AlliDeacon
  • 955
  • 2
  • 13
  • 30
  • 1
    Insight: consider [`email.header.decode_header()`](https://docs.python.org/2/library/email.header.html#email.header.decode_header). Alternative: consider http://stackoverflow.com/questions/7406102/create-sane-safe-filename-from-any-unsafe-string – Robᵩ Jan 25 '17 at 17:47
  • `email.header.decode_header()` was exactly what I needed. Thanks so much @Robᵩ – AlliDeacon Jan 25 '17 at 18:12

1 Answers1

1

email.header.decode_header() was exactly what I needed. Thanks so much!

Added the following lines:

filename = part.get_filename() if decode_header(filename)[0][1] is not None: filename = str(decode_header(filename)[0][0]).decode(decode_header(filename)[0][1]) filename_zero, fileext = os.path.splitext(filename) filename = str(var_seq) + "_" + filename_zero + fileext

AlliDeacon
  • 955
  • 2
  • 13
  • 30