Ruby/Network/Email POP3

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

connect to a POP3 server to see if there are any messages available for download

require "net/pop"
mail_server = Net::POP3.new("mail.mailservernamehere.ru")
begin
  mail_server.start("username","password")
  if mail_server.mails.empty?
    puts "No mails"
  else
    puts "#{mail_server.mails.length} mails waiting"
  end
rescue
  puts "Mail error"
end



deletes messages if their subject contains the word "medicines":

require "net/pop"
mail_server = Net::POP3.new("mail.mailservernamehere.ru")
 
mail_server.mails.each do |m|
  m.delete if m.header =~ /Subject:.+?medicines\b/i
end



Downloading all the mails is as simple as using the pop method for each Net::POPMail object:

require "net/pop"
mail_server = Net::POP3.new("mail.mailservernamehere.ru")
 
mail_server.mails.each do |m|
  mail = m.pop
  puts mail
end



e-mail provider

require "net/smtp"
message = <<MESSAGE_END
From: Private Person <me@privacy.net>
To: Author of Beginning Ruby <test@rubyinside.ru>
Subject: SMTP e-mail test
This is a test e-mail message.
MESSAGE_END
Net::SMTP.start("mail.your-domain.ru") do |smtp|
  smtp.send_message message, "me@your.net", "test@r.ru"
end



Sending Mail with SMTP

require "net/smtp"
message = <<MESSAGE_END
From: Private Person <me@privacy.net>
To: Author of Beginning Ruby <test@rubyinside.ru>
Subject: SMTP e-mail test
This is a test e-mail message.
MESSAGE_END
Net::SMTP.start("localhost") do |smtp|
  smtp.send_message message, "me@privacy.net", "test@rubyinside.ru"
end



Send the mail directly to that user

require "resolv"
require "net/smtp"
from = "your-email@example.ru"
to = "another-email@example.ru"
message = <<MESSAGE_END
From: #{from}
To: #{to}
Subject: Direct e-mail test
This is a test e-mail message.
MESSAGE_END
to_domain = to.match(/\@(.+)/)[1]
Resolv::DNS.open do |dns|
  mail_servers = dns.getresources(to_domain, Resolv::DNS::Resource::IN::MX)
  mail_server = mail_servers[rand(mail_servers.size)].exchange.to_s
  Net::SMTP.start(mail_server) do |smtp|
    smtp.send_message message, from, to
  end
end



specify port number

require "net/smtp"
message = <<MESSAGE_END
From: Private Person <me@privacy.net>
To: Author of Beginning Ruby <test@rubyinside.ru>
Subject: SMTP e-mail test
This is a test e-mail message.
MESSAGE_END
Net::SMTP.start("mail.your-domain.ru", 25, "localhost", "username", "password", :plain)
 do |smtp|
  smtp.send_message message, "me@privacy.net", "test@r.ru"
end



To delete a mail

require "net/pop"
mail_server = Net::POP3.new("mail.mailservernamehere.ru")
 
mail_server.mails.each do |m|
  m.delete if m.pop =~ /\bthis is a spam e-mail\b/i
end