Skip to content

Instantly share code, notes, and snippets.

@sahidursuman
Forked from derwiki/gmail-invoice-parse.rb
Created May 31, 2018 08:58
Show Gist options
  • Select an option

  • Save sahidursuman/3295bef025cb897ea92b9ca5cc9f13cf to your computer and use it in GitHub Desktop.

Select an option

Save sahidursuman/3295bef025cb897ea92b9ca5cc9f13cf to your computer and use it in GitHub Desktop.
Ruby script utilizing the ruby-gmail gem that allows for searching and downloading Gmail messages by label. This implementation is looking for invoice emails and parsing the amount of money that was transferred.
require 'gmail'
label = 'transactional/payment'
Gmail.new(username, password) do |gmail|
puts "Emails that match label '#{ label }'"
lender_profit = 0
gmail.mailbox(label).emails.each do |email|
message = email.message
next if message.subject =~ /^Re: /
next if message.subject =~ /^Fwd: /
timestamp = message.date.to_time.to_i
recipient_email = if message.to.is_a?(Enumerable)
message.to.first
else
message.to
end
match = message.body.to_s[/your profit:\n\-?\$([0-9\.]*)/] ||
message.body.to_s[/for a total of\n\$([0-9\.]*)/]
# before 2013-06-03, we didn't put the profit rate in emails
next if match.nil?
profit = match.split('$').last.to_f
profit *= -1 if match.include?(?-)
puts [ timestamp, recipient_email, profit ].join(',')
lender_profit += profit
end
puts "Total lender profit: $#{ lender_profit.round(2) }"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment