Class: Gmail::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/utilities/gmail/service.rb

Constant Summary collapse

SCOPES =
[
  "https://www.googleapis.com/auth/gmail.readonly",
  "https://www.googleapis.com/auth/gmail.send",
  "https://www.googleapis.com/auth/gmail.modify"
]
SCOPE =
SCOPES.join(" ")

Instance Method Summary collapse

Constructor Details

#initialize(skip_auth: false) ⇒ Service

Returns a new instance of Service.



24
25
26
27
28
# File 'lib/utilities/gmail/service.rb', line 24

def initialize(skip_auth: false)
  ensure_env!
  @service = Google::Apis::GmailV1::GmailService.new
  @service.authorization = authorize unless skip_auth
end

Instance Method Details

#add_label(email_id, label) ⇒ Object



228
229
230
231
# File 'lib/utilities/gmail/service.rb', line 228

def add_label(email_id, label)
  label_id = resolve_label_id(label)
  modify_message(email_id, add_label_ids: [label_id])
end

#archive_email(email_id) ⇒ Object



238
239
240
# File 'lib/utilities/gmail/service.rb', line 238

def archive_email(email_id)
  modify_message(email_id, remove_label_ids: ["INBOX"])
end

#authenticateObject



267
268
269
270
271
272
# File 'lib/utilities/gmail/service.rb', line 267

def authenticate
  perform_auth_flow
  {success: true}
rescue => e
  {success: false, error: e.message}
end

#get_email_content(email_id) ⇒ Object



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
# File 'lib/utilities/gmail/service.rb', line 107

def get_email_content(email_id)
  message = @service.get_user_message("me", email_id)

  # Extract email metadata
  headers = extract_headers(message.payload)

  # Extract email body
  body_data = extract_body(message.payload)

  {
    id: message.id,
    thread_id: message.thread_id,
    subject: headers["Subject"],
    from: headers["From"],
    to: headers["To"],
    cc: headers["Cc"],
    bcc: headers["Bcc"],
    date: headers["Date"],
    body: body_data[:text],
    body_html: body_data[:html],
    snippet: message.snippet,
    labels: message.label_ids || [],
    attachments: extract_attachments(message.payload)
  }
rescue Google::Apis::Error => e
  raise "Gmail API Error: #{e.message}"
rescue => e
  log_error("get_email_content", e)
  raise e
end

#list_emails(start_date: nil, end_date: nil, max_results: 20, sender: nil, subject: nil, labels: nil, read_status: nil) ⇒ Object



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
# File 'lib/utilities/gmail/service.rb', line 30

def list_emails(start_date: nil, end_date: nil, max_results: 20, sender: nil, subject: nil, labels: nil, read_status: nil)
  query_parts = []

  # Date filtering
  if start_date
    query_parts << "after:#{start_date}"
  end
  if end_date
    query_parts << "before:#{end_date}"
  end

  # Sender filtering
  if sender
    query_parts << "from:#{sender}"
  end

  # Subject filtering
  if subject
    query_parts << "subject:\"#{subject}\""
  end

  # Labels filtering
  if labels && !labels.empty?
    if labels.is_a?(Array)
      labels.each { |label| query_parts << "label:#{label}" }
    else
      query_parts << "label:#{labels}"
    end
  end

  # Read/unread status
  case read_status&.downcase
  when "unread"
    query_parts << "is:unread"
  when "read"
    query_parts << "is:read"
  end

  query = query_parts.join(" ")

  results = @service.list_user_messages(
    "me",
    q: query.empty? ? nil : query,
    max_results: max_results
  )

  emails = (results.messages || []).map do |message|
    get_email_summary(message.id)
  end.compact

  {emails: emails, count: emails.length}
rescue Google::Apis::Error => e
  raise "Gmail API Error: #{e.message}"
rescue => e
  log_error("list_emails", e)
  raise e
end

#mark_as_read(email_id) ⇒ Object



220
221
222
# File 'lib/utilities/gmail/service.rb', line 220

def mark_as_read(email_id)
  modify_message(email_id, remove_label_ids: ["UNREAD"])
end

#mark_as_unread(email_id) ⇒ Object



224
225
226
# File 'lib/utilities/gmail/service.rb', line 224

def mark_as_unread(email_id)
  modify_message(email_id, add_label_ids: ["UNREAD"])
end

#perform_auth_flowObject



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/utilities/gmail/service.rb', line 274

def perform_auth_flow
  client_id = Mcpeasy::Config.google_client_id
  client_secret = Mcpeasy::Config.google_client_secret

  unless client_id && client_secret
    raise "Google credentials not found. Please save your credentials.json file using: mcpz config set_google_credentials <path_to_credentials.json>"
  end

  # Create credentials using OAuth2 flow with localhost redirect
  redirect_uri = "http://localhost:8080"
  client = Signet::OAuth2::Client.new(
    client_id: client_id,
    client_secret: client_secret,
    scope: SCOPE,
    redirect_uri: redirect_uri,
    authorization_uri: "https://accounts.google.com/o/oauth2/auth",
    token_credential_uri: "https://oauth2.googleapis.com/token"
  )

  # Generate authorization URL
  url = client.authorization_uri.to_s

  puts "DEBUG: Client ID: #{client_id[0..20]}..."
  puts "DEBUG: Scope: #{SCOPE}"
  puts "DEBUG: Redirect URI: #{redirect_uri}"
  puts

  # Start callback server to capture OAuth code
  puts "Starting temporary web server to capture OAuth callback..."
  puts "Opening authorization URL in your default browser..."
  puts url
  puts

  # Automatically open URL in default browser on macOS/Unix
  if system("which open > /dev/null 2>&1")
    system("open", url)
  else
    puts "Could not automatically open browser. Please copy the URL above manually."
  end
  puts
  puts "Waiting for OAuth callback... (will timeout in 60 seconds)"

  # Wait for the authorization code with timeout
  code = GoogleAuthServer.capture_auth_code

  unless code
    raise "Failed to receive authorization code. Please try again."
  end

  puts "✅ Authorization code received!"
  client.code = code
  client.fetch_access_token!

  # Save credentials to config
  credentials_data = {
    client_id: client.client_id,
    client_secret: client.client_secret,
    scope: client.scope,
    refresh_token: client.refresh_token,
    access_token: client.access_token,
    expires_at: client.expires_at
  }

  Mcpeasy::Config.save_google_token(credentials_data)
  puts "✅ Authentication successful! Token saved to config"

  client
rescue => e
  log_error("perform_auth_flow", e)
  raise "Authentication flow failed: #{e.message}"
end

#remove_label(email_id, label) ⇒ Object



233
234
235
236
# File 'lib/utilities/gmail/service.rb', line 233

def remove_label(email_id, label)
  label_id = resolve_label_id(label)
  modify_message(email_id, remove_label_ids: [label_id])
end

#reply_to_email(email_id:, body:, include_quoted: true) ⇒ Object



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/utilities/gmail/service.rb', line 166

def reply_to_email(email_id:, body:, include_quoted: true)
  # Get the original message to extract reply information
  original = @service.get_user_message("me", email_id)
  headers = extract_headers(original.payload)

  # Build reply headers
  original_subject = headers["Subject"] || ""
  reply_subject = original_subject.start_with?("Re:") ? original_subject : "Re: #{original_subject}"

  reply_to = headers["Reply-To"] || headers["From"]
  message_id = headers["Message-ID"]

  # Prepare reply body
  reply_body = body
  if include_quoted
    original_body = extract_body(original.payload)[:text]
    date_str = headers["Date"]
    from_str = headers["From"]

    reply_body += "\n\n"
    reply_body += "On #{date_str}, #{from_str} wrote:\n"
    reply_body += original_body.split("\n").map { |line| "> #{line}" }.join("\n")
  end

  mail = Mail.new do
    to reply_to
    subject reply_subject
    body reply_body
    in_reply_to message_id if message_id
    references message_id if message_id
  end

  raw_message = mail.to_s
  encoded_message = Base64.urlsafe_encode64(raw_message)

  message_object = Google::Apis::GmailV1::Message.new(
    raw: encoded_message,
    thread_id: original.thread_id
  )

  result = @service.send_user_message("me", message_object)

  {
    success: true,
    message_id: result.id,
    thread_id: result.thread_id
  }
rescue Google::Apis::Error => e
  raise "Gmail API Error: #{e.message}"
rescue => e
  log_error("reply_to_email", e)
  raise e
end

#search_emails(query, max_results: 10) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/utilities/gmail/service.rb', line 88

def search_emails(query, max_results: 10)
  results = @service.list_user_messages(
    "me",
    q: query,
    max_results: max_results
  )

  emails = (results.messages || []).map do |message|
    get_email_summary(message.id)
  end.compact

  {emails: emails, count: emails.length}
rescue Google::Apis::Error => e
  raise "Gmail API Error: #{e.message}"
rescue => e
  log_error("search_emails", e)
  raise e
end

#send_email(to:, subject:, body:, cc: nil, bcc: nil, reply_to: nil) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/utilities/gmail/service.rb', line 138

def send_email(to:, subject:, body:, cc: nil, bcc: nil, reply_to: nil)
  mail = Mail.new do
    to to
    cc cc if cc
    bcc bcc if bcc
    subject subject
    body body
    reply_to reply_to if reply_to
  end

  raw_message = mail.to_s
  encoded_message = Base64.urlsafe_encode64(raw_message)

  message_object = Google::Apis::GmailV1::Message.new(raw: encoded_message)
  result = @service.send_user_message("me", message_object)

  {
    success: true,
    message_id: result.id,
    thread_id: result.thread_id
  }
rescue Google::Apis::Error => e
  raise "Gmail API Error: #{e.message}"
rescue => e
  log_error("send_email", e)
  raise e
end

#test_connectionObject



252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/utilities/gmail/service.rb', line 252

def test_connection
  profile = @service.("me")
  {
    ok: true,
    email: profile.email_address,
    messages_total: profile.messages_total,
    threads_total: profile.threads_total
  }
rescue Google::Apis::Error => e
  raise "Gmail API Error: #{e.message}"
rescue => e
  log_error("test_connection", e)
  raise e
end

#trash_email(email_id) ⇒ Object



242
243
244
245
246
247
248
249
250
# File 'lib/utilities/gmail/service.rb', line 242

def trash_email(email_id)
  @service.trash_user_message("me", email_id)
  {success: true}
rescue Google::Apis::Error => e
  raise "Gmail API Error: #{e.message}"
rescue => e
  log_error("trash_email", e)
  raise e
end