Home > database >  Python smtplib - not sending with variables
Python smtplib - not sending with variables

Time:12-28

I am trying to send an email using the smtplib library. It works fine, but if my message includes a fixed string variable, it doesn't work.

Here is my code:

destinationEmail = '[email protected]'
server = smtplib.SMTP("smtp.gmail.com", 587) 
server.starttls() 
server.login("[email protected]", "password") 
message = f"I am sending this variable: {variableName}" 
server.sendmail("[email protected]", destinationEmail, message)

Using the above code does not work. I've tried using this format for the message as well:

message = "I am sending this variable: "   variableName

It also does not work. If my message has no variables, it sends successfully, like:

message = "testing"

Another thing I've tried is sending the variable alone, like:

message = variableName

And that works! So I'm really confused what is wrong here. It seems like it doesn't wanna send messages that has a fixed string variable. BTW the variable I am using is of type string. Even when I use str( ) around the variable, it doesn't work.

CodePudding user response:

This is usually a version problem, but you can always substitute your f-string for message = "I am sending this variable: {}".format(variable_name) which worked for me.

CodePudding user response:

The answer is here: How to send variable value via email with smtplib in python3?

Use MIMEText to construct the message (with 'subject' 'from' and 'to'). @tax evader was right about the subject thing. I guess it requires a subject.

  • Related