Reputation: 223
I'm starting to work with Python again and have an issue with how to handle exceptions from arguments in a function. Say someone does not enter a toaddr
or a fromaddr
or subject
or body
. Or they enter a fromaddr
but not a toaddr
. How can I tell if they are putting in a to or from? Say I do:
SendMail('', [email protected], Message, message body)
This works becuase I'm providing all the arugments, but if I leave toaddr
blank I get not enough requirements error.
I don't think I'm explaining this very well :(.
My function is this:
def SendMail(toaddr, fromaddr, subject, body, attach=False):
# create a MIME(Multipurpose Internet Mail Extension)
msg = MIMEMultipart()
# assign toaddr, fromaddr and subject to lists
msg['To'] = toaddr
msg['From'] = fromaddr
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
# attach a file if set to true
if attach == True:
filename = raw_input('fullpath/filename.extension>>> ')
attachment = open(filename, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
# establish connection to smtp server and send mail
try:
print('Sending Mail')
server = smtplib.SMTP('mail.server.com', 25)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
print('Mail Sent!')
except smtplib.SMTPException:
print("Could not send mail")
pass
except smtplib.socket.error:
print("Could not connect to server")
pass
Upvotes: 2
Views: 1767
Reputation: 8215
You have two choices
ValueError
)server.sendmail
function, let it raise the exception, and don't catch it.Either way, there's nothing you can sensibly do to deal with the exception, so simply let it propagate to the caller.
Consider a toy example
def divide(a, b):
return a / b;
Now this can be broken in a number of ways:
So you could check for all those things (assume this only works for int)
def divide(a,b):
if not (isinstance(a,int) and isinstance(b,int)):
raise ValueError("Arguments must both be integers")
if b == 0:
raise ValueError("Attempt to divide by zero")
return a / b
Or you can just leave it as is, and let Python raise the appropriate exception
Upvotes: 3