2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonでのGmailの自動化

Posted at

はじめに

PythonでのGmail送信自動化の備忘録です💁
初心者です😅
間違えてる部分多々あると思います。
もし見つけた場合、ツッコミいただけると助かります🙇

内容

PythonにGmailを送るときに使えるやり方。
関数化しておいて後で再利用できるように作成。

メール処理定義

sendsys.py
import smtplib
from email.mime.text import MIMEText


def send_email(from_email, to_email, subject, message, smtp_password, smtp_host='smtp.gmail.com', smtp_port=587):
    msg = MIMEText(message, 'plain')
    msg['Subject'] = subject
    msg['To'] = to_email
    msg['From'] = from_email

    with smtplib.SMTP(smtp_host, smtp_port) as server:
        try:
            server.starttls()
            server.login(from_email, smtp_password)
            server.send_message(msg)
            print(f'メール送信が完了しました。')
        except Exception as e:
            print(f'メール送信に失敗しました:{e}')

メール内容を定義

本文、件名などを決めておいて送信できるように設定。
「処理に成功」「処理に失敗」
このようなシーンでメールでの通知が欲しいシュチュエーションに合わせて内容を記載する。

sample.py
from sendsys import send_email

# 処理が成功した際にメールを送る機能
def success_send():
    # 送信するメールの情報を設定
    # 送信元
    from_email = '*****@gmail.com'

    # メールを送る相手のアドレス
    to_email = '*****@gmail.com'

    # 件名
    subject = 'テストメール'

    # 本文
    message = '今日も最高でした。'

    # アプリパスワードを設定
    # やり方 Googleのアカウント→セキュリティ→2段階認証→アプリパスワード
    smtp_password = 'eaqa kyvh pmso xzmr'

    # メール送信関数を呼び出す
    send_email(from_email, to_email, subject, message, smtp_password)

押さえておくべき点🧠

  • アプリパスワードの取得
  • Gmailの受信メールなどの機能を使いたい場合はAPI

参考にしたサイト

Pythonでメール作成・自動送信

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?