Tutorial on sending e-mail using net:: SMTP class in Ruby

Time:2022-5-6

Simple Mail Transfer Protocol(SMTP)SendE-mailAnd routing protocol processing between e-mail servers.

RubyIt provides the connection of simple mail transfer protocol (SMTP) client of net:: SMTP class, and provides two new methods: new and start

New takes two parameters:

  1. Server name defaults to localhost
  2. Port number defaults to 25

The start method takes these parameters:

  • Server – IP SMTP server name. The default is localhost
  • Port – port number, 25 by default
  • Domain – the domain name of the mail sender. The default is env [“hostname”]
  • Account – user name. The default is nil
  • Password – user password, which defaults to nil
  • Authtype – authorization type. The default is cram_ md5

The SMTP object has an instance method that calls sendmail, which is usually used to mail messages. It has three parameters:

  • Source – a string or array or any string returned one at a time for each iteration.
  • Sender – a string that will appear in the email field.
  • Recipients – a string or array of strings representing the address of the recipient

example:

Here is a simple way to send an email using a ruby script. Give it a try:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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, '[email protected]',
               '[email protected]'
end

A basic e-mail message has been placed here, using the file. At the same time, pay attention to the correct formatting of the title. A message needs sender, recipient and subject header separated by a blank line from the body of the email.

With the message to be sent, use net:: SMTP to connect to the SMTP server on the local machine, and then use send_ The message method takes the slave address and destination address as parameters (even if the address is within the scope of the e-mail itself, these are not always used to route the message).

If you do not have an SMTP server running on the machine, you can use the net:: SMTP remote SMTP server to communicate. Unless a webmail service (such as hotmail or Yahoo mail) is used, the email provider will provide the details of the outgoing mail server, including net:: SMTP, as follows:

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

This line of code connects to the SMTP server mail your-domain. COM port 25., No user name or password is required. However, if necessary, you can specify port number or other parameters. For example:

?
1
2
3
4
Net::SMTP.start('mail.your-domain.com',
        25,
        'localhost',
        'username', 'password' :plain)

This example connects mail your-domain. The user name and password used by com to the SMTP server are in plain text format. It is identified as the hostname of the localhost client.
Send HTML email using Ruby:

When you want to send a text message, all Ruby content will be treated as simple text. Even if HTML tags are included in the message, it will display simple text and HTML tags, and HTML syntax will not be formatted. But Ruby’s net:: SMTP provides the option of sending HTML messages by actual HTML mail.

When sending an email message, you can specify a mime version, content type and character set to send HTML email.
For example:

The following example sends HTML content as an email. Give it a try:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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, '[email protected]',
               '[email protected]'
end

Send as attachment to email:

When sending an email with mixed content, it is required to set the content type header to multipart / mixed. Then, the text and attachment sections can be specified within the boundaries.

Two hyphens followed by a unique number cannot appear at the beginning of the boundary of the message part of the email. The last boundary indicates that there must also be two hyphens at the end of the last section of the email.

The attached files are Base64 encoded using the pack (“m”) function and encoded before transmission.
example:

The following example will the file / TMP / test Txt is sent as an attachment. Give it a try:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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, '[email protected]',
             ['[email protected]'])
 end
rescue Exception => e
 print "Exception occured: " + e
end

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