2017-08-04 28 views
0

電子メールを送信するpythonスクリプトを作成しようとしています。中れ、testServer MSG =ます:MIMEText(fp.read())、smtplibとMIMETextを使用してpythonスクリプトで電子メールを送信するが、エンコーディングエラーを受け取る

ファイル "server.py"、行43:これは私にエラーを与えていることを実行している、現在

import unittest 
from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 
import os 
import time 
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary 
from selenium.webdriver.common.action_chains import ActionChains 
from urllib.request import urlopen 
from html.parser import HTMLParser 
import smtplib 
from email.mime.text import MIMEText 



binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\Firefox.exe') 
driver = webdriver.Firefox(firefox_binary=binary, executable_path='C:\geckodriver-v0.18.0-win64\geckodriver.exe') 


class PythonOrgSearch(unittest.TestCase): 

    def setUp(self): 
     self.driver = driver 

    def testServer(self): 
     me = '[email protected]' 
     you = '[email protected]' 

     with open("testfile.txt", 'rb') as fp: 
       msg = MIMEText(fp.read()) 
     msg['Subject']= 'Testing email' 
     msg['From'] = me 
     msg['To'] = you 
     s = smtplib.SMTP('localhost') 
     s.sendmail(me, [you], msg.as_string()) 
     s.quit() 
     driver.close() 
if __name__ == "__main__": 
    unittest.main() 

:私のコードは、現在のようになります。 ファイル "C:¥Users¥663255¥AppData¥Local¥Programs¥Python¥Python36¥lib¥email¥mime¥text.py"、行34、 _text.encode( 'us-ascii') AttributeError: 'bytes'オブジェクトに 'エンコード'属性がありません

ただし、エンコードをasciiからunicodeまたはUTF-8にぶら下げても、上記のエラーがasciiを参照していました...

簡単な解決方法がありますか?ありがとうございました!

+0

行番号を追加することができます –

答えて

1

MIMEText()は、fpの読み取りテキストを正しく処理するために、バイナリ読み取りモードではなく、読み取りモード(つまり、'r'を使用)でファイルを開こうとする必要があります。

+0

これはうまくいきましたが、これを除いて問題は次のとおりです。ConnectionRefusedError:[WinError 10061]ターゲットマシンが積極的に拒否したため接続できませんでした –

+0

これはコードに電子メールの資格情報を持たない電子メールですか? –

+1

これはおそらく、 'localhost'ターゲット上で実行されているSMTPサーバがないためです。 'smtplib.SMTP()'関数は、対象のメールサーバを特定する文字列を取ります。したがって、有効なアドレスを指定してください。 – Kayjukh

関連する問題