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