Use Ruby to send and receive emails

Source: Internet
Author: User

1. Send email via SMTP

Every week, Holden Glova, Pat eyler, and Phil Thomson submit a ruby Weekly News (RWN) article to the ruby garden website (http://www.rubygarden.org. A ruby script receives this article via email, converts it from the original XML format to HTML and plain text format, and then publishes the HTML format to the website, then, the article in plain text format is sent to the Mail list. If there is any problem in the middle (for example, the XML document structure is incorrect), this script will send an email containing the error message to the sender.

This script is usedNet: SMTP(Simple Mail Transfer Protocol) Library sends an email. Listing 1 is the email sending method in this script. This method receives three parameters: email address, title, and email content. Because this program is used in various control environments, some attributes such as the sender and Email Forwarding hosts are defined as global constants rather than parameters.

Listing 1: sending emails through 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            msg1011     Net::SMTP.start(SMTP_HOST) do |smtp|12       smtp.send_mail(mail, FROM_ADDRESS,13         [ to, 'rurl_archive@zip.local.pragprog.com' ])14     end15   end

An email message consists of two parts: an envelope (Envelope) And content (Content). Envelope tells SMTP proxy (SendmailOrPostfix) How to deliver messages. The content includes the message itself that can be read and some headers (such as message subject), while some headers in the content may be duplicated (such as "to" Address) in envelope ), these repeated headers are used for display, while envelope is used for delivery. (That's why you receive a "to" address that is not your spam)

You can see that the reply method has separated envelop and content, and lines 5th to 9th have generated content, which includes three headers: to, from, subject, then, the message content is added to the end of an empty line. Note that the header before the body content must be followed by a carriage return line break, that is, a combination of "/R" and "/N.

MethodNet: SMTP. StartConnect to the MTA (Mail Transfer Agent). One Parameter of this method is the name of the machine that runs the MTA and the default port (25) is used ), this method returns an object used to interact with the MTA, and transmits this object as a parameter to the block (Lines 11 to 13 ). When block is used, the connection can be closed after the block ends.

In our example, the interaction process is very simple. The 12th-line program only sent the content of the email that sent the sword just now.

The second parameter of the send_mail method is the FROM address, which is a global variable. The third parameter is an array containing the receiver address. Here we send this message to two places, one parameter specified to, and one local mailbox for archiving all messages.

 


2. Use Pop to receive and read emails

It is very easy to use Ruby to receive emails from the POP server. Suppose we want to love people in a variety of languages. people participating in the survey can send an email titled I like XXXXX to a specific address. Xxxxx is the name of the language that the sender prefers. The ruby script in listing 3 is used to receive and compute results from the POP server, and store the number of likes in each language in a common file, one file in each language.

 

Listing 3: 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     end1112     count = (File.read(language) rescue "0")13     File.open(language, "w") {|f| f.puts old_count.succ}14   end

The POP server stores user messages. When you finish reading a message, you can delete the message or store it on the server. In our example, we will delete it after reading it. Fortunately, Ruby provides a very convenient iteratorDelete_allIt extracts mails one by one and deletes them after processing.Delete_allThe required parameters include the address and port of the POP server (the standard port is 110), and the user name and password.

After this method starts, it will connect to the server with the specified parameter, get the user's email one by one, and then each time this letter (asNet: PopmailObject) to the given block for processing. After the block completes processing the letter, it will be deleted.

In this block, all the headers of the 5th line will be extracted and put into a string. Then, use a regular expression in row 6th to search for a similarI likeXxxxRow, locate the language represented by XXXX, and update the count of the language selected by the voter in the 12 and 13 lines.

 

Row 12th has an interesting structure. Every time we get a vote for a language, we use a file to store the number of votes in this language. We can read this value, add it, and write it back to the file. However, when someone voted for a language for the first time, this file does not exist. When we read this file, we will get an exception. Fortunately, Ruby provides an exception mechanism (keyword rescue ), however, when an exception occurs, it may be because the file does not exist. Therefore, if this exception is caught, a default value 0 is returned, indicating that the number of votes in this language is 0.

The other tips are 13th rows.Old_count.succTo add a string. This is allowed in Ruby. If a string contains an integer, The succ method returns the string containing the next value of this integer. That is, astring. succ = astring. to_ I .succ.to_s.

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.