0

I am trying to make a program that'd email me the date and time whenever it is run. I am using smtlib and verified it already using some string as message and it is working fine. But whenever I add datetime variable and convert it to string it sends an empty email.

import smtplib
import datetime

b=datetime.datetime.time(datetime.datetime.now())

print b

svr = smtplib.SMTP("smtp.gmail.com:587")
svr.starttls()
svr.login("******@*****", "*********") 

msg = str(b)


svr.sendmail("******@*****", "******@*****", msg)
print ("Terminate")

svr.quit()
Aniruddha Bera
  • 399
  • 6
  • 19

2 Answers2

1

You should add headers to your msg :

headers  = "From: From Person \r\n"
headers += "To: To Person \r\n"
headers += "Subject: \r\n"
headers += "\r\n"
msg = headers + msg
t.m.adam
  • 15,106
  • 3
  • 32
  • 52
  • IMHO, this fixes the problem. Of course valid mail addresses must be supplied. RFC2822 states that the header lines should be CRLF terminated, i.e. with `\r\n` – VPfB Apr 09 '17 at 08:06
  • In theory yes , but it works . And you are right about the `\r\n` , i will update my post . – t.m.adam Apr 09 '17 at 08:11
-2

This is kinda messy but it works, what I have have done is but b in a list called c and sent the list instead, unfortunately I have no idea why what you where doing doesn't work... Here's the code:

import smtplib
import datetime
b = datetime.datetime.time(datetime.datetime.now())
c = []
c.insert(0, b)
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login("***********", "***********")

msg = '' + str(c) + ''
server.sendmail("**********", "*********", msg)
server.quit()
raise SystemExit   
elmuscovado
  • 114
  • 3
  • 6
  • 13