LoginSignup
28
32

More than 3 years have passed since last update.

PythonでGmailを送信する

Posted at

事前準備

Googleアカウントのセキュリティを変更して、pythonからメールを送信できるようにする必要があります。

Googleアカウントのセキュリティから
Googleへのログイン-2段階認証プロセスをオンに変更、
アプリ パスワードを設定します。

セキュリティ.jpg

SMTPサーバに接続する

Gmailのサーバアドレス(smtp.gmail.com)、ポート587に自分のGoogleアカウントとパスワードでログインする必要があります。

smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
smtpobj.starttls()
smtpobj.login(sendAddress, password)

送信するメールを作成する

MIMETextに送信するメールの内容を追加します。
['Subject']に件名、['From']に送信元のメールアドレス、['To']に送信先のメールアドレスを追加することができます。

msg = MIMEText(bodyText)
msg['Subject'] = subject
msg['From'] = fromAddress
msg['To'] = toAddress
msg['Date'] = formatdate()

メールの送信

send_messageで作成したメールを送ることができます。

smtpobj.send_message(msg)
smtpobj.close()

まとめ

import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate

sendAddress = '自分のメールアドレス'
password = 'パスワード'

subject = '件名'
bodyText = '本文'
fromAddress = '送信元のメールアドレス'
toAddress = '送信先のメールアドレス'

# SMTPサーバに接続
smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
smtpobj.starttls()
smtpobj.login(sendAddress, password)

# メール作成
msg = MIMEText(bodyText)
msg['Subject'] = subject
msg['From'] = fromAddress
msg['To'] = toAddress
msg['Date'] = formatdate()

# 作成したメールを送信
smtpobj.send_message(msg)
smtpobj.close()
28
32
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
28
32