Search code examples
pythonemailencodingmimesmtplib

Sending an email in a python script using smtplib and MIMEText, but recieving an encoding error


I am trying to write a python script that sends an email. My code currently looks like:

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 = 'person@gmail.com'
        you = 'person@gmail.com'

        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()

Currently, running this gives me the error that:

File "server.py", line 43, in testServer msg = MIMEText(fp.read()) File "C:\Users\663255\AppData\Local\Programs\Python\Python36\lib\email\mime\text.py", line 34, in init _text.encode('us-ascii') AttributeError: 'bytes' object has no attribute 'encode'

However, I have tried changing the encoding from ascii to unicode or UTF-8 and it still gave me the above error referencing ascii...

Is there a simple resolution to this, or another approach to sending an email that is simpler? Thank you!


Solution

  • In order for MIMEText() to process the read text from fp correctly, you should try opening the file in read mode (i.e. using 'r') instead of binary read mode.