Python 如何将使用poplib捕获的电子邮件转发到其他电子邮件地址?

Python 如何将使用poplib捕获的电子邮件转发到其他电子邮件地址?,python,poplib,Python,Poplib,我有下面的脚本处理电子邮件并保存到csv文件。在脚本中,我将使用mechanize lib处理提取的电子邮件数据,以便在另一个web界面上进行进一步处理。有时它可能会失败,现在我可以捕获特定的电子邮件而没有任何问题,但我如何将捕获的电子邮件转发到其他地址,在那里我可以手动处理它或查看它有什么问题 这是剧本 import ConfigParser import poplib import email import BeautifulSoup import csv import time DEBU

我有下面的脚本处理电子邮件并保存到csv文件。在脚本中,我将使用mechanize lib处理提取的电子邮件数据,以便在另一个web界面上进行进一步处理。有时它可能会失败,现在我可以捕获特定的电子邮件而没有任何问题,但我如何将捕获的电子邮件转发到其他地址,在那里我可以手动处理它或查看它有什么问题

这是剧本

import ConfigParser
import poplib
import email
import BeautifulSoup
import csv
import time

DEBUG = False
CFG = 'email'    # 'email' or 'test_email'


#def get_config():
def get_config(fnames=['cron/orderP/get_orders.ini'], section=CFG):
    """
    Read settings from one or more .ini files
    """
    cfg = ConfigParser.SafeConfigParser()
    cfg.read(*fnames)
    return {
        'host':    cfg.get(section, 'host'),
        'use_ssl': cfg.getboolean(section, 'use_ssl'),
        'user':    cfg.get(section, 'user'),
        'pwd':     cfg.get(section, 'pwd')
    }

def get_emails(cfg, debuglevel=0):
    """
    Returns a list of emails
    """
    # pick the appropriate POP3 class (uses SSL or not)
    #pop = [poplib.POP3, poplib.POP3_SSL][cfg['use_ssl']]

    emails = []
    try:
        # connect!
        print('Connecting...')
        host = cfg['host']
        mail = poplib.POP3(host)
        mail.set_debuglevel(debuglevel)  # 0 (none), 1 (summary), 2 (verbose)
        mail.user(cfg['user'])
        mail.pass_(cfg['pwd'])

        # how many messages?
        num_messages = mail.stat()[0]
        print('{0} new messages'.format(num_messages))

        # get text of messages
        if num_messages:
            get = lambda i: mail.retr(i)[1]                 # retrieve each line in the email
            txt = lambda ss: '\n'.join(ss)                  # join them into a single string
            eml = lambda s: email.message_from_string(s)    # parse the string as an email
            print('Getting emails...')
            emails = [eml(txt(get(i))) for i in xrange(1, num_messages+1)]
        print('Done!')
    except poplib.error_proto, e:
        print('Email error: {0}'.format(e.message))

    mail.quit() # close connection
    return emails

def parse_order_page(html):
    """
    Accept an HTML order form
    Returns (sku, shipto, [items])
    """
    bs = BeautifulSoup.BeautifulSoup(html)  # parse html

    # sku is in first <p>, shipto is in second <p>...
    ps = bs.findAll('p')                    # find all paragraphs in data
    sku = ps[0].contents[1].strip()         # sku as unicode string
    shipto_lines = [line.strip() for line in ps[1].contents[2::2]]
    shipto = '\n'.join(shipto_lines)        # shipping address as unicode string

    # items are in three-column table
    cells = bs.findAll('td')                        # find all table cells
    txt   = [cell.contents[0] for cell in cells]    # get cell contents
    items = zip(txt[0::3], txt[1::3], txt[2::3])    # group by threes - code, description, and quantity for each item

    return sku, shipto, items

def get_orders(emails):
    """
    Accepts a list of order emails
    Returns order details as list of (sku, shipto, [items])
    """
    orders = []
    for i,eml in enumerate(emails, 1):
        pl = eml.get_payload()
        if isinstance(pl, list):
            sku, shipto, items = parse_order_page(pl[1].get_payload())
            orders.append([sku, shipto, items])
        else:
            print("Email #{0}: unrecognized format".format(i))
    return orders

def write_to_csv(orders, fname):
    """
    Accepts a list of orders
    Write to csv file, one line per item ordered
    """
    outf = open(fname, 'wb')
    outcsv = csv.writer(outf)
    for poNumber, shipto, items in orders:
      outcsv.writerow([])     # leave blank row between orders
      for code, description, qty in items:
        outcsv.writerow([poNumber, shipto, code, description, qty])
        # The point where mechanize will come to play

def main():
    cfg    = get_config()
    emails = get_emails(cfg)
    orders = get_orders(emails)
    write_to_csv(orders, 'cron/orderP/{0}.csv'.format(int(time.time())))

if __name__=="__main__":
    main()
