LoginSignup
0
0

Gmail × Python メールの自動送信プログラム

Posted at

はじめに

クライアントからGmailに自動送信されるよう要件定義があったので、そのためのコードを残しておきます。

スクリプト

title.py

import smtplib
from email.mime.text import MIMEText
from email.header import Header

def send_email(from_email, to_email, subject, message, smtp_password):
    msg = MIMEText(message, 'plain', 'utf-8')
    msg['From'] = Header(from_email, 'utf-8')
    msg['To'] = Header(to_email, 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')

    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.login(from_email, smtp_password)
    server.sendmail(from_email, [to_email], msg.as_string())
    server.quit()

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

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

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

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

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

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


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