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
1import imaplib 2import email 3import base64 4from email.header import decode_header, make_header 5 6ADDRESS = "xxxx@xxxx.bz" 7PASSWORD = "xxxxxxxx" 8imapobj = imaplib.IMAP4_SSL("xxxxxx.xserver.jp", '993') 9imapobj.login(ADDRESS, PASSWORD) 10 11#workラベル下のメールを取得 12imapobj.select() 13typ, data = imapobj.search(None, 'ALL') 14 15#取得したメールから表題と本文を出力し、添付ファイルを同階層に書き出す 16for num in data[0].split(): 17 typ, data = imapobj.fetch(num, '(RFC822)') 18 19 #メール内容(タイトル、本文、添付ファイルなど) 20 mail = email.message_from_string(data[0][1].decode('utf-8')) 21 22 #表題出力 23 subject = str(make_header(decode_header(mail["Subject"]))) 24 #print(f"タイトル:{subject}") 25 26 #本文出力と添付ファイル書き出し 27 for part in mail.walk(): 28 if part.get_content_maintype() == 'multipart': 29 continue 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: 35 with open('./' + filename, 'wb') as f: 36 f.write(part.get_payload(decode=True)) 37 print(f"{filename}を保存しました。") 38 39imapobj.close()

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。