Skip to content

Instantly share code, notes, and snippets.

@rxw1
Created November 15, 2013 03:04
Show Gist options
  • Save rxw1/7478447 to your computer and use it in GitHub Desktop.
Save rxw1/7478447 to your computer and use it in GitHub Desktop.
Downloads Gmail attachments of e-mails where the sender matches the given string.
#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-
require 'gmail'
require 'fileutils'
require 'pry'
username = 'YOUR_MAIL_ADDRESS_HERE'
password = 'YOUR_PASSWORD_HERE'
arg = ARGV[0].to_s
Gmail.connect(username, password) do |gmail|
if gmail.logged_in?
emails = gmail.mailbox('[Gmail]/All Mail').emails(:from => arg) # .find(arg)
if !emails.empty?
puts "Found #{emails.length} emails matching #{arg}"
emails.reverse.each do |email|
if !email.message.attachments.empty?
dir = "#{Dir.pwd}/#{arg}/#{email.message.date.strftime('%Y/%m/%d')}"
Dir.exists?(dir) || FileUtils.mkdir_p(dir)
email.message.attachments.each do |attachment|
puts "Downloading #{attachment.filename} to #{dir}"
File.write(File.join(dir, attachment.filename), attachment.body.decoded)
end
end
end
end
end
puts "Done. Good bye!"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment