Dale Curtis | 8adf789 | 2011-09-08 16:13:36 -0700 | [diff] [blame] | 1 | import os, email, smtplib |
mbligh | 929b378 | 2008-03-28 16:01:43 +0000 | [diff] [blame] | 2 | |
| 3 | |
| 4 | def send(from_address, to_addresses, cc_addresses, subject, message_body): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 5 | """ |
| 6 | Send out a plain old text email. It uses sendmail by default, but |
| 7 | if that fails then it falls back to using smtplib. |
mbligh | 929b378 | 2008-03-28 16:01:43 +0000 | [diff] [blame] | 8 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 9 | Args: |
| 10 | from_address: the email address to put in the "From:" field |
| 11 | to_addresses: either a single string or an iterable of |
| 12 | strings to put in the "To:" field of the email |
| 13 | cc_addresses: either a single string of an iterable of |
| 14 | strings to put in the "Cc:" field of the email |
| 15 | subject: the email subject |
| 16 | message_body: the body of the email. there's no special |
| 17 | handling of encoding here, so it's safest to |
| 18 | stick to 7-bit ASCII text |
| 19 | """ |
| 20 | # addresses can be a tuple or a single string, so make them tuples |
| 21 | if isinstance(to_addresses, str): |
| 22 | to_addresses = [to_addresses] |
| 23 | else: |
| 24 | to_addresses = list(to_addresses) |
| 25 | if isinstance(cc_addresses, str): |
| 26 | cc_addresses = [cc_addresses] |
| 27 | else: |
| 28 | cc_addresses = list(cc_addresses) |
mbligh | 929b378 | 2008-03-28 16:01:43 +0000 | [diff] [blame] | 29 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 30 | message = email.Message.Message() |
| 31 | message["To"] = ", ".join(to_addresses) |
| 32 | message["Cc"] = ", ".join(cc_addresses) |
| 33 | message["From"] = from_address |
| 34 | message["Subject"] = subject |
| 35 | message.set_payload(message_body) |
mbligh | 929b378 | 2008-03-28 16:01:43 +0000 | [diff] [blame] | 36 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 37 | server = smtplib.SMTP("localhost") |
| 38 | server.sendmail(from_address, to_addresses + cc_addresses, message.as_string()) |
| 39 | server.quit() |