pythonで添付付メール送信

ググれば簡単にサンプルは入手できるけど、僕の環境では小さいエラーがでてなんだか苦労したので、うまくいったサンプルパタンを挙げておく。

import smtplib
import email.encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

あちこちのサンプルではimportの時点でエラーとなるものがあった。Python3系と2系の違いだろうか?僕のsampleはPython3.6。

charset = 'ISO-2022-JP'
msg = MIMEMultipart()
msg['Subject'] = Header('これはテストです'.encode(charset),charset)
msg['From'] = ['foo@example.com']
msg['To'] = 'var@example.com'
body = MIMEText('これはテストです')
msg.attach(body)
attachment = MIMEBase('application','vnd.ms-excel')
f = open('sample.xlsx','rb')
attachment.set_payload(f.read())
f.close()
email.encoders.encode_base64(attachment)
msg.attach(attachment)
attachment.add_header('Content-Disposition','attachment',filename='sample.xlsx')

つまんな事だけど、open関数のところバイナリで指定がないサンプルがたくさんあった。僕の環境では明にバイナリ指定しないとエラーでした。

あと、email.encoders.encode_base64()の書き方も諸説あり?かな。僕が初心者すぎるのかも。

smtp = smtplib.SMTP('smtp.example.com')
smtp.ehlo()
smtp.sendmail(from_address,['var@example.com'],msg.as_string())
smtp.quit()

いずれにしてもこれまでメールの自動配信はperlで書いていたけど今後はpyhtonに移行する。