【问题标题】:How to read string from a file that contains placeholders for variables and add it to the code and then send an email?如何从包含变量占位符的文件中读取字符串并将其添加到代码中,然后发送电子邮件?
【发布时间】:2021-08-09 18:03:06
【问题描述】:

我有一个名为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 文件时实际工作。

这里是 ma​​in.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()

接下来我可以尝试什么?

【问题讨论】:

  • 我更喜欢使用 .format(b='name', e='something') 方法,而不是 F-String。
  • 如何将它集成到我的代码中?
  • 更新:成功了,谢谢!请将其发布为答案,以便我投票并标记为已批准。

标签: python string email email-attachments f-string


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你会考虑使用 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)
    

    【讨论】:

      【解决方案3】:

      有多种方法可以处理这个问题。

      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) 
        

      正文.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脚本后的Stdout输出:-

      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
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2021-02-13
          • 1970-01-01
          • 2015-01-18
          • 1970-01-01
          • 1970-01-01
          • 2021-09-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多