Python:电子邮件内容配置文件

0 投票
2 回答
528 浏览
提问于 2025-04-17 09:31

我想要一个配置文件,里面有各种内容可以发送邮件。每封邮件都需要有主题和正文,并且要有换行。

比如说:

[Message_One]
Subject: Hey there
Body: This is a test
      How are you?
      Blah blah blah

      Sincerely,
      SOS

[Message_Two]
Subject: Goodbye
Body: This is not a test
      No one cares
      Foo bar foo bar foo bar

      Regards

我该怎么用Python来实现这个配置文件,让它随机选择内容,或者根据定义的名字(比如Message_One,Message_Two)来获取某一条内容呢?

谢谢

2 个回答

3

可能像这样:

from ConfigParser import ConfigParser
import random

conf = ConfigParser()
conf.read('test.conf')

mail = random.choice(conf.sections())
print "mail: %s" % mail
print "subject: %s" % conf.get(mail, 'subject')
print "body: %s" % conf.get(mail, 'body')

这其实就是用 random.choice(conf.sections()) 来随机选择一个部分名称。random.choice 这个函数会从一个序列中随机挑选一个元素,而 sections 方法会返回所有的部分名称,比如说 ["Message_One", "Message_Two"]。然后你就可以用这个部分名称去获取其他你需要的值。

1
#!/usr/bin/env python3
from re import match
from collections import namedtuple
from pprint import pprint
from random import choice

Mail = namedtuple('Mail', 'subject, body')

def parseMails(filename):
    mails = {}
    with open(filename) as f:
        index = ''
        subject = ''
        body = ''
        for line in f:
            m = match(r'^\[(.+)\]$', line)
            if m:
                if index:
                    mails[index] = Mail(subject, body)
                index = m.group(1)
                body = ''
            elif line.startswith('Subject: '):
                subject = line[len('Subject: '):-1]
            else:
                body += line[len('Body: '):]
        else:
            mails[index] = Mail(subject, body)
    return mails

mails = parseMails('mails.txt')
index = choice(list(mails.keys()))
mail = mails[index]
pprint(mail)
Mail(subject='Goodbye', body='This is not a test\nNo one cares\nFoo bar foo bar foo bar\nRegards\n')

这段内容主要是在讲如何处理邮件。具体来说,它包含了两个步骤:

  • 解析邮件:也就是把邮件的内容提取出来,方便后续使用。
  • 随机选择一封邮件:从解析出来的邮件中,随便挑选一封。

撰写回答