0
2

More than 3 years have passed since last update.

pythonでスプレッドシートに記載しているアドレスにメールを送信

Last updated at Posted at 2020-05-09

こちらの動画のメモです。
https://youtu.be/Pw_jSRyX4lQ

下準備

http://console.developers.google.com/
1. 上記URLから、「Googleシート」と「Googleドライブ」のAPIを有効化し、JSONファイルを入手
2. 新しくフォルダ作成
3. JSONファイルを creds.json というファイル名に変更をして、フォルダに入れる
4. フォルダの中に、send.py というファイルを新しく作成
5. 以下のコマンドを入力して2つインストールを済ませておく

$ pip install gspread oauth2client

コードの中身

send.py
# メール送信関係
from email.mime.text import MIMEText
from email.utils import formatdate
import smtplib
# GoogleAPI連携関係
import gspread 
from oauth2client.service_account import ServiceAccountCredentials
from pprint import pprint 

scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]

creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)

client = gspread.authorize(creds)

# pythonというタイトルの最初のシートを取得しています。
# sheet1 = client.open("python").sheet1

SPREADSHEET_KEY = '*******************************'
sheet1= client.open_by_key(SPREADSHEET_KEY).worksheet('sheet1') 
sheet2= client.open_by_key(SPREADSHEET_KEY).worksheet('sheet2') 

# メール内容
body = sheet2.cell(2,2).value
title = sheet2.cell(2,1).value

# 全ての値を、dataという変数に代入しています。
data = sheet1.get_all_records()

# データ数を取得
last_number = len(data)

for row in range(last_number):
    # メール送信に必要な情報を抽出
    full_name = data[row]["name"]  # お名前
    msg = MIMEText(full_name + body)
    pprint(msg)

    msg['Subject'] = sheet2.cell(2,1).value
    msg['From'] = '**************@gmail.com'
    msg['To'] = data[row]["メールアドレス"]  # メールアドレス
    msg['Date'] = formatdate()

    smtp = smtplib.SMTP('smtp.gmail.com', 587)
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    smtp.login('**************@gmail.com', '**************')
    smtp.send_message(msg)
    smtp.close()
0
2
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
2