add a newline at the end of replies
[edward.git] / edward
diff --git a/edward b/edward
index 98590d37f3338f207236a7b8171f3e32ba54fc94..673e4dc74f8ac18414b5a61d1cdebe24458d5653 100755 (executable)
--- a/edward
+++ b/edward
@@ -31,17 +31,20 @@ Code sourced from these projects:
   * http://www.physics.drexel.edu/~wking/code/python/send_pgp_mime
 """
 
-import sys
-import gpgme
 import re
 import io
 import os
+import sys
+import enum
+import gpgme
 import importlib
+import subprocess
 
 import email.parser
 import email.message
 import email.encoders
 
+from email.mime.text            import MIMEText
 from email.mime.multipart       import MIMEMultipart
 from email.mime.application     import MIMEApplication
 from email.mime.nonmultipart    import MIMENonMultipart
@@ -53,14 +56,19 @@ langs = ["de", "el", "en", "fr", "ja", "pt-br", "ro", "ru", "tr"]
 """This list contains the abbreviated names of reply languages available to
 edward."""
 
+class TxtType (enum.Enum):
+    text        = 0
+    message     = 1
+    pubkey      = 2
+    detachedsig = 3
+    signature   = 4
 
-match_types =  [('clearsign',
-                '-----BEGIN PGP SIGNED MESSAGE-----.*?-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----'),
-                ('message',
+
+match_pairs =  [(TxtType.message,
                 '-----BEGIN PGP MESSAGE-----.*?-----END PGP MESSAGE-----'),
-                ('pubkey',
+                (TxtType.pubkey,
                 '-----BEGIN PGP PUBLIC KEY BLOCK-----.*?-----END PGP PUBLIC KEY BLOCK-----'),
-                ('detachedsig',
+                (TxtType.detachedsig,
                 '-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----')]
 
 """This list of tuples matches query names with re.search() queries used
@@ -78,14 +86,12 @@ class EddyMsg (object):
     'subparts' points to a list of mime sub-parts if it is a multi-part
     message. Otherwise it points to an empty list.
 
-    'payload_bytes' contains the raw mime-decoded bytes that haven't been
-    encoded into a character set.
+    'payload_bytes' is a binary representation of the mime part before header
+    removal and message decoding.
 
     'payload_pieces' is a list of objects containing strings that when strung
     together form the fully-decoded string representation of the mime part.
 
-    The 'charset' describes the character set of payload_bytes.
-
     The 'filename', 'content_type' and 'description_list' come from the mime
     part parameters.
     """
@@ -96,7 +102,6 @@ class EddyMsg (object):
     payload_bytes           = None
     payload_pieces          = []
 
-    charset                 = None
     filename                = None
     content_type            = None
     description_list        = None
@@ -109,11 +114,11 @@ class PayloadPiece (object):
     Instances of this class are often strung together within one or more arrays
     pointed to by each instance of the EddyMsg class.
 
-    'piece_type' refers to a string whose value describes the content of
-    'string'.  Examples include "pubkey", for public keys, and "message", for
-    encrypted data (or armored signatures until they are known to be such.) The
-    names derive from the header and footer of each of these ascii-encoded gpg
-    blocks.
+    'piece_type' refers to an enum whose value describes the content of
+    'string'.  Examples include TxtType.pubkey, for public keys, and
+    TxtType.message, for encrypted data (or armored signatures until they are
+    known to be such.) Some of the names derive from the header and footer of
+    each of these ascii-encoded gpg blocks.
 
     'string' contains some string of text, such as non-GPG text, an encrypted
     block of text, a signature, or a public key.
@@ -237,7 +242,7 @@ def main ():
         implied by the To: address in the original email.
     """
 
-    handle_args()
+    print_reply_only = handle_args()
 
     gpgme_ctx = get_gpg_context(edward_config.gnupghome,
                               edward_config.sign_with_key)
@@ -246,7 +251,7 @@ def main ():
     email_struct = parse_pgp_mime(email_text, gpgme_ctx)
 
     email_to, email_from, email_subject = email_to_from_subject(email_text)
-    lang = import_lang(email_to)
+    lang, reply_from = import_lang_pick_address(email_to, edward_config.hostname)
 
     replyinfo_obj = ReplyInfo()
     replyinfo_obj.replies = lang.replies
@@ -259,7 +264,10 @@ def main ():
                                          email_subject, encrypt_to_key,
                                          gpgme_ctx)
 
