开发者

Parsing through email in Ruby using Action Mailer

开发者 https://www.devze.com 2022-12-27 11:30 出处:网络
I retrieve mail using net/pop , but I a开发者_JAVA百科lso need to parse through the email to obtain subject,from address and email body.

I retrieve mail using net/pop , but I a开发者_JAVA百科lso need to parse through the email to obtain subject,from address and email body. Any ideas with Action Mailer? I'm supposed to use 3rd party gems.(No,not even Tmail)

require 'rubygems'
require 'net/pop'
require 'pop_ssl'

Net::POP3.enable_ssl(OpenSSL::SSL::VERIFY_NONE)  

def pull_mail
  Net::POP3.start("pop.gmail.com", 995, "uname","pass") do |pop|  

    if pop.mails.empty?  
      puts 'No mails.'  
    else  
      pop.each_mail do |mail|  
      puts mail_header
    end  
  end

end

Cheers!


Basically, you just need to write your email handler, and all the parsing will be done for you behind the scenes:

class MailHandler < ActionMailer::Base
  def receive(email)
    # here you will have an email object and will be able to call methods like
    # email.subject and email.attachments

    puts "from: #{email.from}, subject: '#{email.subject}'"
  end
end

When you get emails using Net::POP3, just hand them off to your handler:

Net::POP3.start(server, port, username, password) do |pop|
  pop.each_mail { |mail| MailHandler.receive(mail.pop) }
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号