0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Deven Jain
  • 27
  • 1
  • 8

4 Answers4

1

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"))
Aakash Singh
  • 409
  • 5
  • 13
1

Would you consider using Jinja Templates

pip install Jinja2

If you just add an extra bracket to your existing template

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

Thank You

Regards
XXXXXXXXXXXXX
XXXXXXXXXXXXX

You can then just pass in variables to the template to render it

from jinja2 import Template

name = "john"
date = "02/05/2032"

with open('email.txt') as file_:
    template = Template(file_.read())

body = template.render(b=name, e=date)
Tom
  • 182
  • 7
1

There are multiple ways to handle this.

  1. A brute force solution:- Replace placeholders with your variable. Given 'USER' is the string you used to read in your file and 'DEVEN JAIN' is the variable to replace it with, just use FileContents.replace("{USER}", "DEVEN JAIN") -- This methosd I won't personally suggest

  2. A better way is to do using dictionaries. If you can define a dictionary of placeholders as keys and the corresponding values you want to substitute : -

    You can create a dynamic dictionary. Just for your reference, I created a static dictionary to show how you can make this work in an efficient manner :-

    # Script.py
    if __name__ == "__main__":
        body = open('body.txt', 'r')
        variables = {
            "USER": "Alok",
            "EMAIL_ID": "xyz@gmail.com",
            "MSSG": "Happy to help !!!"
        }
        k = body.read().format(**variables)
        print("Mail Body : -"+k) 
    

Body.txt: -

Hi {USER},

This is in regarding your account associated with us with username :- {EMAIL_ID}.
Please do reach out to us for any assistance.
{MSSG}

Thanks
Alok 

Stdout Output after running the above python script: -

Mail Body : -Hi Alok,

This is in regarding your account associated with us with username :- xyz@gmail.com.
Please do reach out to us for any assistance.
Happy to help !!!

Thanks
Alok
halfer
  • 19,824
  • 17
  • 99
  • 186
Pratap Alok Raj
  • 1,098
  • 10
  • 19
0

Instead of F-String I prefer to user .format(b='name', e='something') method.

Suyog Shimpi
  • 706
  • 1
  • 8
  • 16