RingDotNetfor Ring

E-mail messages

Build an e-mail in a program — check addresses, set the sender and the recipients, write the subject and the body, and add an HTML version next to the text. This lesson only builds messages; nothing is sent, so it runs without a mail server.

What you will learn#

The program#

samples/UsingDotNet/tutorials/ch07_mail_messages.ring
# e-mail messages - addresses, a MailMessage with several recipients, an attachment, a body in HTML and in text (nothing is sent)
load "dotnet.ring"

using {
	"System"
	"System.IO"
	"System.Net.Mail"
	"System.Net.Mime"
	"System.Text"
}

func main

	# 1. MailAddress reads "Name <user@host>" and splits it. A wrong address raises an error, so it is a check too.
	oAddress = new MailAddress("Ann Lee <ann.lee@example.com>")
	? "1. display name: " + oAddress.DisplayName
	? "   user: " + oAddress.User + ", host: " + oAddress.Host + ", address: " + oAddress.Address
	for cText in ["bob@example.com","bob@","bob@@example.com","@example.com"]
		? "   '" + cText + "' is an address: " + isAddress(cText)
	next

	# 2. A message: from, to, cc, subject and body. Nothing is sent here: SmtpClient.Send would do that with a server.
	oMessage = new MailMessage()
	oMessage.From = new MailAddress("Ann Lee <ann.lee@example.com>")
	oMessage.To.Add("bob@example.com")
	oMessage.To.Add("Carla <carla@example.com>")
	oMessage.CC.Add("boss@example.com")
	oMessage.Subject = "Meeting on Friday"
	oMessage.Body = "Hello," + nl + "the meeting is on Friday at 10:00." + nl + "Ann"
	? nl + "2. from: " + oMessage.From.Address
	? "   to: " + oMessage.To.Count + " people, cc: " + oMessage.CC.Count + " person"
	aPersons = oMessage.To.toList()
	for oPerson in aPersons
		? "      " + oPerson.DisplayName + " <" + oPerson.Address + ">"
	next
	? "   subject: " + oMessage.Subject
	? "   body is HTML: " + oMessage.IsBodyHtml

	# 3. HTML with a text version: AlternateViews hold the same message in more than one form, and the mail program shows the best one
	oText = (new AlternateView).CreateAlternateViewFromString([ :content = "Meeting on Friday at 10:00", :contentEncoding = dnNull(), :mediaType = "text/plain" ])
	oHtml = (new AlternateView).CreateAlternateViewFromString([ :content = "<p>Meeting on <b>Friday</b> at 10:00</p>", :contentEncoding = dnNull(), :mediaType = "text/html" ])
	oMessage.AlternateViews.Add(oText)
	oMessage.AlternateViews.Add(oHtml)
	? nl + "3. views: " + oMessage.AlternateViews.Count + " (" + oText.ContentType.MediaType + ", " + oHtml.ContentType.MediaType + ")"

# A text is an address when MailAddress accepts it (a wrong one raises an error)
func isAddress cText

	try
		new MailAddress(cText)
		return True
	catch
		return False
	done
Output
1. display name: Ann Lee
   user: ann.lee, host: example.com, address: ann.lee@example.com
   'bob@example.com' is an address: 1
   'bob@' is an address: 0
   'bob@@example.com' is an address: 0
   '@example.com' is an address: 0

2. from: ann.lee@example.com
   to: 2 people, cc: 1 person
       <bob@example.com>
      Carla <carla@example.com>
   subject: Meeting on Friday
   body is HTML: 0

3. views: 2 (text/plain, text/html)
Note

This program uses a few generic functions (dnStatic, dnNull) where a class cannot be used. The lesson The generic functions explains them.

How it works#

Addresses#

new MailAddress("Ann Lee <ann.lee@example.com>") splits the text into DisplayName, User, Host and Address. A text that is not an address raises an error, so the function isAddress uses try / catch (the tutorial When things go wrong) to turn the error into a yes or no. The check is about the form (user@host); it cannot know whether the mailbox exists. bob@ and @example.com are refused, bob@example.com is accepted.

Note

.NET is generous with display names: bob example@x.com is read as the name bob and the address example@x.com. If your program needs exactly one address in a text box, also compare oAddress.Address with the text.

The message#

MailMessage has the parts of a letter: From, To, CC, Bcc, Subject and Body. To and CC are collections (MailAddressCollection): Add takes an address text, with or without a display name, and Count and toList() read them back. IsBodyHtml says how the mail program should show Body; the default is plain text.

Properties named like Ring words#

From and To are words of the Ring language (from is used in class X from Y, to in for i = 1 to 10). Ring accepts them as the name of an attribute or a method after a dot, so oMessage.From = ... and oMessage.To.Add(...) work like any other property. Some other words are reserved there (get, and, or, not, next, end, if, for, new, load, call, put, give, see); a .NET method with such a name gets an @ at the start (@Next), and a property with such a name is read with getProp and setProp (Core concepts, Plain objects).

Text and HTML together#

A mail with HTML is shown badly by programs that only show text. The solution is two alternate views of the same message: the plain one and the HTML one; the receiving program shows the best one it can. AlternateView has no public constructor for a text, only a static method, CreateAlternateViewFromString(text, encoding, mediaType), which is called with dnStatic(type, method, [arguments]) (the encoding is dnNull() for the default).

Sending#

SmtpClient connects to a mail server and sends a message (Send). It needs a server name, a port, a user and a password, and real recipients, so it is not part of a lesson that must run anywhere. Notes for your own program: use port 587 with EnableSsl = True, never write the password in the source (read it from the environment or a settings file, the tutorial Settings), and check with a test server or a test account first. Microsoft recommends a library such as MailKit for new programs, because SmtpClient is limited.

What you learned#

Exercises#

  1. Write addressList(cText) that splits a@x.com; b@y.com into a list of MailAddress objects and skips the wrong ones.
  2. Add a Bcc recipient and print all the recipients of the mail.
  3. Add an attachment (Attachments.Add) made from a file of the tutorial Files and folders and print its name.
  4. Read about MailMessage.Headers and add the header X-Mailer.

Where to go next#

This was the last tutorial of the chapter Networking and the web. The next chapter is Security: it starts with Protecting and signing messages. The Tutorials page lists all the chapters, and you can start any of them.

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.