I'm having a file.txt file which has many lines. I want that any one line is chosen at random and emailed. This is looped thrice.
import smtplib,datetime,random
def mail(em):
#print "yo"
fromAddress = "[email protected]"
toAddress = "[email protected]"
subject = "WOW " + str(datetime.datetime.now())
#print subject
msg = em
server=smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
password = "mypassword"
server.login(fromAddress, password)
server.sendmail(fromAddress, toAddress, msg)
#print server.sendmail(fromAddress, toAddress, msg)
for i in range(0,3):
em=str(random.choice(list(open('file.txt'))))
mail(em)
This code does not work. The login and everything is fine. The only problem I notice is that server.sendmail(fromAddress, toAddress, msg) returns an empty {} What could be the possible fix to this? Whats the problem in first place? I have run the mail() function in the terminal and that seems to work fine. All the files are hosted here
First, as the docs say:
So, the fact that you're getting back
{}
isn't a problem; it means that you had no errors.Second, what you're sending is not a valid message. A message must contain headers, then a blank line, then the body. And the headers should contain at least
From:
andTo:
.The
smtplib
library doesn't do this for you; as explained in the example:Or, in the
sendmail
docs:In this case (as in the example), it's simple enough to just craft the message manually:
Finally, you really should call
server.quit()
at the end of themail
function. While (at least in CPython) theserver
object will be destroyed as soon as the function ends, unlike many other objects in Python,SMTP
objects do not callclose
when destroyed, much lessquit
. So, from the server's point of view, you're suddenly dropping connection. While the RFCs suggest that a server should work just fine without aQUIT
, and most of them do, they also recommend that the client should always send it and wait for a response, so… why not do it?