メール送信ツール -Python-

#!/usr/bin/python
# -*- coding: utf-8 -*-
import smtplib
import os
import argparse
import mimetypes

from email import Encoders
from email.Utils import formatdate
from email.Header import Header
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase  import MIMEBase
from email.MIMEImage import MIMEImage
from email.MIMEAudio import MIMEAudio

parser = argparse.ArgumentParser(description='This is a program to send a mail.')
parser.add_argument('-f', '--from_addr', help='From Address',     required=True)
parser.add_argument('-t', '--to_addr',   help='To Address',       required=True)
parser.add_argument('-s', '--subject',   help='Subject',          required=True)
parser.add_argument('-m', '--mta',       help='SMTP Server',      required=False, default='localhost')
parser.add_argument('-a', '--attach',    help='Attachment Files', required=False, default=[],    action='append')
parser.add_argument('-S', '--spam',      help='Send a SPAM mail', required=False, default=False, action='store_true')
parse = parser.parse_args()

def read_file(f):
    try:
        with open(f, 'r') as fh:
            data = fh.read()
    except:
        print('Error: can not open ' + f)
        exit()
    return data

def set_attach(mp, files):
    for f in files:
        # 添付ファイルデータを読み込む
        data = read_file(f)

        # Content-Typeヘッダに添付ファイルのメディアタイプをセット
        # http://docs.python.jp/2/library/mimetypes.html
        # http://docs.python.jp/2/library/email-examples.html
        ctype, encording = mimetypes.guess_type(f)

        # メディアタイプを判定出来ない場合、以下を設定
        if ctype is None or encording is not None:
            ctype = 'application/octet-stream'

        # タイプとサブタイプ
        mtype, msub = ctype.split('/')
        if mtype == 'text':
             mime = MIMEText(data, _subtype=msub)
        elif mtype == 'image':
             mime = MIMEImage(data, _subtype=msub)
        elif mtype == 'audio':
             mime = MIMEAudio(data, _subtype=msub)
        else:
             mime = MIMEBase(mtype, msub)
             mime.set_payload(data)
             Encoders.encode_base64(mime)

        f = os.path.basename(f)
        mime.add_header('Content-Disposition','attachment', filename=f)
        mp.attach(mime)

    return mp

def create_message(d):
    cs = 'UTF-8'
    body = '''
これはテストメールです。

'''
    if d['spam']:
        body = 'XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X'

    msg = MIMEText(body, 'plain', cs)
    if d['attach']:
        mp = MIMEMultipart()
        mp.attach(msg)
        msg = set_attach(mp, d['attach'])

    msg['Subject'] = Header(d['subject'], cs)
    msg['From'] = d['from']
    msg['To'] = d['to']
    msg['Date'] = formatdate(localtime=True)

    d['msg'] = msg
    return d

def send(d):
    s = smtplib.SMTP(d['mta'])
    s.sendmail(d['from'], [d['to']], d['msg'].as_string())
    s.close()

def get_args():
    d = dict()
    d['from'] = parse.from_addr
    d['to'] = parse.to_addr
    d['subject'] = parse.subject
    d['mta'] = parse.mta
    d['attach'] = parse.attach
    d['spam'] = parse.spam
    return d

def main():
    d = get_args()
    d = create_message(d)
    send(d)

if __name__ == '__main__':
    main()