6.01.2014

Python: How to Send an E-mail

Python: Eメールの送信

 

何度も車輪の再発明を繰り返しているが、今のところちょっとしたスクリプトにおいては
以下の内容で落ち着いている。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import ConfigParser
import codecs
import smtplib
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import formatdate

# load config
CONF_PATH = os.path.join(os.path.dirname(__file__), 'mail_sender.conf')

config = ConfigParser.SafeConfigParser()
config.readfp(codecs.open(CONF_PATH, 'r', 'utf-8'))

SMTP_SERVER = config.get('system', 'smtp-server')
SMTP_PORT = config.getint('system', 'smtp-port')


class MailSender(object):
    """General mail sending class"""

    def __init__(self, project_id):
        self.from_addr = config.get(project_id, 'from-address')
        self.to_addr_list = [a.strip() for a in config.get(project_id, 'to-address-list').split(',')]

    def send(self, subject, body, from_addr=None, to_addr_list=None):
        """send a message using SMTP"""

        if from_addr is None:
            from_addr = self.from_addr
        if to_addr_list is None:
            to_addr_list = self.to_addr_list
        msg = MailSender.__create_message(from_addr, to_addr_list, subject, body)

        s = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        s.sendmail(from_addr, to_addr_list, msg.as_string())
        s.close()

    @staticmethod
    def __create_message(from_addr, to_addr_list, subject, body, encoding='iso-2022-jp'):
        """create MIMEText object"""

        msg = MIMEText(body.encode(encoding), 'plain', encoding)
        msg['Subject'] = Header(subject, charset=encoding, header_name='Subject')
        msg['From'] = from_addr
        msg['To'] = ','.join(to_addr_list)
        msg['Date'] = formatdate(localtime=True)
        return msg


if __name__ == '__main__':
    # test code
    #MailSender('awesome-project').send(u'TITLE', u'THIS IS A TEST MAIL!')
    pass

同じ階層に conf ファイルを置く。

[system]
smtp-server: {{ smtp_server }}
smtp-port: {{ smtp_port }}

[awesome-project]
from-address: {{ from_address }}
to-address-list: {{ to_address_list }}

{{ }} の部分は適宜書き換え。to_address_list はカンマ区切りで複数指定可能。

0 件のコメント:

コメントを投稿