Created
September 20, 2011 15:47
-
-
Save mark-kubacki/1229465 to your computer and use it in GitHub Desktop.
Modul zum Versenden von Emails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import smtplib | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.base import MIMEBase | |
from email.mime.text import MIMEText | |
from email.header import Header | |
from email.Utils import COMMASPACE, formatdate | |
from email import Encoders | |
try: | |
import turbomail | |
has_turbomail = True | |
except: | |
has_turbomail = False | |
__all__ = ['send_email', 'send_advanced_mail'] | |
charsets = ['ascii', 'iso-8859-1', 'utf-8'] | |
def send_email(from_addr, to_addr, subject, text, conn_data = {'host': 'localhost'}): | |
if has_turbomail: | |
msg = turbomail.Message(from_addr, to_addr, subject) | |
msg.plain = text | |
turbomail.enqueue(msg) | |
else: | |
from email.MIMEMultipart import MIMEMultipart | |
from email.MIMEText import MIMEText | |
from email.Utils import formatdate | |
# Email Header | |
msg = MIMEMultipart() | |
msg['From'] = from_addr | |
msg['To'] = to_addr | |
msg['Date'] = formatdate(localtime=True) | |
for charset in charsets: | |
try: | |
msg['Subject'] = Header(subject, charset) | |
break | |
except UnicodeEncodeError: | |
pass | |
# email body (here known as 'text') | |
for charset in charsets: | |
try: | |
text = text.encode(charset) | |
msg.attach(MIMEText(text, _charset=charset)) | |
break | |
except UnicodeEncodeError: | |
pass | |
send_email_smtp(from_addr, to_addr, msg.as_string(), conn_data) | |
def send_email_smtp(from_addr, to_addr, message, conn_data): | |
"""Send email via SMTP.""" | |
smtp = smtplib.SMTP(conn_data['host']) | |
if 'user' in conn_data and 'passwd' in conn_data: | |
smtp.login(conn_data['user'], conn_data['passwd']) | |
# 'message' is the complete and raw email (with headers, body) | |
smtp.sendmail(from_addr, to_addr, message) | |
smtp.close() | |
def send_advanced_mail(to, subject, text, sender='nobody@localhost', files=[], server='localhost'): | |
assert type(to)==list | |
assert type(files)==list | |
msg = MIMEMultipart() | |
msg['From'] = sender | |
msg['To'] = COMMASPACE.join(to) | |
msg['Date'] = formatdate(localtime=True) | |
msg['Subject'] = subject | |
msg.attach( MIMEText(text) ) | |
for file in files: | |
part = MIMEBase('application', 'octet-stream') | |
part.set_payload( open(file, 'rb').read() ) | |
Encoders.encode_base64(part) | |
part.add_header('Content-Disposition', 'attachment; filename="%s"' % file) | |
msg.attach(part) | |
smtp = smtplib.SMTP(server) | |
smtp.sendmail(sender, to, msg.as_string() ) | |
smtp.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment