Using Python, I wrote a simple timer that sends an email when the timer reaches 0. But the only part of the message being sent is the body. The sender address, recipient address, and subject are not being sent. Here is the code:
#Coffee timer
import smtplib
#Set timer for 00:03:00
from time import sleep
for i in range(0,180):
print(180 - i),
sleep(1)
print("Coffee is ready")
print("Sending E-mail")
SUBJECT = 'Coffee timer'
msg = '\nCoffee is ready'
TO = 'email-B@email.com'
FROM = 'email-A@email.com'
server = smtplib.SMTP('192.168.1.8')
server.sendmail(FROM, TO, msg, SUBJECT)
server.quit()
print("Done")
Can anyone explain why this is happening/what I can do to resolve it?
Before passing the message to .sendmail()
, you must format the message as an "RFC822" message. (It is named that after the original and now obsolete version of the Internet email message format standard. The current version of that standard is RFC5322.)
An easy way to create RFC822 messages is to use Python's email.message
type heirarchy. In your case, the subclass email.mime.text.MIMEText
will do nicely.
Try this:
#Coffee timer
import smtplib
from email.mime.text import MIMEText
print("Coffee is ready")
print("Sending E-mail")
SUBJECT = 'Coffee timer'
msg = 'Coffee is ready'
TO = 'email-B@email.com'
FROM = 'email-A@email.com'
msg = MIMEText(msg)
msg['Subject'] = SUBJECT
msg['To'] = TO
msg['From'] = FROM
server = smtplib.SMTP('192.168.1.8')
server.sendmail(FROM, TO, msg.as_string())
server.quit()
print("Done")
As a convenient alternative to .sendmail()
, you can use .send_message()
, like so:
# Exactly the same code as above, until we get to smtplib:
server = smtplib.SMTP('192.168.1.8')
server.send_message(msg)
server.quit()