通过Python在电子邮件中替换值

0 投票
2 回答
823 浏览
提问于 2025-04-16 21:38

用Python替换邮件中的值

我刚开始学习Python,想写一个脚本来给一群人发送邮件(用HTML格式)。

这个Python脚本会运行一个Perl脚本,Perl脚本会读取一个Excel文件,然后把内容保存到一个.txt文件里。一旦这个文件创建好,Python脚本就会打开这个txt文件,并把所有的名字放到一个数组里:

以下是脚本的一部分

file = open(txtFile, "r" )
array = []
for line in file:
    array.append( line )

print array[2]
print array[1]

$ ./tempSendOnCall.py
分支编号是2011.06
07-15-11
Ash dy
Joe Des

完成这个部分后,我会在同一个脚本里创建一封邮件,然后把值替换成数组里的值,因为这些值每周都会变。

以下是邮件的部分内容:

sendmail="/p4/sendEmail"
SERVER = "ServerName"

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

me = "name@domain"
you = "name@domain"

msg = MIMEMultipart('alternative')
msg['Subject'] = "3LS / QA / SA on-call review"
msg['From'] = me
msg['To'] = you

text = "test"
html = """\
<html>
  Message
  Hi Ash dy, (Need to be updated from Array[1])
     starting on DATE (Should ready from date = time.strftime("%m-%d-%y"))

  Joe Des (Should be replaced with Array[2]) is the 3LS lead for this week.\n

  Let me know if you have any questions,

"""

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(part1)
msg.attach(part2)

s = smtplib.SMTP(SERVER)
s.sendmail(me, you, msg.as_string())
s.quit()

我现在一切都能正常工作,但我找不到方法在邮件中替换数组的值或日期!!

请帮帮我 :-)

-某人

2 个回答

0

你可以用一个 dict(字典)来替代你的字段(具体的内容)。你可以在这里查看相关的文档:字符串格式化操作。举个例子:

>>> Array = ["foo", "bar", "baz"]
>>> "some text %(a)s --more text %(b)s at %(c)s" % {"a":Array[1], "b":time.strftime("%m-%d-%y"), "c":Array[2]}
'some text bar --more text 07-15-11 at baz'
0

请让我引起你对格式化字符串函数的注意。

html = """\
<html>
  Message
  Hi {0:}, (Need to be updated from Array[1])
     starting on {1:} (Should ready from date = time.strftime("%m-%d-%y"))

  {2:} (Should be replaced with Array[2]) is the 3LS lead for this week.\n

  Let me know if you have any questions,

""".format(Array[1], time.strftime("%m-%d-%y"), Array[2])

当然,它需要访问你的数组变量才能正常工作。

撰写回答