Python3でメール送信(文字コードエラー)
Python3でメール送信(送信先複数)が出来るようにしたいです。
実装したいのは「件名・本文が書かれているテキストファイルを読み込み、その内容を送信」といった機能です。
現在、件名・タイトルのいずれかに日本語を使用するとエラーが起きてしまいます。
エラーメッセージ
Traceback (most recent call last): File "sendmailer.py", line 50, in <module> sendmail.sendmail("BBB@example.com,CCC@example.com") File "sendmailer.py", line 28, in sendmail result = smtp.sendmail( self.sender, recipients_text.split(','), message_body ) # メールの送信 File "C:\Users\---\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 855, in sendmail msg = _fix_eols(msg).encode('ascii') UnicodeEncodeError: 'ascii' codec can't encode characters in position 106-108: ordinal not in range(128)
該当のソースコードとテキストファイル
Python
1import smtplib 2from smtplib import SMTPException 3 4class SendMail: 5 def __init__(self, sender, subject, contents): 6 self.sender = sender 7 self.subject = subject 8 self.contents = contents 9 10 def sendmail(self, recipients_text): 11 # 接続先 SMTP サーバの定義 12 smtp = smtplib.SMTP('smtp.office365.com', 587) # FQDN とポート番号 13 # 認証情報の定義 14 user = self.sender # SMTP サーバに接続するためのユーザ 15 password = "password" 16 17 # SMTP サーバへの接続とメールの送信 18 try: 19 smtp.ehlo() 20 smtp.starttls() # TLS の開始(以降の通信は暗号化される) 21 smtp.ehlo() 22 smtp.login(user, password) # SMTP サーバにログイン 23 #ヘッダー 24 header = 'To:' + recipients_text + '\n' + 'From: ' + self.sender + '\n' + 'Subject:' + self.subject + '\n' 25 #本文 26 message_body = header + '\n' + self.contents + '\n\n' 27 28 result = smtp.sendmail( self.sender, recipients_text.split(','), message_body ) # メールの送信 29 smtp.quit() # SMTP セッションの終了と TCP コネクションの切断 30 except smtplib.SMTPException as e: 31 print("エラーが起きました!送信できません") 32 33 34 35#送信者アドレス・送信内容 36f = open("mail_content.txt", encoding='utf-8') 37#1行目はスキップ 38file_contents = f.readlines() 39#送信者メールアドレス・件名・本文をテキストファイルから読み込み 40Sender = file_contents[1] 41Sender = Sender.rstrip("\n") 42Subject = file_contents[2] 43Subject = Subject.rstrip("\n") 44Contents = "" 45for i in range(3, len(file_contents)): 46 Contents = Contents + file_contents[i] 47f.close() 48 49sendmail = SendMail(Sender, Subject, Contents) 50sendmail.sendmail("BBB@example.com","CCC@example.com")
送信者、件名、内容の順番 AAA@example.com 件名 本文
###試したこと
>>> import sys >>> sys.getdefaultencoding() 'utf-8'
補足情報
Python: 3.6.5
テキストファイルの文字コードはUTF-8(BOMなし)
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。