Browse Source

Add staticmethod for sending mails via MTA on Toollabs

master
Jonathan Golder 8 years ago
parent
commit
0d38bbbfff
  1. 67
      jogobot.py

67
jogobot.py

@ -23,6 +23,8 @@
#
import os
from email.mime.text import MIMEText
from subprocess import Popen, PIPE, TimeoutExpired
import pywikibot
@ -132,3 +134,68 @@ class JogoBot:
# Try to create file
with open(disable_file, 'a'):
pass
@staticmethod
def sendmail( Subject, Body, To=None, CC=None, BCC=None,
From="JogoBot <tools.jogobot@tools.wmflabs.org>" ):
"""
Provides a simple wrapper for exim (MTA) on tool labs
Params should be formated according related fields in RFC 5322
@param subject Mail subject
@type subject str
@param body Mail body as (formated) string
@type body unicode-str
@param to Mail-Recipiends (comma-separeded)
@type str
@param from Mail-Sender
@type str
"""
# Create mail body as MIME-Object
msg = MIMEText(Body)
# Set up mail header
msg['Subject'] = Subject
msg['From'] = From
if To:
msg['To'] = To
if CC:
msg['CC'] = CC
if BCC:
msg['BCC'] = BCC
msg['Content-Type'] = 'text/plain; charset=utf-8'
# Make sure we have a recipient
if not( To or CC or BCC):
raise JogoBotMailError( "No recipient was provided!" )
# Send the message via exim
with Popen( ["/usr/sbin/exim", "-odf", "-i", "-t"],
stdin=PIPE, universal_newlines=True) as MTA:
MTA.communicate(msg.as_string())
# Try to get returncode of MTA
# Process is not terminated until timeout, set returncode to None
try:
returncode = MTA.wait(timeout=30)
except TimeoutExpired:
returncode = None
# Catch MTA errors
if returncode:
raise JogoBotMailError( "/usr/sbin/exim terminated with " +
"returncode != 0. Returncode was " +
str( returncode ) )
class JogoBotMailError( Exception ):
"""
Handles errors occuring in class JogoBot related to mail actions
"""
pass

Loading…
Cancel
Save