Tutorial on using the NET::SMTP class to send e-mail in ruby _ruby topics

Source: Internet
Author: User
Tags base64 character set html tags instance method mixed pack port number


Simple Mail Transfer Protocol (SMTP) sends e-mail messages and routes the protocol processing between e mail servers.



Ruby provides a connection to the Simple Mail Transfer Protocol (SMTP) client of the Net::smtp class, and provides two new ways to start.



New with two parameters:


    1. Server name defaults to localhost
    2. Port number defaults to the well-known 25


The Start method carries the following parameters:


    • Server-ip SMTP server name, default is localhost
    • Port-port number, defaults to 25
    • Domain-the name of the sender of the message, default to env["HOSTNAME"]
    • Account-Username, default to nil
    • Password-user password, default is nil
    • AuthType-Authorization type, default is CRAM_MD5


The SMTP object has an instance method invocation SendMail, which is usually used to do the work of mailing messages. It has three parameters:


    • Source-a string or array or any of the same iterations that return one string at a time.
    • Sender-A string that will appear in the E-mail field.
    • Recipients-a string or array of strings representing the addresses of the recipients


Example:



Here's a simple way to use Ruby script to send an e-mail message. Let's try it once:


require 'net/smtp'

message = <<MESSAGE_END
From: Private Person <me@fromdomain.com>
To: A Test User <test@todomain.com>
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@fromdomain.com', 
               'test@todomain.com'
end


Here you have placed a basic email message, using the file, where you pay attention to the correct formatting of the title. A message requires a sender, a recipient, a topic header, and a blank line separated from the body of the e-mail message.



As messages are sent using NET::SMTP to connect to the SMTP server on the local machine, and then use the Send_message method, from the address, destination address as a parameter (even within the address e-mail itself, these are not always used to route messages).



If you have not yet run an SMTP server on the machine, you can use the NET::SMTP remote SMTP server to communicate. Unless using a webmail service (such as Hotmail or Yahoo Mail), the email provider will provide details of the outgoing mail server, which can be net::smtp as follows:


Net::smtp.start (' mail.your-domain.com ')


This line of code connects to the SMTP server mail.your-domain.com port 25. Without using any user name or password. However, you can specify a port number or other parameters, if necessary. For example:


Net::smtp.start (' mail.your-domain.com ',, 
        ' localhost ', ' 
        username ', ' password ':p lain)


This example connects mail.your-domain.com to the SMTP server using the username and password in plain text format. It is identified as the host name for the localhost client.
To send an HTML e-mail message using Ruby:



When you want to send a text message, Ruby All content will be treated as simple text. Even if you include HTML tags in your text message, it will display simple text and HTML tags that will not format HTML syntax. But Ruby's NET::SMTP provides an option for the actual HTML message to send HTML messages.



When sending an e-mail message, you can specify a MIME version, a content type, and a character set to send HTML e-mail messages.
For example:



The following example sends HTML content as an e-mail message. Let's try it once:


Require ' net/smtp ' message

= <<message_end
from:private person <me@fromdomain.com>
to:a Test User <test@todomain.com>
mime-version:1.0
content-type:text/html
subject:smtp e-mail test

This is a e-mail message to was sent in HTML format

<b>this was HTML message.</b>


To send as an attachment to an e-mail message:



Mixed content sends an e-mail message requiring the Content-type header to be set to multipart/mixed. The text and attachment sections can then be specified within the boundaries range.



Two hyphens followed by a unique number that cannot appear at the boundary of the message portion of the e-mail. The last boundary indicates that the end of the last section of an e-mail message must also have two hyphens.



Additional files use the pack ("M") function to encode Base64 encoded transmissions.
Example:



The following example sends the file/tmp/test.txt as an attachment. Let's try it once:



require 'net/smtp'

filename = "/tmp/test.txt"
# Read a file and encode it into base64 format
filecontent = File.read(filename)
encodedcontent = [filecontent].pack("m")  # base64

marker = "AUNIQUEMARKER"

body =<<EOF
This is a test email to send an attachement.
EOF

# Define the main headers.
part1 =<<EOF
From: Private Person <me@fromdomain.net>
To: A Test User <test@todmain.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=#{marker}
--#{marker}
EOF

# Define the message action
part2 =<<EOF
Content-Type: text/plain
Content-Transfer-Encoding:8bit

#{body}
--#{marker}
EOF

# Define the attachment section
part3 =<<EOF
Content-Type: multipart/mixed; name=\"#{filename}\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{filename}"

#{encodedcontent}
--#{marker}--
EOF

mailtext = part1 + part2 + part3

# Let's put our code in safe area
begin 
 Net::SMTP.start('localhost') do |smtp|
   smtp.sendmail(mailtext, 'me@fromdomain.net',
             ['test@todmain.com'])
 end
rescue Exception => e 
 print "Exception occured: " + e 
end 


Note: You can specify multiple destination internal arrays, but they need to be separated by commas.





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.