Python言語 Send email

#!/usr/bin/env python
# encoding: utf-8
#
# filename: sendemail.py
#

import os.path
import smtplib
import email.Header
import email.MIMEMultipart
import email.MIMEText
import email.MIMEBase
import email.Encoders
import mimetypes

class Email:
def __init__(self, **kwg):
self._setting = dict(kwg)

def send(self, msg):
smtp = smtplib.SMTP(
self._setting.get('server’),
self._setting.get('port’, 25)
)
msg[“From"] = self._setting.get('From’)
smtp.sendmail(
msg['From’],
msg['To’].split(',’)+
msg['Cc’].split(',’),
msg.as_string()
)
smtp.quit()

def writemail(coding=’utf-8′, **kwg):
msg = email.MIMEMultipart.MIMEMultipart()
msg[“To"] = kwg.get('To’, 'me@arkgame.com’)
msg[“Cc"] = kwg.get('Cc’, ")
msg['Date’] = email.Utils.formatdate()
msg[“Subject"] = email.Header.Header(
kwg.get('Subject’, 'No Subject’), coding)
msg.attach(email.MIMEText.MIMEText(
kwg.get('Context’).encode(coding),
_charset=coding))
return msg

def attach(msg, file_name):
# MIMEBaseオブジェクトを作成
ctype, encoding = mimetypes.guess_type(file_name)
if ctype is None or encoding is not None:
ctype=’application/octet-stream’
maintype, subtype = ctype.split('/’, 1)

## ファイルの内容と形式を読む
with open(file_name, 'rb’) as data:
file_msg = email.MIMEBase.MIMEBase(maintype, subtype)
file_msg.set_payload(data.read())

##添付ヘッダの設定
basename = os.path.basename(file_name)E
file_msg.add_header('Content-Disposition’,
'attachment’, filename = basename)
email.Encoders.encode_base64(file_msg)
msg.attach(file_msg)
return msg

def _tester():
msg = writemail(
To = 'someone@example.com’,
Subject = u’データ統計’,
Context = u’Please see the attachment.’,
)
attach(msg, u’../rpt/sys_monitor.zip’)
Email(
server = 'smtp.163.com’,
From = 'someone@example.com’
).send(msg)

if __name__ == '__main__’:
_tester()

Source

Posted by arkgame