-    print(reply_mime)
+    if print_reply_only == True:
+        print(reply_mime)
+    else:
+        send_reply(reply_mime, email_subject, email_from, reply_from)
 
 
 def get_gpg_context (gnupghome, sign_with_key_fp):
@@ -287,7 +295,7 @@ def get_gpg_context (gnupghome, sign_with_key_fp):
 
     try:
         sign_with_key = gpgme_ctx.get_key(sign_with_key_fp)
-    except:
+    except gpgme.GpgmeError:
         error("unable to load signing key. is the gnupghome "
                 + "and signing key properly set in the edward_config.py?")
         exit(1)
@@ -354,7 +362,7 @@ def parse_mime(msg_struct):
     return eddymsg_obj
 
 
-def scan_and_split (payload_piece, match_type, pattern):
+def scan_and_split (payload_piece, match_name, pattern):
     """This splits the payloads of an EddyMsg object into GPG and text parts.
 
     An EddyMsg object's payload_pieces starts off as a list containing a single
@@ -364,7 +372,7 @@ def scan_and_split (payload_piece, match_type, pattern):
 
     Args:
         payload_piece: a single payload or a split part of a payload
-        match_type: the type of data to try to spit out from the payload piece
+        match_name: the type of data to try to spit out from the payload piece
         pattern: the search pattern to be used for finding that type of data
 
     Returns:
@@ -374,7 +382,7 @@ def scan_and_split (payload_piece, match_type, pattern):
     """
 
     # don't try to re-split pieces containing gpg data
-    if payload_piece.piece_type != "text":
+    if payload_piece.piece_type != TxtType.text:
         return [payload_piece]
 
     flags = re.DOTALL | re.MULTILINE
@@ -392,13 +400,13 @@ def scan_and_split (payload_piece, match_type, pattern):
 
         match                   = PayloadPiece()
         match.string            = matches.group('match')
-        match.piece_type        = match_type
+        match.piece_type        = match_name
 
         rest                    = PayloadPiece()
         rest.string             = matches.group('rest')
         rest.piece_type         = payload_piece.piece_type
 
-        more_pieces = scan_and_split(rest, match_type, pattern)
+        more_pieces = scan_and_split(rest, match_name, pattern)
         pieces = [beginning, match ] + more_pieces
 
     return pieces
@@ -417,24 +425,25 @@ def get_subpart_data (part):
         a single-part EddyMsg() object
     """
 
-    obj = EddyMsg()
+    charset                 = part.get_content_charset()
+    mime_decoded_bytes      = part.get_payload(decode=True)
 
-    obj.charset             = part.get_content_charset()
-    obj.payload_bytes       = part.get_payload(decode=True)
+    obj = EddyMsg()
+    obj.payload_bytes       = part.as_bytes()
 
     obj.filename            = part.get_filename()
     obj.content_type        = part.get_content_type()
     obj.description_list    = part['content-description']
 
     # your guess is as good as a-myy-ee-ine...
-    if obj.charset == None:
-        obj.charset = 'utf-8'
+    if charset == None:
+        charset = 'utf-8'
 
-    if obj.payload_bytes != None:
+    if mime_decoded_bytes != None:
         try:
             payload = PayloadPiece()
-            payload.string = obj.payload_bytes.decode(obj.charset)
-            payload.piece_type = 'text'
+            payload.string = mime_decoded_bytes.decode(charset)
+            payload.piece_type = TxtType.text
 
             obj.payload_pieces = [payload]
         except UnicodeDecodeError:
@@ -491,11 +500,11 @@ def split_payloads (eddymsg_obj):
         The EddyMsg object's payloads are all split into GPG and non-GPG parts.
     """
 
-    for match_type in match_types:
-        do_to_eddys_pieces(split_payload_pieces, eddymsg_obj, match_type)
+    for match_pair in match_pairs:
+        do_to_eddys_pieces(split_payload_pieces, eddymsg_obj, match_pair)
 
 
-def split_payload_pieces (eddymsg_obj, match_type):
+def split_payload_pieces (eddymsg_obj, match_pair):
     """A helper function for split_payloads(); works on PayloadPiece objects.
 
     This function splits up PayloadPiece objects into multipe PayloadPiece
@@ -504,7 +513,7 @@ def split_payload_pieces (eddymsg_obj, match_type):
 
     Args:
         eddymsg_obj: a single-part EddyMsg object.
-        match_type: a tuple from the match_types list, which specifies a match
+        match_pair: a tuple from the match_pairs list, which specifies a match
             name and a match pattern.
 
     Returns:
@@ -516,10 +525,10 @@ def split_payload_pieces (eddymsg_obj, match_type):
 
     Post:
         The EddyMsg object's payload piece(s) are split into a list of pieces
-        if matches of the match_type are found.
+        if matches of the match_pair are found.
     """
 
-    (match_name, pattern) = match_type
+    (match_name, pattern) = match_pair
 
     new_pieces_list = []
     for piece in eddymsg_obj.payload_pieces:
@@ -566,11 +575,11 @@ def gpg_on_payloads (eddymsg_obj, gpgme_ctx, prev_parts=[]):
 
     for piece in eddymsg_obj.payload_pieces:
 
-        if piece.piece_type == "text":
+        if piece.piece_type == TxtType.text:
             # don't transform the plaintext.
             pass
 
-        elif piece.piece_type == "message":
+        elif piece.piece_type == TxtType.message:
             (plaintext, sigs) = decrypt_block(piece.string, gpgme_ctx)
 
             if plaintext:
@@ -585,31 +594,24 @@ def gpg_on_payloads (eddymsg_obj, gpgme_ctx, prev_parts=[]):
             (plaintext, sigs) = verify_sig_message(piece.string, gpgme_ctx)
 
             if plaintext:
-                piece.piece_type = "signature"
+                piece.piece_type = TxtType.signature
                 piece.gpg_data = GPGData()
                 piece.gpg_data.sigs = sigs
                 # recurse!
                 piece.gpg_data.plainobj = parse_pgp_mime(plaintext, gpgme_ctx)
 
-        elif piece.piece_type == "pubkey":
+        # FIXME: consider handling pubkeys first, so that signatures can be
+        # validated on freshly imported keys
+        elif piece.piece_type == TxtType.pubkey:
             key_fps = add_gpg_key(piece.string, gpgme_ctx)
 
             if key_fps != []:
                 piece.gpg_data = GPGData()
                 piece.gpg_data.keys = key_fps
 
-        elif piece.piece_type == "clearsign":
-            (plaintext, sig_fps) = verify_clear_signature(piece.string, gpgme_ctx)
-
-            if sig_fps != []:
-                piece.gpg_data = GPGData()
-                piece.gpg_data.sigs = sig_fps
-                piece.gpg_data.plainobj = parse_pgp_mime(plaintext, gpgme_ctx)
-
-        elif piece.piece_type == "detachedsig":
+        elif piece.piece_type == TxtType.detachedsig:
             for prev in prev_parts:
-                payload_bytes = prev.payload_bytes
-                sig_fps = verify_detached_signature(piece.string, payload_bytes, gpgme_ctx)
+                sig_fps = verify_detached_signature(piece.string, prev.payload_bytes, gpgme_ctx)
 
                 if sig_fps != []:
                     piece.gpg_data = GPGData()
@@ -670,19 +672,18 @@ def prepare_for_reply_pieces (eddymsg_obj, replyinfo_obj):
     """
 
     for piece in eddymsg_obj.payload_pieces:
-        if piece.piece_type == "text":
+        if piece.piece_type == TxtType.text:
             # don't quote the plaintext part.
             pass
 
-        elif piece.piece_type == "message":
+        elif piece.piece_type == TxtType.message:
             prepare_for_reply_message(piece, replyinfo_obj)
 
-        elif piece.piece_type == "pubkey":
+        elif piece.piece_type == TxtType.pubkey:
             prepare_for_reply_pubkey(piece, replyinfo_obj)
 
-        elif (piece.piece_type == "clearsign") \
-            or (piece.piece_type == "detachedsig") \
-            or (piece.piece_type == "signature"):
+        elif (piece.piece_type == TxtType.detachedsig) \
+            or (piece.piece_type == TxtType.signature):
                     prepare_for_reply_sig(piece, replyinfo_obj)
 
 
@@ -690,7 +691,7 @@ def prepare_for_reply_message (piece, replyinfo_obj):
     """Helper function for prepare_for_reply()
 
     This function is called when the piece_type of a payload piece is
-    "message", or GPG Message block. This should be encrypted text. If the
+    TxtType.message, or GPG Message block. This should be encrypted text. If the
     encryted block is signed, a sig will be attached to .target_key unless
     there is already one there.
 
@@ -703,7 +704,7 @@ def prepare_for_reply_message (piece, replyinfo_obj):
         Nothing
 
     Pre:
-        the piece.payload_piece value should be "message".
+        the piece.payload_piece value should be TxtType.message.
 
     Post:
         replyinfo_obj gets updated with decryption status, signing status and a
@@ -727,7 +728,7 @@ def prepare_for_reply_message (piece, replyinfo_obj):
         # only include a signed message in the reply.
         get_signed_part = True
 
-    replyinfo_obj.msg_to_quote = flatten_decrypted_payloads(piece.gpg_data.plainobj, get_signed_part)
+    flatten_decrypted_payloads(piece.gpg_data.plainobj, replyinfo_obj, get_signed_part)
 
     # to catch public keys in encrypted blocks
     prepare_for_reply(piece.gpg_data.plainobj, replyinfo_obj)
@@ -743,7 +744,7 @@ def prepare_for_reply_pubkey (piece, replyinfo_obj):
         replyinfo_obj: a ReplyInfo object
 
     Pre:
-        piece.piece_type should be set to "pubkey".
+        piece.piece_type should be set to TxtType.pubkey .
 
     Post:
         replyinfo_obj has its fields updated.
@@ -754,8 +755,8 @@ def prepare_for_reply_pubkey (piece, replyinfo_obj):
     else:
         replyinfo_obj.public_key_received = True
 
-        if replyinfo_obj.fallback_target_key == None:
-            replyinfo_obj.fallback_target_key = piece.gpg_data.keys[0]
+        # prefer public key as a fallback for the encrypted reply
+        replyinfo_obj.fallback_target_key = piece.gpg_data.keys[0]
 
 
 def prepare_for_reply_sig (piece, replyinfo_obj):
@@ -768,8 +769,8 @@ def prepare_for_reply_sig (piece, replyinfo_obj):
         replyinfo_obj: a ReplyInfo object
 
     Pre:
-        piece.piece_type should be set to "clearsign", "signature", or
-        "detachedsig".
+        piece.piece_type should be set to TxtType.signature, or
+        TxtType.detachedsig .
 
     Post:
         replyinfo_obj has its fields updated.
@@ -784,54 +785,56 @@ def prepare_for_reply_sig (piece, replyinfo_obj):
             replyinfo_obj.fallback_target_key = piece.gpg_data.sigs[0]
 
 
+def flatten_decrypted_payloads (eddymsg_obj, replyinfo_obj, get_signed_part):
+    """For creating a string representation of a signed, encrypted part.
 
-def flatten_decrypted_payloads (eddymsg_obj, get_signed_part):
-    """Returns a string representation of a signed, encrypted part.
-
-    Returns the string representation of the first signed/encrypted or signed
-    then encrypted block of text. (Signature inside of Encryption)
+    When given a decrypted payload, it will add either the plaintext or signed
+    plaintext to the reply message, depeding on 'get_signed_part'. This is
+    useful for ensuring that the reply message only comes from a signed and
+    ecrypted GPG message. It also sets the target_key for encrypting the reply
+    if it's told to get signed text only.
 
     Args:
         eddymsg_obj: the message in EddyMsg format created by decrypting GPG
             text
+        replyinfo_obj: a ReplyInfo object for holding the message to quote and
+            the target_key to encrypt to.
         get_signed_part: True if we should only include text that contains a
             further signature. If False, then include plain text.
 
     Returns:
-        A string representation of encrypted and signed text.
+        Nothing
 
     Pre:
         The EddyMsg instance passed in should be a piece.gpg_data.plainobj
         which represents decrypted text. It may or may not be signed on that
         level.
-    """
 
-    flat_string = ""
+    Post:
+        the ReplyInfo instance may have a new 'target_key' set and its
+        'msg_to_quote' will be updated with (possibly signed) plaintext, if any
+        could be found.
+    """
 
     if eddymsg_obj == None:
-        return ""
+        return
 
     # recurse on multi-part mime
     if eddymsg_obj.multipart == True:
         for sub in eddymsg_obj.subparts:
-            flat_string += flatten_decrypted_payloads (sub, get_signed_part)
-
-        return flat_string
+            flatten_decrypted_payloads(sub, replyinfo_obj, get_signed_part)
 
     for piece in eddymsg_obj.payload_pieces:
         if (get_signed_part):
-            if ((piece.piece_type == "clearsign") \
-                    or (piece.piece_type == "detachedsig") \
-                    or (piece.piece_type == "signature")) \
+            if ((piece.piece_type == TxtType.detachedsig) \
+                    or (piece.piece_type == TxtType.signature)) \
                     and (piece.gpg_data != None):
-                        # FIXME: the key used to sign this message needs to be the one that is used for the encrypted reply.
-                        flat_string += flatten_decrypted_payloads (piece.gpg_data.plainobj, False)
+                        flatten_decrypted_payloads(piece.gpg_data.plainobj, replyinfo_obj, False)
+                        replyinfo_obj.target_key = piece.gpg_data.sigs[0]
                         break
         else:
-            if piece.piece_type == "text":
-                flat_string += piece.string
-
-    return flat_string
+            if piece.piece_type == TxtType.text:
+                replyinfo_obj.msg_to_quote += piece.string
 
 
 def get_key_from_fp (replyinfo_obj, gpgme_ctx):
@@ -866,7 +869,7 @@ def get_key_from_fp (replyinfo_obj, gpgme_ctx):
             encrypt_to_key = gpgme_ctx.get_key(replyinfo_obj.target_key)
             return encrypt_to_key
 
-        except:
+        except gpgme.GpgmeError:
             pass
 
     # no available key to use
@@ -930,6 +933,7 @@ def write_reply (replyinfo_obj):
 
     reply_plain += "\n\n"
     reply_plain += replyinfo_obj.replies['signature']
+    reply_plain += "\n"
 
     return reply_plain
 
@@ -950,8 +954,11 @@ def add_gpg_key (key_block, gpgme_ctx):
 
     fp = io.BytesIO(key_block.encode('ascii'))
 
-    result = gpgme_ctx.import_(fp)
-    imports = result.imports
+    try:
+        result = gpgme_ctx.import_(fp)
+        imports = result.imports
+    except gpgme.GpgmeError:
+        imports = []
 
     key_fingerprints = []
 
@@ -989,7 +996,7 @@ def verify_sig_message (msg_block, gpgme_ctx):
 
     try:
         sigs = gpgme_ctx.verify(block_b, None, plain_b)
-    except:
+    except gpgme.GpgmeError:
         return ("",[])
 
     plaintext = plain_b.getvalue().decode('utf-8')
@@ -1000,39 +1007,6 @@ def verify_sig_message (msg_block, gpgme_ctx):
     return (plaintext, fingerprints)
 
 
-def verify_clear_signature (sig_block, gpgme_ctx):
-    """Verifies the signature of a clear signature.
-
-    It first encodes the string into utf-8, but this will need to be fixed in
-    order to support other character encodings.
-
-    Args:
-        sig_block: a string of clear-signed text.
-        gpgme_ctx: the gpgme context
-
-    Returns:
-        A tuple of the plaintext of the signed part and the list of
-        fingerprints of keys signing the data. If verification failed, then
-        empty results are returned.
-    """
-
-    # FIXME: this might require the un-decoded bytes
-    # or the correct re-encoding with the carset of the mime part.
-    msg_fp = io.BytesIO(sig_block.encode('utf-8'))
-    ptxt_fp = io.BytesIO()
-
-    result = gpgme_ctx.verify(msg_fp, None, ptxt_fp)
-
-    # FIXME: this might require using the charset of the mime part.
-    plaintext = ptxt_fp.getvalue().decode('utf-8')
-
-    sig_fingerprints = []
-    for res_ in result:
-        sig_fingerprints += [res_.fpr]
-
-    return plaintext, sig_fingerprints
-
-
 def verify_detached_signature (detached_sig, plaintext_bytes, gpgme_ctx):
     """Verifies the signature of a detached signature.
 
@@ -1050,9 +1024,11 @@ def verify_detached_signature (detached_sig, plaintext_bytes, gpgme_ctx):
 
     detached_sig_fp = io.BytesIO(detached_sig.encode('ascii'))
     plaintext_fp = io.BytesIO(plaintext_bytes)
-    ptxt_fp = io.BytesIO()
 
-    result = gpgme_ctx.verify(detached_sig_fp, plaintext_fp, None)
+    try:
+        result = gpgme_ctx.verify(detached_sig_fp, plaintext_fp, None)
+    except gpgme.GpgmeError:
+        return []
 
     sig_fingerprints = []
     for res_ in result:
@@ -1080,7 +1056,7 @@ def decrypt_block (msg_block, gpgme_ctx):
 
     try:
         sigs = gpgme_ctx.decrypt_verify(block_b, plain_b)
-    except:
+    except gpgme.GpgmeError:
         return ("",[])
 
     plaintext = plain_b.getvalue().decode('utf-8')
@@ -1091,24 +1067,17 @@ def decrypt_block (msg_block, gpgme_ctx):
     return (plaintext, fingerprints)
 
 
-def choose_reply_encryption_key (gpgme_ctx, fingerprints):
-
-    reply_key = None
-    for fp in fingerprints:
-        try:
-            key = gpgme_ctx.get_key(fp)
-
-            if (key.can_encrypt == True):
-                reply_key = key
-                break
-        except:
-            continue
-
+def email_to_from_subject (email_text):
+    """Returns the values of the email's To:, From: and Subject: fields
 
-    return reply_key
+    Returns this information from an email.
 
+    Args:
+        email_text: the string form of the email
 
-def email_to_from_subject (email_text):
+    Returns:
+        the email To:, From:, and Subject: fields as strings
+    """
 
     email_struct = email.parser.Parser().parsestr(email_text)
 
@@ -1119,34 +1088,74 @@ def email_to_from_subject (email_text):
     return email_to, email_from, email_subject
 
 
-def import_lang(email_to):
+def import_lang_pick_address(email_to, hostname):
+    """Imports language file for i18n support; makes reply from address
+
+    The language imported depends on the To: address of the email received by
+    edward. an -en ending implies the English language, whereas a -ja ending
+    implies Japanese. The list of supported languages is listed in the 'langs'
+    list at the beginning of the program. This function also chooses the
+    language-dependent address which can be used as the From address in the
+    reply email.
+
+    Args:
+        email_to: the string containing the email address that the mail was
+            sent to.
+        hostname: the hostname part of the reply email's from address
+
+    Returns:
+        the reference to the imported language module. The only variable in
+        this file is the 'replies' dictionary.
+    """
+
+    # default
+    use_lang = "en"
 
     if email_to != None:
         for lang in langs:
             if "edward-" + lang in email_to:
-                lang = "lang." + re.sub('-', '_', lang)
-                language = importlib.import_module(lang)
+                use_lang = lang
+                break
 
-                return language
+    lang_mod_name = "lang." + re.sub('-', '_', use_lang)
+    lang_module = importlib.import_module(lang_mod_name)
 
-    return importlib.import_module("lang.en")
+    reply_from = "edward-" + use_lang + "@" + hostname
 
+    return lang_module, reply_from
 
-def generate_encrypted_mime (plaintext, email_from, email_subject, encrypt_to_key,
+
+def generate_encrypted_mime (plaintext, email_to, email_subject, encrypt_to_key,
                     gpgme_ctx):
+    """This function creates the mime email reply. It can encrypt the email.
+
+    If the encrypt_key is included, then the email is encrypted and signed.
+    Otherwise it is unencrypted.
 
-    # quoted printable encoding lets most ascii characters look normal
-    # before the mime message is decoded.
-    char_set = email.charset.Charset("utf-8")
-    char_set.body_encoding = email.charset.QP
+    Args:
+        plaintext: the plaintext body of the message to create.
+        email_to: the email address to reply to
+        email_subject: the subject to use in reply
+        encrypt_to_key: the key object to use for encrypting the email. (or
+            None)
+        gpgme_ctx: the gpgme context
 
-    # MIMEText doesn't allow setting the text encoding
-    # so we use MIMENonMultipart.
-    plaintext_mime = MIMENonMultipart('text', 'plain')
-    plaintext_mime.set_payload(plaintext, charset=char_set)
+    Returns
+        A string version of the mime message, possibly encrypted and signed.
+    """
 
     if (encrypt_to_key != None):
 
+        # quoted printable encoding lets most ascii characters look normal
+        # before the mime message is decoded.
+        char_set = email.charset.Charset("utf-8")
+        char_set.body_encoding = email.charset.QP
+
+        # MIMEText doesn't allow setting the text encoding
+        # so we use MIMENonMultipart.
+        plaintext_mime = MIMENonMultipart('text', 'plain')
+        plaintext_mime.set_payload(plaintext, charset=char_set)
+
         encrypted_text = encrypt_sign_message(plaintext_mime.as_string(),
                                               encrypt_to_key,
                                               gpgme_ctx)
@@ -1170,9 +1179,9 @@ def generate_encrypted_mime (plaintext, email_from, email_subject, encrypt_to_ke
         message_mime['Content-Disposition'] = 'inline'
 
     else:
-        message_mime = plaintext_mime
+        message_mime = MIMEText(plaintext)
 
-    message_mime['To'] = email_from
+    message_mime['To'] = email_to
     message_mime['Subject'] = email_subject
 
     reply = message_mime.as_string()
@@ -1180,7 +1189,32 @@ def generate_encrypted_mime (plaintext, email_from, email_subject, encrypt_to_ke
     return reply
 
 
+def send_reply(email_txt, subject, reply_to, reply_from):
+
+    email_bytes = email_txt.encode('ascii')
+
+    p = subprocess.Popen(["/usr/sbin/sendmail", "-f", reply_from, "-F", "Edward, GPG Bot", "-i", reply_to], stdin=subprocess.PIPE)
+
+    (stdout, stderr) = p.communicate(email_bytes)
+
+    if stdout != None:
+        debug("sendmail stdout: " + str(stdout))
+    if stderr != None:
+        error("sendmail stderr: " + str(stderr))
+
+
 def email_quote_text (text):
+    """Quotes input text by inserting "> "s
+
+    This is useful for quoting a text for the reply message. It inserts "> "
+    strings at the beginning of lines.
+
+    Args:
+        text: plain text to quote
+
+    Returns:
+        Quoted text
+    """
 
     quoted_message = re.sub(r'^', r'> ', text, flags=re.MULTILINE)
 
@@ -1188,7 +1222,20 @@ def email_quote_text (text):
 
 
 def encrypt_sign_message (plaintext, encrypt_to_key, gpgme_ctx):
+    """Encrypts and signs plaintext
+
+    This encrypts and signs a message.
 
+    Args:
+        plaintext: text to sign and ecrypt
+        encrypt_to_key: the key object to encrypt to
+        gpgme_ctx: the gpgme context
+
+    Returns:
+        An encrypted and signed string of text
+    """
+
+    # the plaintext should be mime encoded in an ascii-compatible form
     plaintext_bytes = io.BytesIO(plaintext.encode('ascii'))
     encrypted_bytes = io.BytesIO()
 
@@ -1200,28 +1247,81 @@ def encrypt_sign_message (plaintext, encrypt_to_key, gpgme_ctx):
 
 
 def error (error_msg):
+    """Write an error message to stdout
+
+    The error message includes the program name.
+
+    Args:
+        error_msg: the message to print
+
+    Returns:
+        Nothing
+
+    Post:
+        An error message is printed to stdout
+    """
 
     sys.stderr.write(progname + ": " + str(error_msg) + "\n")
 
 
 def debug (debug_msg):
+    """Writes a debug message to stdout if debug == True
+
+    If the debug option is set in edward_config.py, then the passed message
+    gets printed to stdout.
+
+    Args:
+        debug_msg: the message to print to stdout
+
+    Returns:
+        Nothing
+
+    Post:
+        A debug message is printed to stdout
+    """
 
     if edward_config.debug == True:
         error(debug_msg)
 
 
 def handle_args ():
+    """Sets the progname variable and processes optional argument
+
+    If there are more than two arguments then edward complains and quits. An
+    single "-p" argument sets the print_reply_only option, which makes edward
+    print email replies instead of mailing them.
+
+    Args:
+        None
+
+    Returns:
+        True if edward should print arguments instead of mailing them,
+        otherwise it returns False.
+
+    Post:
+        Exits with error 1 if there are more than two arguments, otherwise
+        returns the print_reply_only option.
+    """
 
     global progname
     progname = sys.argv[0]
 
-    if len(sys.argv) > 1:
-        print(progname + ": error, this program doesn't " \
-                "need any arguments.", file=sys.stderr)
+    print_reply_only = False
+
+    if len(sys.argv) > 2:
+        print(progname + " usage:  " + progname + " [-p]\n\n" \
+                + "        -p      print reply message to stdout, do not mail it\n", \
+                file=sys.stderr)
         exit(1)
 
+    elif (len(sys.argv) == 2) and (sys.argv[1] == "-p"):
+        print_reply_only = True
+
+    return print_reply_only
+
 
 if __name__ == "__main__":
+    """Executes main if this file is not loaded interactively"""
 
     main()