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
import smtplib from smtplib import SMTPException class SendMail: def __init__(self, sender, subject, contents): self.sender = sender self.subject = subject self.contents = contents def sendmail(self, recipients_text): # 接続先 SMTP サーバの定義 smtp = smtplib.SMTP('smtp.office365.com', 587) # FQDN とポート番号 # 認証情報の定義 user = self.sender # SMTP サーバに接続するためのユーザ password = "password" # SMTP サーバへの接続とメールの送信 try: smtp.ehlo() smtp.starttls() # TLS の開始(以降の通信は暗号化される) smtp.ehlo() smtp.login(user, password) # SMTP サーバにログイン #ヘッダー header = 'To:' + recipients_text + '\n' + 'From: ' + self.sender + '\n' + 'Subject:' + self.subject + '\n' #本文 message_body = header + '\n' + self.contents + '\n\n' result = smtp.sendmail( self.sender, recipients_text.split(','), message_body ) # メールの送信 smtp.quit() # SMTP セッションの終了と TCP コネクションの切断 except smtplib.SMTPException as e: print("エラーが起きました!送信できません") #送信者アドレス・送信内容 f = open("mail_content.txt", encoding='utf-8') #1行目はスキップ file_contents = f.readlines() #送信者メールアドレス・件名・本文をテキストファイルから読み込み Sender = file_contents[1] Sender = Sender.rstrip("\n") Subject = file_contents[2] Subject = Subject.rstrip("\n") Contents = "" for i in range(3, len(file_contents)): Contents = Contents + file_contents[i] f.close() sendmail = SendMail(Sender, Subject, Contents) sendmail.sendmail("BBB@example.com","CCC@example.com")
送信者、件名、内容の順番 AAA@example.com 件名 本文
###試したこと
>>> import sys >>> sys.getdefaultencoding() 'utf-8'
補足情報
Python: 3.6.5
テキストファイルの文字コードはUTF-8(BOMなし)
まだ回答がついていません
会員登録して回答してみよう