LoginSignup
0
0

More than 1 year has passed since last update.

Pythonでメールを送りたい

Posted at

メール送信を自動化したかったので、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を使いましたが、使用するプロトコルが違うと別のメソッドを使うみたいです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0