Sending E-mail with Ruby

I know that there are a number of guides online that provide the basic source for sending email using Ruby but I found that the basic sample code was lacking in one major respect – it did not set the date on the outgoing email. That meant that there was no specific “sent time” for the email and its treatment would depend on the email client. For example, Thunderbird would mark it with the date/ time at which it was downloaded.

The solution to this problem is really quite simple – you just need to format and print the date into the message as shown below on Line 26 – this uses strftime to formatting the time output on Line 22. You can change the time to another time/ time zone if that makes sense in your use case.

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
require 'net/smtp'

#Senders and Recipients
from_name = 'My Name'
from_mail = 'me@mydomain.com'
to_name = 'My Friend'
to_mail = 'them@theirdomain.com'

#Servers and Authentication
smtp_host   = 'mail.mydomain.com'
smtp_port   = 25
smtp_domain = 'mydomain.com'
smtp_user   = 'user@mydomain.com'
smtp_pwd    = 'secure_password'

#The subject and the message
t = Time.now
subj = 'Sending Email with Ruby'
msg_body = "Check out the instructions on how to send mail using Ruby.\n"

#The date/time should look something like: Thu, 03 Jan 2006 12:33:22 -0700
msg_date = t.strftime("%a, %d %b %Y %H:%M:%S %z")

#Compose the message for the email
msg = <<END_OF_MESSAGE
Date: #{msg_date}
From: #{from_name} <#{from_mail}>
To: #{to_name} <#{to_mail}>
Subject: #{subj}
  
#{msg_body}
END_OF_MESSAGE

Net::SMTP.start(smtp_host, smtp_port, smtp_domain, smtp_user, smtp_pwd, :plain) do |smtp|
  smtp.send_message msg, smtp_user, to_mail
end

And that’s all there is to it – hope this helps!

Note: this post is migrated from my earlier website.

comments powered by Disqus