Variable in email_body

I have a varible being generated by a loop through OpenAI and storing the answer in a txt file. The variable will print, but I can’t get it display within the sent email

I’ve tried {answer}

Appreciate any help on this one. Thanks Woody

Below is that part of the code.

open the answer.txt file

with open(‘answer.txt’, ‘r’) as answer: # answer.txt file has the response for OpenAI
for line in answer:
answer = line[line.find(‘user:’):line.find(‘Thank:’)]
email_body = ‘We are sorry to inform you that big has gone out of business.’


for address in addresses:
# create and configure the email message
msg: EmailMessage = EmailMessage()
msg.add_alternative(email_body + answer)
#msg.add_alternative("we are sorry " {answer})

# Add message headers
msg['Subject'] = "so good"
msg['From'] = sender_email
msg['To'] = address

# send the email
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
    server.login(sender_email, password)
    server.send_message(msg)'Email sent to {}'.format(address))

except Exception as e:
#log the exception

I searched related openai and related python, email.message

How does your answer.txt really look like?
Is answer.txt really closed before you try to open it by Python and not in use by anything else adding further lines to the file for example.

The next things is to decide how you want to read the file. Line by line, all lines. That can be used to just print whatever Python will find within the file.

Then the next things is to think over how to find the string you like to figure out.
To find a substring within a string. If the string can not be found find it will return -1.

Does your answer.txt always and solely have just one single line and will that look like the below:
user: Tom answer: Happy

But which information are you then searching for?

with open('answer.txt','r') as fin :
    lines = fin.readlines()

line_num = -1
for k,line in enumerate(lines) :
    if line.find( search ) != -1 :
        line_num = k

`user: Tom answer: Happy`

You can print the variable answer and only and solely want to know how to add it’s value to the e-mail body.
You tried the below
"msg.add_alternative(email_body + answer)
#msg.add_alternative(“we are sorry " {answer})”
I’m not the expert on that.

add_alternative(*args, content_manager=None, **kw)
If the message is a multipart/alternative, create a new message object, pass all of the arguments to its set_content() method, and attach() it to the multipart. If the message is a non-multipart or multipart/related, call make_alternative() and then proceed as above. If the message is any other type of multipart, raise a TypeError. If content_manager is not specified, use the content_manager specified by the current policy.

Thus you may need to go along content method