简体   繁体   中英

Python smtplib - not sending with variables

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 = 'destination@gmail.com'
server = smtplib.SMTP("smtp.gmail.com", 587) 
server.starttls() 
server.login("me@gmail.com", "password") 
message = f"I am sending this variable: {variableName}" 
server.sendmail("me@gmail.com", 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM