Sending Email by Seth Willits
09-11-04




Sending Email
Well, we all know what email is, and it'd be cool to send it from REALbasic, and since we can, lets get straight into the code, shall we?


The Design
This is very simple project but a good one to add to the collection. The interface is shown below. There is an SMTPSocket instance named SMTPSocket1 (add this control by Right-Clicking or Control-Clicking on the Window, going to Add Control->Any->SocketCore...->TCPSocket...->SMTPSocket) and four fields named EFTo, EFFrom, EFSubject, and EFBody. The Send button is used to send the email.



The way the sending email in REALbasic is organized, is that there are three classes, EmailMessage (this holds all of the headers for the email including to, cc, bcc, from, subject, etc. as well as the body text, and even attachments), EmailAttachment (used to represent an attachment), and SMTPSocket (used to send a collection of EmailMessages to an SMTP server.

To use the SMTPSocket class we first need to set it up, giving our account information. (Note that to actually use this project you need to have an smtp server to send through.) Then we need to create a new EmailMessage instance and assign who it's being sent from, the subject, and the body text (in this case we're using plain text, but you can also use HTML and rich text). To add who we're sending it to, we use the AddRecipient method of the EmailMessage instance. The parameter to this method is either an email address alone, or one with the a name as well (ie: "Seth Willits <seth@resexcellence.com>").



And rather than an SMTPSocket having to connect to the server, send an email, and disconnect for each message, it keeps track of a list of messages to send and the list of messages is sent all at once. A list can contain only 1 email, that's fine, but it's useful if you have to send more than that. So what we do is append the message to the list of messages to send (SMTPSocket.Messages) and then call the SendMail method to send them.

As each message is sent, the MessageSent event is fired. When all mail has been sent, the MailSent event is fired.



Errors can occur in two fashions. Either the SMTPSocket can have a standard SocketCore error (like 103, 104) or the SMTP server can send us an error, telling us about any kind of unwanted event.




Finished
So, that's how you can send email with REALbasic. We didn't go over attachments or html email or anything, but this will get you started. As always, you can download the project here.