Pythonで添付付きファイルを送信するスクリプトです.

目次

  1. 備考
  2. スクリプト

備考

  • MIMEMultipartで,本文メッセージ部と添付部を扱えるようにする.
  • 例はSTARTTLSで587ポート.

スクリプト

import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

to_email = "宛先"
from_email = "差出人"
subject = "件名"
body = "本文"
filepath = "添付ファイルのパス"

svr_name = "サーバ名"
account = "アカウント"
password = "パスワード"

msg = MIMEMultipart()

msg["To"] = to_email
msg["From"] = from_email
msg["Subject"] = subject
msg.attach(MIMEText(body))

with open(filepath, "rb") as f:
attachment = MIMEApplication(f.read())

filename = os.path.basename(filepath)
attachment.add_header("Content-Disposition", "attachment", filename=filename)
msg.attach(attachment)

server = smtplib.SMTP(svr_name, 587)
server.starttls()
server.login(account, password)
server.send_message(msg)
server.quit()