首页 > 解决方案 > Python/Thunderbird 中的字符串格式化

问题描述

Noob,尝试使用 Thunderbird(而不是 SMTP)向几十个人发送个性化电子邮件。我基本上希望在 Thunderbird 中显示如下消息:

Dear Bob, 

It was nice to meet you the other day.

但是,我最终得到:

Dear Bob (comma missing, and rest of body missing)

我尝试了以下方法:

import subprocess
import os

def send_email(name, email_address):
    #print(name, email_address)
    os.system("thunderbird -compose to= 'to',subject='subject',body='body'")
    tbirdPath = r'c:\Program Files (x86)\Mozilla Thunderbird\thunderbird.exe'
    to = email_address
    subject = 'Test Subject LIne'
    #body = "Dear %s, \n\n This is the body." %(name)
    body = 'html><body>Dear %s, This is the body <br></body></html>'%(name) 
    composeCommand = 'format=html,to={},subject={},body={}'.format(to, subject, body)
    subprocess.Popen([tbirdPath, '-compose', composeCommand])

与往常一样,我可以实现的简单答案优于我无法实现的复杂答案。我怀疑我在字符串格式方面遗漏了一些愚蠢的东西,但不确定到底是什么。在此先感谢您的帮助。

标签: pythonstring-formatting

解决方案


此示例中,您可能需要用单引号和双引号将参数括起来。

像这样:

composeCommand = '"format=html,to=\'{}\',subject=\'{}\',body=\'{}\'"'.format(to, subject, body)

顺便说一句,如果您使用的是 python 3.6+,则使用 f-strings 会使 str 更具可读性:

body = f'<html><body>Dear {name}, This is the body <br></body></html>' 
composeCommand = f'"format=html,to=\'{to}\',subject=\'{subject}\',body=\'{body}\'"'

推荐阅读