-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgmail_streeteasy_reply.py
148 lines (124 loc) · 5.64 KB
/
gmail_streeteasy_reply.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
147
148
# thsi script checks gmail for emails from streeteasy gets the person who is interested email and sends a template email with an ics attachment
# then marks the email as read
import os.path
import re
import base64
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email import message_from_bytes
# If modifying these SCOPES, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send','https://www.googleapis.com/auth/gmail.modify']
def authenticate_gmail():
"""Authenticates with Gmail API and returns the service object."""
creds = None
if os.path.exists('/home/joerod/token.json'):
creds = Credentials.from_authorized_user_file('/home/joerod/token.json', SCOPES)
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(
'/home/joerod/credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('/home/joerod/token.json', 'w') as token:
token.write(creds.to_json())
return creds
def search_emails_with_subject(service, subjects):
subject_query = ' OR '.join([f'subject:"{subject}"' for subject in subjects])
query = f'is:unread ({subject_query})'
results = service.users().messages().list(userId='me', q=query).execute()
messages = results.get('messages', [])
if not messages:
print('No unread messages found with subjects:', subjects)
else:
unique_emails = set()
for message in messages:
msg_id = message['id']
msg = service.users().messages().get(userId='me', id=msg_id, format='raw').execute()
msg_str = base64.urlsafe_b64decode(msg['raw'].encode('ASCII'))
mime_msg = message_from_bytes(msg_str)
email_body = get_email_body(mime_msg)
extract_and_store_unique_emails(email_body, unique_emails)
# Mark the email as read
mark_as_read(service, msg_id)
# Remove specific email address if present
unique_emails.discard('[email protected]')
if unique_emails:
print("Unique email addresses found:", unique_emails)
for email in 'unique_emails':
send_email(service, email)
else:
print("No unique email addresses found.")
def get_email_body(mime_msg):
"""Extracts the body from the email message"""
if mime_msg.is_multipart():
for part in mime_msg.walk():
if part.get_content_type() == "text/html":
return part.get_payload(decode=True).decode()
else:
if mime_msg.get_content_type() == "text/plain":
return mime_msg.get_payload(decode=True).decode()
return ""
def extract_and_store_unique_emails(text, email_set):
"""Extracts email addresses from text and stores unique ones in the set"""
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
email_addresses = re.findall(email_pattern, text)
for email in email_addresses:
email_set.add(email)
def create_message_with_attachment(to, subject, message_text, ics_content):
"""Create a message for an email with an .ics attachment."""
message = MIMEMultipart()
message['to'] = to
message['subject'] = subject
# Add body to email
message.attach(MIMEText(message_text, 'plain'))
# Create the .ics file and attach it
ics = MIMEApplication(ics_content, 'octet-stream')
ics.add_header('Content-Disposition', 'attachment; filename="invite.ics"')
message.attach(ics)
raw = base64.urlsafe_b64encode(message.as_bytes()).decode()
return {'raw': raw}
def send_email(service, to_email):
"""Send an email to the specified address."""
subject = "21-28 35th Street #4E Astoria"
body = """Hello,
Thanks for your interest in my apartment, my name is Joe and I am the owner of this unit.
I am having an open house this Sunday 5/19/24 between 12PM and 1:30PM. Feel free to come by then to view the apartment and fill out an application if you’re interested.
Attached you'll see an invitation to the open house which you can add to your calendar.
Thanks,
Joe Rodriguez
(212) 877-0591"""
# Create .ics file content
ics_content = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Your Organization//NONSGML v1.0//EN
BEGIN:VEVENT
DTSTAMP:20240519T160000Z
DTSTART:20240519T160000Z
DTEND:20240519T173000Z
SUMMARY:Open House
DESCRIPTION:Open house for 2128 35th Street 4e, Astoria, NY 11105.
LOCATION:2128 35th Street, Astoria, NY 11105
END:VEVENT
END:VCALENDAR"""
message = create_message_with_attachment(to_email, subject, body, ics_content)
sent_message = service.users().messages().send(userId="me", body=message).execute()
print(f'Email sent to {to_email}')
def mark_as_read(service, msg_id):
"""Mark an email as read."""
service.users().messages().modify(userId='me', id=msg_id, body={'removeLabelIds': ['UNREAD']}).execute()
print(f'Marked message {msg_id} as read.')
def main():
creds = authenticate_gmail()
service = build('gmail', 'v1', credentials=creds)
subjects = ["New Zillow Group Rentals Contact: 21-28 35th St #4E",
"21-28 35th Street #4E StreetEasy Inquiry"]
search_emails_with_subject(service, subjects)
if __name__ == '__main__':
main()