Skip to content

Instantly share code, notes, and snippets.

@mirrec
Last active May 24, 2022 10:05
Show Gist options
  • Save mirrec/7531098 to your computer and use it in GitHub Desktop.
Save mirrec/7531098 to your computer and use it in GitHub Desktop.
how to delete email from mailbox with ruby and imap
require "net/imap"
imap = Net::IMAP.new("imap.domain.sk")
imap.login("info@domain.sk", "HESLO")
imap.select("inbox")
# search for emails that you want to delete
bad_messages = imap.search(["FROM", "from@gmail.com"])
puts "#{bad_messages.count} messages will be deleted"
bad_messages.each do |message_id|
# copy mail to TRASH folder, just in case you are deleting wrong emails
imap.copy(message_id, "TRASH")
imap.store(message_id, "+FLAGS", [:Deleted])
end
imap.expunge # flush for deleting
imap.logout
# *Sources*
# * https://gist.github.com/viking/3164382
# * http://stackoverflow.com/questions/10278849/how-to-search-message-in-mailbox-with-net-imap-in-ruby
# * http://alvinalexander.com/blog/post/ruby/ruby-search-imap-mail-server-using-multiple-search-fields
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment