引っ張ってきたメールのタイトルをhtmlに書き込むようなコードを書きたいのですが、いろいろ試しても文字化けしてしまいます。なぜだか教えていただけないでしょうか?
import imaplib import email UserName=********@gmail.com" PassName="*********" gmail = imaplib.IMAP4_SSL("imap.gmail.com", '993') gmail.login(UserName, PassName) gmail.select() head, data = gmail.search(None, 'ALL') class htmlwriting(): def __init__(self): self.file=file def hwrite(self): with codecs.open(file, 'w', encoding='utf-8') as f: for num in data[0].split(): h, d = gmail.fetch(num, '(RFC822)') raw_email = d[0][1] msg = email.message_from_string(raw_email.decode('utf-8','ignore')) msg_encoding = email.header.decode_header(msg.get('Subject'))[0][1] or 'iso-2022-jp' msg_subject = email.header.decode_header(msg.get('Subject'))[0][0] msg_subject=msg_subject.decode('utf-8','ignore') f.write(msg_subject) if __name__=="__main__": file="b.html" htmlwriting.hwrite(file) gmail.close() gmail.logout()