Search code examples
pythonstringemailemail-attachmentsf-string

How to read string from a file that contains placeholders for variables and add it to the code and then send an email?


I have a text file called email_body.txt and it has the following data:

email_body.txt:

Dear {b},
Hope all your queries were resolved in your recent consultation with Dr. XXXXXXXXXXXXX on: {e}
Your prescription is attached herewith. Wishing you a speedy recovery!

Thank You

Regards
XXXXXXXXXXXXX
XXXXXXXXXXXXX

This used to be an f string and the email body and the email subject was fixed. However, my client requested that the email body should be editable, as he might change it in a few months. So now I am stuck.

I want to create a text file and let the client modify the email body as he wishes in that file and I want the placeholders in the body to actually work when I add that string to my Python file using file handling.

Here is main.py:

import smtplib, os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from typing import final
cwd=os.getcwd()
bodyf=cwd+"\Email_Body_&_Subject\email_body.txt"
print(bodyf)
b="Deven Jain"
e="XYZ"
email_user = "XXXXXXXXXXXXX@gmail.com"
email_password = "XXXXXXXXXXXXX"
email_send = "XXXXXXXXXXXXX@gmail.com"

subject = "Prescription of Consultation"

msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject

body=open(bodyf,"r")

x=body.read()
body.close()

final=f"{x}"

print(final)

body =final
msg.attach(MIMEText(body,'plain'))

'''
filename=pdfFile
attachment=open(filename,'rb')

part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
debug=filename.split(".")
if debug[-1]=="png":
    part.add_header('Content-Disposition',"attachment; filename= "+f"{c}-{b}_({e}).png")
else:
    part.add_header('Content-Disposition',"attachment; filename= "+f"{c}-{b}_({e}).pdf")
'''
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(email_user,email_password)

server.sendmail(email_user,email_send,text)
server.quit()

What can I try next?


Solution

  • You can just paste you email tin a text file like email.txt

    Dear {b},
    Hope all your queries were resolved in your recent consultation with Dr. XXXXXXXXXXXXX on: {e}
    Your prescription is attached herewith. Wishing you a speedy recovery!
    
    Thank You
    
    Regards
    XXXXXXXXXXXXX
    XXXXXXXXXXXXX
    

    Then read the file in python and substitute the values as you would in a string.

    with open("email.txt", "r") as f:
        print(f.read().format(b="user", e="email@example.com"))