Ruby sending email - SMATP


SMTP (Simple Mail Transfer Protocol) is a simple mail transfer protocol. It is a set of rules for transmitting mail from a source address to a destination address. It controls the transfer method of letters.

Ruby provides Net::SMTP to send emails, and provides two methods new and start:

new The method has two parameters:

  • server name Default is localhost

  • port number Default is 25

start The method has the following parameters:

  • server - SMTP server IP, default is localhost

  • port - Port number, default is 25

  • domain - Email sender domain name, default is ENV["HOSTNAME "]

  • account - username, default is nil

  • password - user password , default is nil

  • authtype - Authentication type, default is cram_md5

SMTP object The instantiation method calls sendmail with the following parameters:

  • source - a string or array or whatever each iterator returns at any one time.

  • #sender - A string that appears in the email form field.

  • recipients - A string or array of strings representing the recipient's address.

Example

The following provides a simple Ruby script to send an email:

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


In the above example, you have Set up a basic email message, paying attention to proper header formatting. An email requires From, To and Subject, and a blank line between the text content and the header information.


Use Net::SMTP to connect to the SMTP server on the local machine, and use the send_message method to send emails. The method parameters are the sender's email and the recipient's email.

If you do not have an SMTP server running on your local machine, you can use Net::SMTP to communicate with a remote SMTP server. If using a webmail service (such as Hotmail or Yahoo Mail), your email provider will provide you with the details of the outgoing mail server:

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

The above code will connect the host to mail.your-domain.com , the mail server with port number 25, if you need to fill in the username and password, the code is as follows:


Net::SMTP.start('mail.your-domain.com', 
                25, 
                'localhost', 
                'username', 'password', :plain)

The above example uses the specified username and password to connect to the host as mail .your-domain.com, mail server with port number 25.


Use Ruby to send HTML emails

Net::SMTP also provides support for sending emails in HTML format.

When sending emails, you can set the MIME version, document type, and character set to send emails in HTML format.

Examples

The following examples are used to send emails in HTML format:

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 an e-mail message to be sent in HTML format

<b>This is HTML message.</b>
<h1>This is headline.</h1>
MESSAGE_END

Net::SMTP.start('localhost') do |smtp|
  smtp.send_message message, 'me@fromdomain.com', 
                             'test@todomain.com'
end

Send emails with attachments

If you need to send mixed content For email, you need to set Content-type to multipart/mixed. This will allow you to add attachment content to the email.

Attachments need to use the pack("m") function to convert their contents to base64 format before transmission.

Example

The following example will send an email with the attachment /tmp/test.txt:

require 'net/smtp'

filename = "/tmp/test.txt"
# 读取文件并编码为base64格式
filecontent = File.read(filename)
encodedcontent = [filecontent].pack("m")   # base64

marker = "AUNIQUEMARKER"

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

# 定义主要的头部信息
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

# 定义消息动作
part2 =<<EOF
Content-Type: text/plain
Content-Transfer-Encoding:8bit

#{body}
--#{marker}
EOF

# 定义附件部分
part3 =<<EOF
Content-Type: multipart/mixed; name=\"#{filename}\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{filename}"

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

mailtext = part1 + part2 + part3

# 发送邮件
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 to send Addresses must be separated by commas.