Click to See Complete Forum and Search --> : Python - Error Trap on Sending Email


Saugatuckee
02-11-2011, 12:17 PM
I have a Python script that works well on sending email. It runs within a loop in a database process to send a series of email messages. If there's an error in sending any of them, I want to note it and continue running the loop.

My sending ends with:
smtp.sendmail(strFrom, strSend, msgRoot.as_string())
smtp.quit()
except: print "Error: "+strSend

strSend may have a few addresses between brackets, such as ['joe@email.com','hank@another.com']

If there is an error, instead of capturing it I get a Python error:
except: print "Error: "+strSend
TypeError: cannot concatenate 'str' and 'list' objects

Obviously I have a conflict in the format of strSend. How do I correct the formatting?
If anyone knows how to do more detailed error trapping on sending email, I'd love to know about it.

TIA

The full script with variables from the database as ^«lvFrom»^ and $«Subject»$:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
try:
strFrom = ^«lvFrom»^
strTo = ^«lvTo»^
strCC = ^«lvCC»^
strSend = ^«lvSend»^
strError = ""

# Create the root message and fill in the from, to, and subject headers
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = $«Subject»$
msgRoot['From'] = strFrom
msgRoot['Reply-to'] = strFrom
msgRoot['To'] = strTo
msgRoot['Cc'] = strCC
msgRoot.preamble = 'This is a multi-part message in MIME format.'

# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so email agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText($«lvPlain»$)
msgAlternative.attach(msgText)
msgText = MIMEText($«lvHTML»$, 'html')
msgAlternative.attach(msgText)

# ATTACH MULTIPLE IMAGES
if $«unixImagePaths»$ != "":
images = $«unixImagePaths»$.splitlines()
i=1
for image in images:
# print 'Image',i,': ',image,'\n'
fp = open(image, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image'+str(i)+'>')
msgRoot.attach(msgImage)
i+=1

# Send the email
import smtplib
smtp = smtplib.SMTP($«fgSMTP»$, ^«fgPort»^)
try:
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
except:
pass
smtp.login($«fgUser»$, $«fgPassword»$)
smtp.sendmail(strFrom, strSend, msgRoot.as_string())
smtp.quit()
except: print "Error: "+strSend