Skip to content

Instantly share code, notes, and snippets.

@kujirahand
Last active January 14, 2024 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kujirahand/fcf91f38711f9aea5781def0d86f1595 to your computer and use it in GitHub Desktop.
Save kujirahand/fcf91f38711f9aea5781def0d86f1595 to your computer and use it in GitHub Desktop.
import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email import encoders
from googleapiclient.discovery import build
from google.auth import load_credentials_from_file
# クレデンシャルファイルのパスを指定 --- (*1)
CREDENTIALS_PATH = 'credentials.json'
# カレンダーIDを指定
CALENDAR_ID = '28e4bb3f327eb238d29a282e9935fc957c40bb3e63ae831b9ecc935bee67efed@group.calendar.google.com'
# 誰にメールを送信するか指定 --- (*2)
EMAIL_ADDRESS = "***@gmail.com"
# SMTPサーバーの設定 --- (*3)
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
SMTP_PASSWORD = '***'
SUBJECT = 'イベントまでの日数'
# Google Calendar APIクライアントの作成 --- (*4)
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
credentials = load_credentials_from_file(CREDENTIALS_PATH, SCOPES)[0]
service = build('calendar', 'v3', credentials=credentials)
# イベントの開始日を指定 --- (*5)
now = datetime.datetime.utcnow()
start_date = now.isoformat() + 'Z'
# イベントの終了日を指定(ここでは30日後まで
end_date = (now + datetime.timedelta(days=30)).isoformat() + 'Z'
# イベントの一覧を取得 --- (*6)
events_result = service.events().list(
calendarId=CALENDAR_ID,
timeMin=start_date,
timeMax=end_date,
singleEvents=True,
maxResults=30, # 最大30件のイベントを取得
orderBy='startTime'
).execute()
events = events_result.get('items', [])
# イベントを表示 --- (*7)
body = "1ヶ月以内に重要なイベントは見つかりませんでした。"
if events:
body2 = ""
for event in events:
# イベントの開始時間を取得
target_date = event['start'].get('dateTime', event['start'].get('date'))
# そのイベントまで何日あるか調べて表示 --- (*9)
if 'T' in target_date: # タイムスタンプがあれば除去
target_date = target_date[:10]
now = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
target_td = datetime.datetime.strptime(target_date, '%Y-%m-%d')
days = (target_td - now).days
title = f'{days:2}日 - {event["summary"]}\n'
if '★' in title: # 重要なイベントは★をつける
body2 += title
if body2 != "":
body = body2
print("メッセージ本文:\n", body)
# メールの送信設定 --- (*10)
msg = MIMEMultipart()
msg["From"] = EMAIL_ADDRESS
msg["To"] = EMAIL_ADDRESS
msg["Subject"] = SUBJECT
msg["date"] = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
msg.attach(MIMEText(body.encode("utf-8"), "plain", "utf-8"))
# SMTPの設定とメール送信 --- (*11)
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls()
server.login(EMAIL_ADDRESS, SMTP_PASSWORD)
server.sendmail(
from_addr=EMAIL_ADDRESS,
to_addrs=EMAIL_ADDRESS,
msg=msg.as_string())
server.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment