Hatena::ブログ(Diary)

とある誰かの覚え書き このページをアンテナに追加 RSSフィード

2008-11-15

添付ファイル付きメールの送信サンプル

サンプル
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os.path
import datetime
import smtplib

from email import Encoders
from email.Utils import formatdate
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

def create_message(from_addr, to_addr, subject, body, attach_file):
    """
    Mailのメッセージを構築する
    """
    msg = MIMEMultipart()
    msg["Subject"] = subject
    msg["From"] = from_addr
    msg["To"] = to_addr
    msg["Date"] = formatdate()

    body = MIMEText(body)
    msg.attach(body)

    # 添付ファイルのMIMEタイプを指定する
    attachment = MIMEBase("application","vnd.ms-excel")
    # 添付ファイルのデータをセットする
    file = open(attach_file)
    attachment.set_payload(file.read())
    file.close()
    Encoders.encode_base64(attachment)
    msg.attach(attachment)
    attachment.add_header("Content-Disposition","attachment", filename=attach_file)

    return msg


def send(from_addr, to_addrs, msg):
    """
    Mailを送信する
    """
    smtp = smtplib.SMTP("localhost")
    smtp.sendmail(from_addr, to_addrs, msg.as_string())
    smtp.close()


if __name__ == '__main__':
    from_addr = "xxx@xx.xx"
    to_addr = "yyy@yy.yy"
    subject = "sample" 
    body = "test body"
    msg = create_message(from_addr, to_addr, subject, body, "sample.xls")
    send(from_addr, [to_addr], msg)

送信されたメール

こんな感じのメールが届きます。

Subject: sample
From: xxx@xx.xx
To: yyy@yy.yy
Date: Sat, 15 Nov 2008 09:42:15 -0000

--===============2075738206==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

test body
--===============2075738206==
Content-Type: application/vnd.ms-excel
MIME-Version: 1.0
Content-Disposition: attachment; filename="sample.xls"

スパム対策のためのダミーです。もし見えても何も入力しないでください
ゲスト


画像認証