Hi, I`m trying to create the following feature: You register and receive an email like [email protected] and when you send something to this email it automatically appears in something like your wall... So my problem is how to realize the creation of the email and the receiving of the mail itself. Any ideas?
Sending E-Mails is simple as pie. Simply have a look at the ActionMailer Basics. If you also want to receive E-Mail, you should write a daemon that fetches Mails from the mailserver continuously in the background.
Here a snippet that fetches Mails via POP:
require 'net/pop'
config = {
:host => "mail.example.com",
:user => "[email protected]",
:password => "…",
:port => 110,
:timeout => 10
}
pop = Net::POP3.new(config[:host])
pop.start(config[:user], config[:password])
if pop.mails.empty?
puts "No mails…"
else
pop.mails.each do |mail|
# do stuff with mail
end
end
This is pure Ruby-Code, Rails is not needed for this snippet.
There might be other options but that's how we do it:
- Postfix
- Rails Cron Job
Postfix allows you to specify a MySQL table/view to check whether an email address exists or not. You can also define Mail Forwardings.
- Create a DB View to match the requirements on Postfix
- This View should contain all the email addresses and forward them to a different mail account, like
mailparser
.
- This View should contain all the email addresses and forward them to a different mail account, like
- Now your Rails can either
- use a POP3/IMAP frontend to the mailserver (you should install Dovecot or Courier then) to fetch the mails and process them
- or go to the place on the disk where all the mails are located (check Postfix config for that) and parse the files as TMail objects and process them.
A different option is to make Postfix call script/runner
with the Mail data, but rails boot-up can take long and a lot of memory, so I prefer having a Cronjob/Backgroundjob/Worker to do this.
P.S. The Creation of the E-Mail will be done by creating a Model for your Rails app which the View will use as a basis.
Ruby provides Net/IMAP and Net/POP3 you can use to login into your email account. Here's a small tutorial.
POP3
pop = Net::POP3.new("pop.gmail.com", port)
pop.enable_ssl
pop.start('YourAccount', 'YourPassword')
if pop.mails.empty?
puts 'No mail.'
else
i = 0
pop.each_mail do |m|
File.open("inbox/#{i}", 'w') do |f|
f.write m.pop
end
m.delete
i += 1
end
puts "#{pop.mails.size} mails popped."
end
pop.finish
IMAP
imap = Net::IMAP.new('imap.gmail.com')
imap.authenticate('LOGIN', 'username', 'password')
imap.select('INBOX')
imap.search(['ALL']).each do |message_id|
msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
MailReader.receive(msg)
imap.store(message_id, "+FLAGS", [:Deleted])
end
imap.expunge()