简体   繁体   中英

Python - Forward IMAP Email with Attachments (imaplib, smtplib)

I'm having trouble forwarding mail with attachments. Can anyone point me in the right direction? I'm guessing it's in the Fetch statement but am unsure.

import sys
import uuid
import re
import smtplib
import email

address = ''
username = ''
password = ''

def checkMail():
    M = imaplib.IMAP4_SSL(address)
    M.login(username, password)
    M.select("INBOX", readonly=True)
    typ, data = M.search(None, 'Unseen')

    messageCount = len(data[0].split())    
    print('messageCount: %', messageCount)
    if messageCount > 0:     
        for num in data[0].split():
            typ, data = M.fetch(num, '(BODY[TEXT])')
            foundAt = data[0][1].find('Content-Type: application')
            if(foundAt > 0):
                print('attachmentfound')
                sendMail(data[0][1])


    M.close()
    M.logout()       


def sendMail(raw_message):

    toAddress = ''
    fromAddress = ''
    LOGIN    = ''
    PASSWORD = ''


    server = smtplib.SMTP('', 587)
    server.set_debuglevel(1)
    server.ehlo()
    server.starttls()
    server.login(LOGIN, PASSWORD)
    server.sendmail(fromAddress, toAddress, raw_message)
    server.quit()

def main():
    checkMail()

main()

If you want to use imaplib, why not just fetch the whole message (RFC822)? See this similar SO question:

How to fetch an email body using imaplib in python?

这是抓取...为(BODY [])添加抓取成功了。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM