Quantcast
Channel: Maesan blog » Python
Viewing all articles
Browse latest Browse all 7

[Python] メール送信

$
0
0

Pythonでメールを送信したかったのでやってみた

基本的には以下のページのコピペなのですが、1点引っかかったのでメモ
Pythonでメールを送信したい人のためのサンプル集

#!/usr/bin/env python
# encoding: utf-8

import smtplib
from email.MIMEText import MIMEText
from email.Utils import formatdate

def SendMail(to_addr, subject, body, from_addr=None):
if from_addr is None:
from_addr = "hoge@maesan.jp"
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = from_addr
msg["To"] = to_addr
msg["Date"] = formatdate()

s = smtplib.SMTP()
s.sendmail(from_addr, [to_addr], msg.as_string())
s.close()

if __name__ == '__main__':
from_addr = 'hoge@maesan.jp'
to_addr = 'foo@maesan.jp'
subject = 'test mail'
body = 'test'
SendMail(to_addr, subject, body, from_addr)

これでおkだと思ってたのですが、実行すると

AttributeError: SMTP instance has no attribute ‘sock’

ってエラーがでた。

多分メールサーバーとの接続に失敗したのかなと思い、明示的にサーバーとポートを指定したら動いた。

# s = smtplib.SMTP() # ↓こんな感じに変更
s = smtplib.SMTP("localhost", 25)

参考ページ

Pythonでメールを送信したい人のためのサンプル集
[ mailman-Bugs-1315417 ] SMTP problem


Viewing all articles
Browse latest Browse all 7

Trending Articles