Sending email from your app

When your app needs to send email there are a couple techniques you can use.

Use email client

You can open a new email in the default system Email client by using the mailto: prefix with System.GotoURL.

This is the simplest way to open the default Email client with the To: filled in:

ShowURL("mailto:paul@xojo.com")

You can also supply a Subject using this format:

mailto:paul@xojo.com?subject=Xojo

Which becomes this Xojo code: ShowURL("mailto:paul@xojo.com?subject=Xojo")

You can even add both a Subject and some Body text using this format:

mailto:paul@xojo.com?subject=Xojo&body=I%20love%20Xojo!

You need to use EncodeURLComponent on the subject and body in order for them to be properly received by the Email client.

iOS notes

On iOS you can use the MobileSharingPanel to allow the user to choose to send the provided text or image as an email. You cannot force the user to use email for this, however.

You can also use the ShowURL method on iOS by implementing ShowURL using Declares as shown on the iOS Declares page.

Using SMTP

To directly send email, you use the SMTPSecureSocket class. There is also a non-secure SMTPSecureSocket class but most SMTP servers are secured these days so you should just use SMTPSecureSocket.

Any SMTP server will work but you will need to configure it properly so that you can connect to it.

Gmail configuration

Many people have Gmail accounts and you can use the Gmail SMTP server to send emails as long as you do a little initial setup.

By default, Gmail has SMTP disabled as they consider SMTP “less secure” than their web interface and proprietary API. You can enable SMTP for Gmail by visiting this page when logged into your Google Account:

Enable SMTP

Turn the switch from OFF to ON.

With this enabled you can now use Gmail with port 465 and TLS security. Set this up for an SMTPSocket added to the window like this:

// Connect to Gmail
MailSocket.Address = "smtp.gmail.com"
MailSocket.Port = 465
MailSocket.ConnectionType = SMTPSecureSocket.TLSv1
MailSocket.SMTPConnectionMode = SMTPSecureSocket.ModeSSLTLS
MailSocket.Secure = True

MailSocket.Username = "YourGmailUsername"
MailSocket.Password = "YourGmailPassword"

Keep in mind that Gmail's SMTP server is not designed to send bulk email. If you are sending large amounts of email you should instead consider using a bulk email server that is designed for that purpose.

Sending a simple email

Before you can send an email, you need to create the email message. You do this using the EmailMessage class.

This example creates simple email message and then sends it using an SMTPSocket:

Var email As New EmailMessage
email.FromAddress = "paul@xojo.com"
email.Subject = "Xojo"
email.BodyPlainText = "I love Xojo!"
email.AddRecipient("hello@xojo.com")

You then set up your SMTPSocket, add the EmailMessage to it and send it. This code uses the Gmail setup code from above to send the EmailMessage:

// Connect to Gmail
MailSocket.Address = "smtp.gmail.com"
MailSocket.Port = 465
MailSocket.ConnectionType = SMTPSecureSocket.TLSv1
MailSocket.SMTPConnectionMode = SMTPSecureSocket.ModeSSLTLS
MailSocket.Secure = True

MailSocket.Username = "YourGmailUsername"
MailSocket.Password = "YourGmailPassword"

MailSocket.Password.Messages.AddRow(email)
MailSocket.Password.SendMail

The EmailMessage class has even more properties and methods to set HTML message text, headers and CC recipients.

You can also add attachments to your email using the EmailAttachment class.

Sending email from web apps

Sending Email from web apps works the same as above. However because a web app can have multiple connected users you will want to have a single SMTPSecureSocket that is shared by all of them to prevent your SMTP server from rejecting too many connections.

One way to do this is to use a Semaphore to manage the availability of the SMTPSocket.

To do this you can initialize both the Semaphore and SMTPSocket in the WebApplication.Opening event.

// Semaphore is used to ensure that only one session at a time tries
// to send an email.
MailSemaphore = New Semaphore // Mail Semaphore is a Property: MailSemaphore As Semaphore

// Global socket for sending emails
MailSocket = New SMTPSecureSocket // MailSocket is a Property: MailSocket As SMTPSecureSocket

// Map the socket's error events to methods on the App object
AddHandler MailSocket.MailSent, AddressOf MailSentHandler
AddHandler MailSocket.ServerError, AddressOf MailServerErrorHandler

