Search code examples
pythonsmtplib

Python smtplib subject not working inside function


I'm experiencing a curious phenomenon when using the smtplib for Python. I'm writing a simple message using f-strings and two \n's to delimit the subject header. This works fine when outside a function, but behaves differently when inside one.

Email sent from outside the function delivers with subject: "Outside a function" Email sent from inside the function delivers with subject: "No Subject"

Why is this?

Of course I would like to fix this, but ultimately I am more interested in what's causing this!

Code below... just slap your gmail address and password in if you want to test.

import smtplib

login = "youremail@gmail.com"
password = "yourpassword"

name = "name"

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(login, password)


def sendMail():
    message = f"""\
    Subject: Sent from inside a function
    To: {login}
    From: {login}

    Hello {name},
    This is sent from inside a function"""

    server.sendmail(login, receiver, message)

sendMail()


message = f"""\
Subject: Outside a function
To: {login}
From: {login}

Hello {name},
This is sent from outside a function"""

server.sendmail(login, receiver, message)

Solution

  • import smtplib
    
    login = "test@gmail.com"
    password = "test"
    receiver=login
    
    name = "name"
    
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(login, password)
    
    
    def sendMail():
        message = f"""\
    Subject: Sent from inside a function
    To: {login}
    From: {login}
    
    Hello {name},
    This is sent from inside a function"""
    
        server.sendmail(login, receiver, message)
    
    
    sendMail()
    

    python indentation is applicable only for commands not for multi-line string. when you give space it has different syntax not the same. The above will create same result

    https://stackoverflow.com/a/2504457/6793637

    if you don't want the unnecessary indentation start it from first line itself

    import smtplib
    
    login = "test@gmail.com"
    password = "test"
    receiver=login
    
    name = "name"
    
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(login, password)
    
    
    def sendMail():
        message = f"""Subject: Sent from inside a function
        To: {login}
        From: {login}
    
        Hello {name},
        This is sent from inside a function"""
    
        server.sendmail(login, receiver, message)
    
    
    sendMail()