Search code examples
pythonemailsmtplib

Python smtplib - No recipient after sending mail


I recently wrote a script that sent me an email if a website I wanted to monitor had changed using smtplib. The program works, and I get the email but when I look at the sent email (as I am sending myself the email from the same account), it says that there is no recipient or 'To:' address, only a Bcc with the address I want the email to be sent to. Is this a feature of smtplib -- that it doesn't actually add a 'To:' address, only Bcc addresses? code is as follows:

if (old_source != new_source):

# now we create a mesasge to send via email
fromAddr = "example@gmail.com"
toAddr = "example@gmail.com"
msg = ""

# smtp login
username = "example@gmail.com"
pswd = "password"

# create server object and login to the gmail smtp
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.login(username, pswd)
server.sendmail(fromAddr, toAddr, msg)
server.quit()

Solution

  • Updating your code as follows will do the trick:

    if (old_source != new_source):
    
    # now we create a mesasge to send via email
    fromAddr = "example@gmail.com"
    toAddr = "example@gmail.com"
    msg = ""
    
    # smtp login
    username = "example@gmail.com"
    pswd = "password"
    
    # create server object and login to the gmail smtp
    
    server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
    header = 'To:' + toAddr + '\n' + 'From: ' + fromAddr + '\n' + 'Subject:testing \n'
    msg = header + msg
    server.login(username, pswd)
    server.sendmail(fromAddr, toAddr, msg)
    server.quit()