Here are the method definitions for MailSentHandler and MailServerErrorHandler:

Public Sub MailSentHandler(m As SMTPSecureSocket)
  MailSocket.Release // Release the Semaphore to make the socket available for use
End Sub

Public Sub MailServerErrorHandler(m As SMTPSecureSocket, errorID As Integer, errorMessage As String, email As EmailMessage)
  MailSocket.Release // Release the Semaphore to make the socket available for use
End Sub

The only code in them is to release the Semaphore to make the socket available for use once you are done with it. You could also put other code in here for error logging for example.

You can then create a method on the App object to send the email. This method lets you pass in the To address, a Subject and Message body:

Public Sub SendMail(toAddress As String, subject As String, message As String)
  MailSemaphore.Signal

  // Connect to Gmail
  MailSocket.Address = "smtp.gmail.com"
  MailSocket.Port = 465
  MailSocket.ConnectionType = SMTPSecureSocket.TLSv1
  MailSocket.SMTPConnectionMode = SMTPSecureSocket.ModeSSLTLS
  MailSocket.Secure = True

  MailSocket.Username = Username
  MailSocket.Password = Password

  // Create EmailMessage
  Var mail As New EmailMessage
  mail.FromAddress = "paul@logicalvue.com"
  mail.AddRecipient(toAddress)
  mail.Subject = subject
  mail.BodyPlainText = message
  mail.Headers.AppendHeader("X-Mailer","SMTP Test")

  // Send it
  MailSocket.Messages.AddRow(mail)
  MailSocket.SendMail
End Sub

You can see that this code is similar to the earlier code to send an email. The only difference is the addition of the Semaphore Signal method at the beginning. If the MailSocket is currently in use, this will cause the method to wait for the MailSocket to be available.

You can then call this method from elsewhere in the web app, perhaps a web page, like this:

App.SendMail("paul@xojo.com", "Xojo", "I love Xojo!")

Sending email from iOS

You cannot use SMTPSecureSocket with iOS apps. Instead you will want your iOS app to call a web service API (that is using SMTPSecureSocket) to send the email. For example, you can modify the above web project to also handle a web service call.

In the web project, Add the HandleURL event to the App object. Put this code in it for it to handle an API call to "/Mail":

// Send an email using the provided to address, subject and message
If Request.Path = "Mail" Then
  // Convert incoming data to JSON
  Var data As String = DefineEncoding(Request.Entity, Encodings.UTF8).ToString
  Var json As New JSONItem(data)

  // Grab the parts we need
  Var email As String = json.Value("Email")
  Var subject As String = json.Value("Subject")
  Var message As String = json.Value("Message")

  // Send the email
  SendMail(email, subject, message, Nil)

  Request.Status = 200

  Return True
End If

This code call the SendMail that you already created to send the email after getting the Email address, Subject and Message from the JSON that is sent to the web service API.

In the iOS project you can call the web service. First put an URLConnection on a MobileScreen, name it eMail and call the web service like this:

Var mail As New Dictionary
mail.Value("Email") = "paul@xojo.com"
mail.Value("Subject") = "Xojo"
mail.Value("Message") = "I love Xojo!"

Var json As String
json = GenerateJSON(mail)

eMail.SetRequestContent(json, "application/x-www-form-urlencoded")

// Use the IP address of the running web app
Email.Send("POST", "http://10.0.1.32:8080/api/Mail%22)

Receiving email

To receive email, you use the POP3SecureSocket or POP3SecureSocket classes. POP3 is a protocol for downloading email messages from a server. As messages are received it MessageReceived event handler is called with the EmailMessage provides as a parameter.

POP3Socket has many events, properties and methods to allow you to receive POP3 email.

Many email services use IMAP instead of POP. If you need IMAP, consider looking into the MonkeyBread Software Plugin.

Security

You should stick to using the SMTPSecureSocket and POP3SecureSocket classes as they allow you to securely connect to their respective servers, which is required most everywhere these days.

See also

EmailAttachment, EmailHeaders, EmailMessage, POP3SecureSocket, POP3SecureSocket, SMTPSecureSocket, SMTPSecureSocket, URLConnection classes

Example Projects:

  • Example Projects/Communication/Internet/Email

Video: