2

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)

1 Answers1

0
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()
PDHide
  • 18,113
  • 2
  • 31
  • 46
  • Said differently, in OP's code, the header names were not at the beginning of a line which does not respect the SMTP protocol. – Serge Ballesta Dec 07 '20 at 11:21
  • @SergeBallesta the outer and inner works , but has different subject and format. OPs thought both to be same format – PDHide Dec 07 '20 at 11:23