Reputation: 9165
The following code results in a
htmlbody,emailaddress = ConnEmailParser()
TypeError: 'NoneType' object is not iterable
Error but works fine in IDE. Emails are being sent and PDF files generated. But from command line just ConnEmailParser()
is working.
What can I do, that the program runs smoothly?
Here the code snipped:
import imaplib
import email
import quopri
from cStringIO import StringIO
import ho.pisa as pisa
from datetime import datetime
import logging
import smtplib
from email.generator import Generator
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import formatdate
from email import Encoders
def sendPdfSurvey():
def ConnEmailParser():
try:
saver = StringIO()
SERVER = "server"
USER = "user"
PASSWORD = "nono"
subject="a certain phrase"
imap4 = imaplib.IMAP4(SERVER)
imap4.login(USER, PASSWORD)
imap4.select()
imap4.search(None, 'ALL')
typ, data = imap4.search(None,'(UNSEEN SUBJECT "%s")' % subject) #looking for phrase
count = 0
for num in data[0].split():
count = count + 1 # this is stupid but it gets just oone messsage
if count ==1 :
typ, data = imap4.fetch(num,'(RFC822)')
email7 = email.message_from_string(data[0][1])
varSubject = email7['subject']
# The phase from above has an emailaddress in the subject field
emailaddressraw = varSubject[13:]
emailaddressmedium = emailaddressraw.replace("<","")
emailaddress= emailaddressmedium.replace(">","")
msg = email.message_from_string(data[0][1])
typ, data = imap4.store(num,'+FLAGS','\Seen')
a=str(msg)
i= a.decode('quopri').decode('utf-8')
saver.write(i)
savercontent = saver.getvalue()
# body of the email is html and all of the header elements get deleted
planhtml = savercontent.split('<html xmlns="http://www.w3.org/1999/xhtml">')[1].strip()
return planhtml, emailaddress.strip()
saver.close()
imap4.close()
imap4.logout()
except:
"could not get participant email!"
#here somewhere is the trouble maker
htmlbody,emailaddress = ConnEmailParser()
filenamePDF= "UmfrageEthics_%s.pdf" % datetime.utcnow().strftime('%m%d%H%M%S%f')
def printPdf():
try:
html = htmlbody
result = StringIO()
pdf = pisa.pisaDocument(StringIO(html.encode("UTF-8")), result, encoding='UTF-8')
filetoparse=open(filenamePDF,"wb")
filetoparse.write(result.getvalue())
filetoparse.close()
#pisa.startViewer(filenamePDF)
except:
print "could not write PDF"
def sendPdfParticipant():
try:
oNachricht = MIMEMultipart()
oNachricht['From'] = '[email protected]'
oNachricht['To'] = emailaddress
oNachricht['Date'] = formatdate(localtime= True)
oNachricht['Subject'] = 'A subject'
oAnhang = MIMEBase('application','octet-stream')
oAnhang.set_payload(open(filenamePDF,'rb').read())
Encoders.encode_base64(oAnhang)
oAnhang.add_header('Content-Disposition', 'attachment;filename = some.pdf')
message_text_plain = u'Some message...'
oNachricht.attach(MIMEText(message_text_plain.encode('utf-8'), 'plain', 'UTF-8'))
io = StringIO()
g = Generator(io, False)
g.flatten(oNachricht)
oNachricht.attach(oAnhang)
user = 'user'
pwd = 'pwd'
smtpserver = smtplib.SMTP("smtp.raumopol.de",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(user, pwd)
smtpserver.sendmail('[email protected]',emailaddress,oNachricht.as_string())
smtpserver.quit()
except:
print"could no send data"
sendPdfSurvey()
Upvotes: 1
Views: 160
Reputation: 21175
In def ConnEmailParser()
, check if data
is None
before calling data[0].split()
.
If it is None
, check if imap4
is correctly initiated and if login worked. If that is the case, post a reduced part of your code pinpointing on where it actually goes wrong.
As @Jim Garrison pointed out, a traceback would help us (and you) a lot. This is how:
import traceback
try:
some_code...
except TypeError:
traceback.print_exc()
edit (based on your comment)
When you encode a unicode string, you are replacing characters that are not part of ASCII with codes as '\xfc'. Apparently, saver.write() tries to encode your already encoded text, after first interpreting it as unicode (you got u'\xfc'
). So don't encode yourself. If it still goes wrong, see how you can change the encoding (e.g. 'utf-8', 'cp1252'). Get the current encoding of your OS with
import locale
encoding=locale.getlocale()[1]
Upvotes: 1