-
-
Save sparrovv/70beb618d4e71cce8b19 to your computer and use it in GitHub Desktop.
Mailman and rest client example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'mailman' | |
require 'rest_client' | |
require 'fileutils' | |
CLIENT_PATH = File.dirname(__FILE__) | |
module EmailHelper | |
def self.save_attachment(attachment) | |
File.open(CLIENT_PATH + '/files/' + attachment.filename, "w+b", 0644) do |f| | |
f.write attachment.body.decoded | |
f.path | |
end | |
rescue Exception => e | |
puts "Unable to save data for #{attachment.filename} because #{e.message}" | |
nil | |
end | |
def self.remove_attachments(attachments) | |
FileUtils.rm_f(attachments) | |
end | |
def self.valid_utf8_text_body(message) | |
if message.text_part | |
charset = message.text_part.charset | |
message.text_part.body.decoded.force_encoding(charset).encode('utf-8') | |
else | |
charset = message.charset | |
message.body.decoded.force_encoding(charset).encode('utf-8') | |
end | |
end | |
end | |
class Endpoint | |
def self.send(from, to, subject, body, attachments = []) | |
attrs = { | |
:body => body, | |
:from => from, | |
:to => to, | |
:subject => subject, | |
:attachments => attachments.map { |a| File.new(a, 'rb') } | |
} | |
RestClient.post(url, {:email => attrs}) | |
end | |
def self.url | |
'http://yourapp.com/api/emails' | |
end | |
end | |
# config to your mail account | |
Mailman.config.pop3 = { | |
:username => 'username', | |
:password => 'password', | |
:server => '', | |
:port => '', | |
:ssl => '' | |
} | |
Mailman.config.poll_interval = 10 | |
Mailman::Application.run do | |
to "%email-name%@yourdomain.com" do | |
begin | |
attachments = message.attachments.map do |attachment| | |
EmailHelper.save_attachment(attachment) | |
end.compact | |
text_body = EmailHelper.valid_utf8_text_body(message) | |
Endpoint.send( | |
message.from.first, | |
message.to, | |
message.subject, | |
text_body, | |
attachments | |
) | |
rescue => e | |
puts e.inspect | |
ensure | |
EmailHelper.remove_attachments(attachments) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment