メール送信を自動化したかったので、Pythonで作ってみました。
テキストメールを送信する
下のプログラムは、SMTPS(TCP465)のプロトコルを使ってプレーンテキストを送信します。
import smtplib
from email.mime.text import MIMEText
msg = MIMEText("メールの本文を書きます","plain","utf-8")
msg["From"] = "xxx@xxx.xxx"
msg["To"] = "yyy@yyy.yyy"
msg["Subject"] = "タイトルを書きます"
smtp = smtplib.SMTP_SSL(host="プロバイダのSMTPメールサーバ",port=465)
smtp.login("ユーザ名","パスワード")
smtp.send_message(msg)
smtp.quit()
添付ファイルを送信する
下のプログラムは、SMTPS(TCP465)のプロトコルを使ってプレーンテキストと添付ファイルを送信します。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
msg = MIMEMultipart()
msg.attach(MIMEText("メールの本文を書きます","plain","utf-8"))
msg["From"] = "xxx@xxx.xxx"
msg["To"] = "yyy@yyy.yyy"
msg["Subject"] = "タイトルを書きます"
with open("file.txt","rb") as f:
mime_file = MIMEApplication(f.read())
mime_file.add_header("Content-Disposition", "attachment", filename="file.txt")
msg.attach(mime_file)
smtp = smtplib.SMTP_SSL(host="プロバイダのSMTPメールサーバ",port=465)
smtp.login("ユーザ名","パスワード")
smtp.send_message(msg)
smtp.quit()
おわりに
今回はSMTPSを使いましたが、使用するプロトコルが違うと別のメソッドを使うみたいです。