先日はサーバ上のPostfixでGmail経由でのメール送信をご紹介したが、
今回はPythonのプログラム上で以下の各種メールサービスを経由して、
メール送信をする方法となる。

以下の場合はPostfixの設定は不要でコード自身からメール送信可能である。

何かの処理結果をメール送信したい場合に使用できると思う。


Gmailの場合

#!/usr/bin/python3
import smtplib,ssl
from email.mime.text import MIMEText

user="loginuser@xxxx.com"
password="password"
# 送受信先
to_email = "abcdefg@xxxxx.com"
from_email = "abcdefg@xxxx.com"
 
# MIMETextを作成
message = "メール本文"
msg = MIMEText(message, "html")
msg["Subject"] = "メール表題"
msg["To"] = to_email 
msg["From"] = from_email 
 
# サーバを指定する
server = smtplib.SMTP("smtp.gmail.com",587)
server.starttls()
server.login(user,password)
# メールを送信する
server.send_message(msg)
# 閉じる
server.quit()

OutLook/Hotmail/msnの場合

#!/usr/bin/python3
import smtplib,ssl

user="loginuser@xxxx.com"
password="password"
# 送受信先
to_email = "abcdefg@xxxxx.com"
from_email = "abcdefg@xxxx.com"

# MIMETextを作成
message = "メール本文"
msg = MIMEText(message, "html")
msg["Subject"] = "メール表題"
msg["To"] = to_email
msg["From"] = from_email

# サーバを指定する
server = smtplib.SMTP("outlook.live.com",587)
server.starttls()
server.login(user,password)
# メールを送信する
server.send_message(msg)
# 閉じる
server.quit()

Yahoo Mailの場合

#!/usr/bin/python3
import smtplib,ssl
from email.mime.text import MIMEText

user="loginuser@xxxx.com"
password="password"
# 送受信先
to_email = "abcdefg@xxxxx.com"
from_email = "abcdefg@xxxx.com"

# MIMETextを作成
message = "メール本文"
msg = MIMEText(message, "html")
msg["Subject"] = "メール表題"
msg["To"] = to_email
msg["From"] = from_email

# サーバを指定する
server = smtplib.SMTP_SSL("smtp.mail.yahoo.co.jp",465, context=ssl.create_default_context())
server.login(user,password)

# メールを送信する
server.send_message(msg)
# 閉じる
server.quit()

GmailとOutLookは同じ仕掛けです。

ただ、Gmailは二段階認証のパスワードが必要です。

これでPythonによる自動化ツールのアラートをメールで飛ばすことができるようになりますね。

参考になれば幸いです。