2012-01-04 59 views
0

我希望能夠有一個配置文件與各種各樣的內容郵寄出去。每封電子郵件都需要包含一個主題和一個主體,並添加新行。Python:電子郵件內容配置文件

例如:

[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)?

感謝

回答

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') 
  • 解析郵件
  • 隨機選擇一個郵件
+0

謝謝,按預期工作,並允許我根據需要進行調整。 – mikeyy 2012-01-04 12:50:54

+0

任何想法爲什麼只有一個新行之前,問候,而不是兩個? – mikeyy 2012-01-04 22:12:52

+0

@mikeyy'body + = line [len('Body:'):]' – kev 2012-01-05 01:07:16

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"]。然後使用該部分名稱來獲取所需的其他值。

+0

感謝。看起來比kev更加簡化,但兩者都按預期工作。 – mikeyy 2012-01-04 12:49:39

+1

[demo](http://ideone.com/nOEld) – jfs 2012-01-04 14:02:59

+0

@ J.F.Sebastian:哇,我不知道那個網站!涼! – 2012-01-04 14:57:41