Send and receive messages using Ruby

Source: Internet
Author: User
Tags mail regular expression

1. Send email via SMTP

Every week Holden Glova,pat Eyler, and Phil Thomson submits a Ruby http://www.rubygarden.org/News (Weekly) article to the Ruby Garden website (rwn). A Ruby script receives this article via email, converts it from the original XML format to HTML and plain text format, and then publishes HTML to the Web site, and then posts the text in plain format to the mailing list. If there is a problem (such as an XML document structure that is not correct), the script sends an email containing the error message to the sender.

This script sends an email with the NET::SMTP (simple Mail Transfer Protocol) library. Listing 1 is the method used to send emails in this script, which receives 3 parameters: email address, title, and letter content. Because this program is to be used in a variety of control environment, so some similar senders, forwarding email hosts and other attributes are defined as global constants, rather than parameters.

Listing 1: Sending mail over SMTP

1 FROM_ADDRESS = "dave@pragprog.com"
2 SMTP_HOST = "localhost"
3
4 def reply(to, subject, msg)
5 mail = "To: #{to}\r\n" +
6 "From: #{FROM_ADDRESS}\r\n" +
7 "Subject: #{subject}\r\n" +
8 "\r\n" +
9 msg
10
11 Net::SMTP.start(SMTP_HOST) do |smtp|
12 smtp.send_mail(mail, FROM_ADDRESS,
13 [ to, 'rurl_archive@zip.local.pragprog.com' ])
14 end
15 end

An email message consists of two parts: an envelope (envelope) and content. Envelopes tell the SMTP proxy (sendmail or postfix) how to post messages. The content includes the message itself and some headers (such as message subject) that can be read by people, and the header in some content may be duplicated in the envelope (such as "to" address), and these duplicate headers are used to display the time used, The envelope is used for posting. (This is also why you receive "to" addresses that are not your spam messages)

You can see that the reply method has separated the envelop and content, and lines 5th through 9th generate the content, which includes 3 Header:to,from,subject, followed by a blank line followed by a message. Note the header before the headers must have a carriage return line, that is, a combination of "\ r" and "\ n".

Method Net::smtp.start to establish a connection to the MTA (Mail transfer agent), one of the parameters of which is the machine name running the MTA, and the default port (25) is used, which returns an object used to interact with the MTA. and passed the object as an argument to block (11 lines to 13 lines). Block is used to ensure that the connection can be closed after block ends.

In our example, the interaction process is simple, and the 12th line of the program just sends the message that was just delivered.

The second parameter of the Send_mail method is the From address used, which is a global variable. The third parameter is an array that contains the address of the recipient. We've sent this message to two places, a parameter to the to, and a local mailbox to archive all the messages.

2. Receive and read mail with pop

Using Ruby to receive mail from a POP server is a very simple thing to do. If we want to be interested in people's various languages, the person who participates in the survey can send a specific address by sending a message titled I like XXXXX, which is the name of the language the sender prefers. The Ruby script in Listing 2 is used to receive results from the POP server and to compute the number of loved persons in each language in a common file, one file per language.

Listing 2:fetching email with POP

1 require 'net/pop'
2
3 Net::POP3.delete_all('pop3.server.address', 110,
4 'YourAccount', 'YourPassword' ) do |email|
5 hdr = email.header
6 if hdr =~ /Subject:\s+I like\s+(\w+)/
7 language = $1.upcase
8 else
9 language = "INVALID"
10 end
11
12 count = (File.read(language) rescue "0")
13 File.open(language, "w") {|f| f.puts old_count.succ}
14 end

The POP server holds the user's message, and when you finish reading a message, you can choose to delete the letter, or put it on the server, in our example, we will delete it after we read it. Fortunately, Ruby offers a handy iterator delete_all, which strips out the mail and deletes the letters after processing. Delete_all required parameters include the address and port of the POP server (standard port is 110), and the username and password.

After this method is started, the server will be connected with the specified parameters, a Feng Yi to get the user's message, and then each time the letter (as a net::P Opmail object) is passed to the given block, and the block will delete the letter after it has finished processing it.

Within this block, line 5th will be taken out of all headers of this letter and placed in a string. Then in line 6th, use a regular expression in the title (Subject) to look for similar included I like XXXX line, find the language represented by XXXX, and then update the count of the language selected by the voter found in lines 12 and 13.

The 12th line has a very interesting structure. Every time we get a vote for a language, we use a file to store the number of votes in the language. We can read this value, add it, and then write it back to the file. But the first time someone voted for a language, this file doesn't exist yet, and when we read this file, we get an exception, and luckily Ruby provides an exception mechanism (keyword rescue), but when an exception occurs because the file does not exist, the exception is caught, and a default value of 0 is returned. The number of votes in this language is 0.

Another tip is the old_count.succ of line 13th, which we use to add a string. This is allowed in Ruby, if a string contains an integer, then the Succ method returns the string containing the next value of the integer. namely astring.succ=astring.to_i.succ.to_s. (Translator Note: OLD_COUNT.SUCC may be COUNT.SUCC)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.