如何从包含变量占位符的文件中读取字符串并将其添加到代码中,然后发送电子邮件?

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

我有一个名为 email_body.txt 的文本文件,它包含以下数据:

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

这曾经是 f string,电子邮件正文和电子邮件主题已修复。但是,我的客户要求电子邮件正文应该是可编辑的,因为他可能会在几个月内更改它。所以现在我卡住了。

我想创建一个文本文件并让客户按照他的意愿在该文件中修改电子邮件正文,并且我希望在将该字符串添加到我的 Python 文件时正文中的占位符真正起作用使用文件处理。

这里是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()

接下来我可以尝试什么?

您可以将电子邮件粘贴到文本文件中,例如 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

然后读取 python 中的文件并像在字符串中一样替换值。

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

您会考虑使用 Jinja 模板吗

pip install Jinja2

如果您只是在现有模板中添加一个额外的括号

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

然后您只需将变量传递给模板即可呈现它

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)

有多种方法可以解决这个问题。

  1. 暴力解决方案:- 用您的变量替换占位符。鉴于 'USER' 是您用来在文件中读取的字符串,而 'DEVEN JAIN' 是要替换它的变量,只需使用 FileContents.replace("{USER}", "DEVEN JAIN") - - 这个方法我个人不会推荐

  2. 更好的方法是使用字典。如果您可以将占位符字典定义为键和要替换的相应值:-

    您可以创建动态词典。仅供参考,我创建了一个静态字典来展示如何以高效的方式完成这项工作:-

    # 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 

运行 上述 python 脚本后的标准输出:-

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

我更喜欢使用 .format(b='name', e='something') 方法而不是 F-String。