带附件的转发邮件

时间:2014-10-29 17:06:46

标签: python email imap forwarding

我想在Python中重新发送附件的电子邮件。我有这个用于发送电子邮件的代码但是如何在另一封电子邮件中引用附件?

发送

def show_emails():
    M.select()
    typ, data = M.search(None, 'All') 
    for num in data[0].split(): 
        typ, data = M.fetch(num, '(RFC822)')
        parser = Parser()
        email = parser.parsestr(data[0][1])
        print "MESSAGE NUMBER %s" % (num)
        print 'Raw Date:'
        print email.get('Date')
        print "From:"
        print email.get('From') 
        print "Subject: "
        print email.get('Subject')

此代码用于发送

msg = MIMEMultipart()

mfrom = 'from@abc.com'
mto = 'to@abc.com'

msg['Subject'] = 'test'
msg['From'] = mfrom
msg['To'] = mto
msg['Date'] = formatdate()

# Open the file to scan in binary mode
fp = open('/path/to/file', 'rb')
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(fp.read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename="filename"')
fp.close()
msg.attach(attachment)

我知道我需要检查是否有任何附件。我怎样才能引用附件并将其转发?

if msg.is_multipart():
        for part in msg.walk(): 
        fileName = part.get_filename()
        if bool(fileName):
            print "Attachment: %s " % (decode_header(fileName)[0][0])
        else:
            print "No attachments" 

1 个答案:

答案 0 :(得分:0)

你不能仅仅参考它:那是什么RFC 4467-9,但是许多服务器都没有实现这些服务器,此时我认为它们已经死了。您必须下载附件并将其发送,就像发送本地文件一样。