Sending an email with a binary attachment

Chris Angelico rosuav at gmail.com
Tue Mar 1 03:03:50 EST 2016


On Tue, Mar 1, 2016 at 6:58 PM, Anthony Papillion
<anthony at cajuntechie.org> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA512
>
> On 02/29/2016 11:13 AM, Chris Angelico wrote:
>> On Tue, Mar 1, 2016 at 4:08 AM, Peter Pearson
>> <pkpearson at nowhere.invalid> wrote:
>>> try: smtp.sendmail(message['From'], message['To'],
>>> message.as_string()) except: print "Message sending has failed"
>>> sys.exit(1) print "Message sending was successful" sys.exit(0)
>>>
>>
>> This is the problem, right here. Replace this code with:
>>
>> smtp.sendmail(message['From'], message['To'], message.as_string())
>
> Hmm, I'm a bit confused. Are you saying that the problem is that I'm
> enclosing the code in a Try/Except block? Besides that, I don't see
> anything different. If it's the Try/Except block, how do I catch the
> exception it might generate if I'm not using the exception block?
>

That's exactly the difference. Why do you need to catch the exception?
All you're doing is destroying all the information, rendering it down
to a blunt "has failed".

We've had several threads touching on this, recently. I'm going to say
this in what might be taken as a rude way, but the emphasis is
necessary:

** Folks, *stop catching exceptions* just to print failure messages
and exit. You are shooting yourselves in the foot. **

You should catch exceptions if you can actually handle them, but if
all you're doing is printing out a fixed message and aborting, delete
that code. Less code AND a better result.

ChrisA



More information about the Python-list mailing list