导入配置解析器
导入poplib
导入电子邮件
进口美联
导入csv
导入时间
调试=错误
CFG=‘email’#‘email’或‘test#u email’
#def get_config():
def get_config(fnames=['cron/orderps/get_orders.ini'],section=CFG):
"""
从一个或多个.ini文件读取设置
"""
cfg=ConfigParser.SafeConfigParser()
cfg.read(*fnames)
返回{
'host':cfg.get(部分'host'),
'use_ssl':cfg.getboolean(部分'use_ssl'),
'user':cfg.get(部分'user'),
'pwd':cfg.get(第'pwd'节)
}
def get_电子邮件(cfg,debuglevel=0):
"""
返回电子邮件列表
"""
#选择适当的POP3类(是否使用SSL)
#pop=[poplib.POP3,poplib.POP3_SSL][cfg['use_SSL']]
电子邮件=[]
尝试:
#连接!
打印('连接…')
host=cfg['host']
mail=poplib.POP3(主机)
mail.set_debuglevel(debuglevel)#0(无)、1(摘要)、2(详细)
mail.user(cfg['user'])
邮件传递(cfg['pwd'])
#有多少条留言?
num_messages=mail.stat()[0]
打印({0}条新消息)。格式(num_消息))
#获取消息文本
如果num_消息:
get=lambda i:mail.retr(i)[1]#检索电子邮件中的每一行
txt=lambda ss:'\n'.join(ss)#将它们连接成一个字符串
eml=lambda s:email.message_from_string#将字符串解析为电子邮件
打印('获取电子邮件…')
emails=[eml(txt(get(i)),用于xrange中的i(1,num_messages+1)]
打印('Done!')
除poplib.error_proto外,e:
打印('电子邮件错误:{0}'。格式(电子邮件))
mail.quit()#关闭连接
回复电子邮件
def解析顺序页面(html):
"""
接受HTML订单
退货(sku、发货人、[项目])
"""
bs=BeautifulSoup.BeautifulSoup(html)#解析html
#sku在第一位,shipto在第二位。。。
ps=bs.findAll('p')#查找数据中的所有段落
sku=ps[0]。内容[1]。strip()#sku为unicode字符串
shipto_lines=[line.strip(),用于ps[1]中的行。内容[2::2]]
shipto='\n'.连接(shipto_行)#作为unicode字符串的发货地址
#项目在三列表中
cells=bs.findAll('td')#查找所有表格单元格
txt=[cell.contents[0]用于单元格中的单元格]#获取单元格内容
items=zip(txt[0::3]、txt[1::3]、txt[2::3])#按三个字母分组-每个项目的代码、说明和数量
退货sku、发货人、物品
def获取订单(电子邮件):
"""
接受订单电子邮件列表
将订单详细信息作为列表返回(sku、发货人、[项目])
"""
订单=[]
对于i,枚举中的eml(电子邮件,1):
pl=eml.get_有效载荷()
如果存在(pl,列表):
sku,shipto,items=parse\u order\u页面(pl[1]。获取有效负载()
订单。追加([sku、发货人、项目])
其他:
打印(“电子邮件#{0}:无法识别的格式”。格式(i))
退货单
def写入到csv(订单、fname):
"""
接受订单列表
写入csv文件,每订购一项一行
"""
OUT=打开(fname,“wb”)
outcsv=csv.writer(outp)
对于poNumber、shipto、订单中的项目:
outcsv.writerow([])#在订单之间保留空行
对于代码、说明、项目数量:
outcsv.writerow([poNumber,shipto,code,description,qty])
#机械化将发挥作用的那一点
def main():
cfg=get_config()
电子邮件=获取电子邮件(cfg)
订单=获取订单(电子邮件)
将_写入_csv(orders,'cron/orderps/{0}.csv'。格式(int(time.time()))
如果名称=“\uuuuu main\uuuuuuuu”:
main()

我们都知道POP3仅用于检索(那些知道或知道电子邮件如何工作的人),因此在发送邮件时使用POP3没有任何意义,这就是为什么我提到如何将使用poplib捕获的电子邮件转发到不同的电子邮件地址?作为一个问题

完整的答案是 smtplib可以用于转发poplib捕获的电子邮件,您只需捕获邮件正文并使用smtplib将其发送到所需的电子邮件地址。此外,正如Aleksandr Dezhin引用的,我同意他的观点,因为一些SMTP服务器对它们处理的邮件施加了不同的限制


此外,如果您在Unix机器上,您还可以使用sendmail来实现这一点。

POP3不是关于发送或转发电子邮件的。对于发送电子邮件,您可以使用SMTP和。但您需要SMTP服务器。是否可以使用smtplib发送捕获的电子邮件?我是否需要在使用smtplib时修改消息,或者我可以按捕获的方式发送消息?通常,是的,您可以按“原样”发送消息正文。但是,某些SMTP服务器对其处理的邮件施加了不同的限制。