3

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()
Rob
  • 33
  • 1
  • 3
  • You might want to check out [IMAPClient](http://imapclient.freshfoo.com/) (alleviates a lot of the frustrations of using imaplib) – Acorn Apr 06 '11 at 20:38

2 Answers2

0

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?

Community
  • 1
  • 1
AJ.
  • 27,586
  • 18
  • 84
  • 94
0

It was the fetch... adding a fetch for (BODY[]) did the trick.

Rob
  • 33
  • 1
  • 3