Clear interface for mail class

Benedict Verheyen benedict.verheyen at gmail.com
Wed Oct 14 08:39:41 EDT 2009


Hi,


I'm trying to come up with a decent interface for my email class.
Basically, i have one email function but it has many (too many?) variables:

    send_mail(self, send_from, send_to, send_cc, subject, text, separate_emails = False, files=[], inline_files=[], server="localhost",
charset="iso-8859-1")

I'm thinking on how i could simplify it and make it look nicer and more easy to use.
I can reduce the number of arguments by adding functions for the less common tasks
like adding attachement, inline files and so on.
Then i would end up with functions like this:

def __init__(self):
    """
    """
    self._files=[]
    self._inline_files=[]
...

def add_files(self, files=[]):
    assert type(files)==list
    self._files=files
...

When sending an email, i could check if files where specified and if so, send them too.

But it doesn't feel right to just have a bunch of small functions to set variables.
Calling the function would change from:
 (where m is the mail class)
 m.send_mail( "from_me at work",
              "to_ at work",
              [],
              "Test emailmodule ",
              MSG,
              separate_emails = True,
              files=["attached_pic.png"],
              inline_files=["inline_pic.png"],
              server="mysmtpserver")

to:

m.add_files(["attached_pic.png"])
m.add_inline_files(["inline_pic.png"])
m.smtp_server("mysmtpserver")
m.send_mail( "from_me at work",
             "to_ at work",
             [],
             "Test emailmodule "",
             MSG)

It looks already better and i could set the smtp server as a class variable,
but i'm not sure this will present me with the most natural interface to use.

Or should i make 1 general function that sets vars according to a type?
For instance: add_header("To",[list_of_recipients])

This kind of problems seems to happen sometimes: i need to fix something quickly,
build a script for it, and then i realise that the code i've written is not the best in
terms of reusability and has some "not so great" functions or classes.
Speedy development eh.

Any ideas are welcome.

Thanks,
Benedict




More information about the Python-list mailing list