pythonでメールの添付ファイルを保存したい

pythonでメールの添付ファイルをmacに保存したくて
ググってソースを動かしてみました。

しかし、下記のエラーが出てしまいました。
解決するにはどうしたら良いでしょうか?
教えて下さい。

UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-7: ordinal not in range(128)

UnicodeEncodeError Traceback (most recent call last) <ipython-input-2-48e1f5c98f61> in <module> 30 filename = part.get_filename() 31 if not filename: ---> 32 body = base64.urlsafe_b64decode(part.get_payload().encode('ASCII')).decode('utf-8') 33 print(f"本文:{body}") 34 else: UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-7: ordinal not in range(128)

python

import imaplib import email import base64 from email.header import decode_header, make_header ADDRESS = "xxxx@xxxx.bz"PASSWORD = "xxxxxxxx"imapobj = imaplib.IMAP4_SSL("xxxxxx.xserver.jp", '993')imapobj.login(ADDRESS, PASSWORD) #workラベル下のメールを取得imapobj.select()typ, data = imapobj.search(None, 'ALL') #取得したメールから表題と本文を出力し、添付ファイルを同階層に書き出すfor num in data[0].split(): typ, data = imapobj.fetch(num, '(RFC822)') #メール内容(タイトル、本文、添付ファイルなど) mail = email.message_from_string(data[0][1].decode('utf-8')) #表題出力 subject = str(make_header(decode_header(mail["Subject"]))) #print(f"タイトル:{subject}") #本文出力と添付ファイル書き出し for part in mail.walk(): if part.get_content_maintype() == 'multipart': continue filename = part.get_filename() if not filename: body = base64.urlsafe_b64decode(part.get_payload().encode('ASCII')).decode('utf-8') print(f"本文:{body}") else: with open('./' + filename, 'wb') as f: f.write(part.get_payload(decode=True)) print(f"{filename}を保存しました。") imapobj.close()

コメントを投稿

0 コメント