I'm trying to send a basic email using Python 3.3. I'm following the first bit of code here:
https://docs.python.org/3.3/library/email-examples.html
My code is as follows:
def emailCurrentRankings(recipientEmail):
fp = open('rankings.txt', 'rb')
msg = MIMEText(fp.read())
fp.close()
sender = '[email protected]'
msg['Subject'] = 'CSA Rankings'
msg['From'] = sender
msg['To'] = recipientEmail
s = smtplib.SMTP('localhost')
s.sendmail(sender, [recipientEmail], msg.as_string())
s.quit()
My main function calls this method like so:
emailCurrentRankings('[email protected]')
The only difference I can tell is that I use 'rankings.txt' instead of textfile on the second line. I've tried with both and get the same error message:
Traceback (most recent call last):
File "helpfulFunctions.py", line 128, in <module>
main()
File "helpfulFunctions.py", line 120, in main
emailCurrentRankings('[email protected]')
File "helpfulFunctions.py", line 106, in emailCurrentRankings
msg = MIMEText(fp.read())
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/email/mime/text.py", line 34, in __init__
_text.encode('us-ascii')
AttributeError: 'bytes' object has no attribute 'encode'
When I googled around, it looks like there's some authentication that has to happen (for me to be able to send from a given email). But their most basic example that I'm modeling my code on doesn't mention this...
Any ideas where I'm going astray?
Thanks, bclayman
smtplib.SMTP('localhost')). This won't solve your main problem which is probably due to an encoding error of the file. Try to follow this link to see how sending emails with attachments.smtp.gmail.com:587. Check the accept answer of a question of mine to allow your app sending emails through gmail: question link