-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsend_email_forum.py
146 lines (119 loc) · 4.93 KB
/
send_email_forum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# we using gmail api now, fk sendgrid and mailgun and courier
# ------------ Dependencies to call the Gmail and Google API ------------------
from __future__ import print_function
import os.path
import base64
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from email.message import EmailMessage
# ------------ Dependencies for AMQP exchange and queue -----------------------
import json
import requests
import os
import amqp_setup
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
# PLEASE CHECK!! THE GOOGLE TOKEN NEEDS TO BE REFRESHED!! IT HAS A TIME FRAME BEFORE IT EXPIRES, WHICH MEANS YOU NEED TO GENERATE A NEW TOKEN BEFORE YOU RUN THIS FILE!!
# TLDR: DELETE TOKEN.JSON BEFORE RUNNING SEND_EMAIL.PY!
monitor_binding_key = "#.email.forum.#"
'''
Function: initiate the queue
'''
def receive_sms():
amqp_setup.check_setup()
queue_name = 'email_forum'
# set up queue and look for incoming messages
amqp_setup.channel.basic_consume(
queue=queue_name, on_message_callback=callback, auto_ack=True)
amqp_setup.channel.start_consuming()
# need to terminate using Ctrl+C
'''
Function: callback function when receiving a message
Input: Input: JSON object -> {
"food" : JSON object,
"user" : JSON object
}
'''
def callback(channel, method, properties, body):
print("\nReceived an email from " + __file__)
sendClientUpdate(json.loads(body))
print()
'''
Function: sending an SMS to related users
Input: JSON object -> {
"food" : JSON object,
"user" : JSON object
}
Output: SMS sent to users + a line printing the result of each SMS + success line when code completes
'''
def sendClientUpdate(body):
comment = body['comment']
post = body['post']
user = body['user']
# user info
# recipient_email = user['email']
# recipient_name = user['name']
recipient_email = "[email protected]"
recipient_name = user['name']
# comment info
commenter_name = comment['commentor_username']
comment_content = comment['comment']
comment_datetime = comment['datetime']
# post info
# poster_name = post["username"]
post_title = post["title"]
# post_description = post["description"]
# post_datetime = post["datetime"]
## edit the body of the message here ##
msg = f'Dear {recipient_name},\n\nUser {commenter_name} has commented on your post: {post_title}!\n\n{commenter_name} commented:\n{comment_content}\n- {comment_datetime}.\n\nThis is an automated message, please do not reply to this thread.\n\nHappy Eating,\nMakanBoleh'
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
try:
# create gmail api client
service = build('gmail', 'v1', credentials=creds)
message = EmailMessage()
## this is where the notification message goes ##
message.set_content(f'{msg}')
message['To'] = recipient_email
message['From'] = '[email protected]'
message['Subject'] = 'MakanBoleh: New Comment on Your Forum Post!'
# encoded message
encoded_message = base64.urlsafe_b64encode(message.as_bytes()) \
.decode()
create_message = {
'raw': encoded_message
}
# pylint: disable=E1101
send_message = (service.users().messages().send
(userId="me", body=create_message).execute())
print(F'Message Id: {send_message["id"]}')
print(f"Email to {recipient_name} has been sent to the following email : {recipient_email}")
except HttpError as error:
# TODO(developer) - Handle errors from gmail API.
print(f'An error occurred: {error}')
if __name__ == "__main__":
print("\nThis is " + os.path.basename(__file__), end='')
print(f": monitoring routing key '{monitor_binding_key}' in exchange '{amqp_setup.exchangename}' ...".format(
monitor_binding_key, amqp_setup.exchangename))
receive_sms()