Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Ruby Sends Mail - SMTP


May 12, 2021 Ruby


Table of contents


Ruby Sends Mail - SMATP

Simple Mail Transfer Protocol, a simple messaging protocol, is a set of rules used to deliver messages from the source address to the destination address, which controls how letters are transited.

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

  • The new method has two parameters:
    • Server name defaults to localhost
    • Port number defaults to 25
  • The start method has the following parameters:
    • Server - SMTP server IP, localhost by default
    • port - Port number, default to 25
    • domain - mail sender domain name, default to ENV ("HOSTNAME")
    • account - user name, nil by default
    • password - user password, the default is nil
    • authtype - Validation type, which defaults to cram_md5

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

  • Source - Anything returned by a string or array or by each iterator at any one time.
  • Sender - A string that appears in the form field of the email.
  • recipients - an array of strings or strings that represent the address of the recipient.

Instance

Here's a simple Ruby script to send a message:

require 'net/smtp'

message = <<MESSAGE_END From: Private Person <[email protected]>
To: A Test User <[email protected]>
Subject: SMTP e-mail test

This is a test e-mail message.
MESSAGE_END

Net::SMTP.start('localhost') do |smtp|
  smtp.send_message message, '[email protected]', 
                             '[email protected]'
end

In the above example, you've set up a basic e-mail message, paying attention to the correct title format. An e-mail message requires an empty line between the text content and the header message, from From, To, and Subject.

Using Net:: SMTP connects to the SMTP server on the local machine and uses send_message methods to send messages, with the method parameters for sender messages and recipient messages.

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

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

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

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

The above instance uses the specified username password to connect to a mail.your-domain.com server with a port number of 25.


Use Ruby to send HTML messages

Net:: SMTP also provides support for sending HTML messages.

When sending e-mail, you can set the MIME version, document type, character set to send HTML-formatted messages.

Instance

The following examples are used to send HTML-formatted messages:

require 'net/smtp'

message = <<MESSAGE_END From: Private Person <[email protected]>
To: A Test User <[email protected]>
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, '[email protected]', 
                             '[email protected]'
end

Send a message with attachments

If you need to send mixed content e-mail, you need to set TheContent-type to multipart/mixed. This allows you to add attachment content to your message.

Attachments need to use the pack ("m") function to convert their contents to base64 format before they can be transferred.

Instance

The following instance sends a message with an attachment of .txt /tmp/test:

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, '[email protected]',
                          ['[email protected]'])
  end
rescue Exception => e  
  print "Exception occured: " + e  
end  

Note: You can specify multiple send addresses, but you need to separate them with commas.