patternpythonMinor
Sending an email via Outlook
Viewed 0 times
sendingviaoutlookemail
Problem
I have a function which sends an email via outlook when given text, a subject, and recipients shown below:
Now, I know that type comparisons in Python are strongly discouraged, but I can't think of a better way to do this. I want it to send to multiple addresses if
def __Emailer(text, subject, recipient, auto=True):
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
if type(recipient) == type([]):
for name in recipient:
mail.Recipients.Add(name)
else:
mail.To = recipients
mail.Subject = subject
mail.HtmlBody = text
if auto:
mail.send
else:
mail.Display(True)Now, I know that type comparisons in Python are strongly discouraged, but I can't think of a better way to do this. I want it to send to multiple addresses if
recipient is a list using the mail.Recipients.Add(name), and mail.To if there is only one name (not given as a list). How can I accomplish this without using nasty type comparisons?Solution
In Python, it is part of the mentality to check for behavior rather than for exact type.
Your method doesn't even need
One way to check if something is a string is to look for a string-specific method, such as
Your method doesn't even need
recipients to be a list—it can be any iterable (e.g. a set) so it can be used in the for loop. Strings, however, are also iterable, so you need to tell them apart. One way to check if something is a string is to look for a string-specific method, such as
strip.def __Emailer(text, subject, recipients, auto=True):
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
if hasattr(recipients, 'strip'):
recipients = [recipients]
for recipient in recipients:
mail.Recipients.Add(recipient)
mail.Subject = subject
mail.HtmlBody = text
if auto:
mail.send
else:
mail.Display(True)Code Snippets
def __Emailer(text, subject, recipients, auto=True):
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
if hasattr(recipients, 'strip'):
recipients = [recipients]
for recipient in recipients:
mail.Recipients.Add(recipient)
mail.Subject = subject
mail.HtmlBody = text
if auto:
mail.send
else:
mail.Display(True)Context
StackExchange Code Review Q#38776, answer score: 3
Revisions (0)
No revisions yet.