Open Exchange
Global Masters
Home / Class Reference / %SYS namespace / %Net.SMTP
Private  Storage   


class %Net.SMTP extends

Send a SMTP mail message

The Charset property of each %Net.MailMessagePart determines the charset for text MIME parts. The charset property is ignored unless ContentType=text/... Charset sets the Character Set for the content-type header. IMPORTANT: Charset must be set before any data is written to the TextData stream associated with this %Net.MailMessagePart. The Charset may also be initialized when the message is created by ##Class(%Net.MailMessagePart).%New(charset) or ##Class(%Net.MailMessage).%New(charset). For Unicode locale the default Charset for ##Class(%Net.SMTP).%New() is utf-8.

	#include %occOptions
	#include %occStatus
	testmailsend3 ;
	;  Replace information marked with [[ ]]
	new attached,err,m,nestedm,s,status
	set s=##class(%Net.SMTP).%New()
	set s.smtpserver=[["SMTP server name"]]
	set s.timezone=[["-0400"]]  may remove this line to get Universal Time
	set m=##class(%Net.MailMessage).%New()
	set m.From=[["test@company.com"]]
	// Either address with name or just email address supported.
	do m.To.Insert([["receiver@another.com"]])
	do m.To.Insert([["Joe Smith <jsmith@another.com>"]])
	write !,"s.port="_s.port
	write !,"s.localhost="_s.localhost
	set m.Subject="Sent by InterSystems IRIS mail"
	set m.Charset="iso-8859-1"
	set status=m.TextData.Write("This is the main body.")
	if $$$ISERR(status) do $system.OBJ.DisplayError(status) quit
	set status=m.TextData.Write($char(13,10))
	if $$$ISERR(status) do $system.OBJ.DisplayError(status) quit
	set status=m.TextData.Write("This is the second line.")
	if $$$ISERR(status) do $system.OBJ.DisplayError(status) quit
	set status=m.TextData.Write($char(13,10))
	if $$$ISERR(status) do $system.OBJ.DisplayError(status) quit
	set status=m.AttachFile("c:\winnt","notepad.exe")
	if $$$ISERR(status) do $system.OBJ.DisplayError(status) quit
	// Attach a text file with charset=iso-8859-1
	set status=m.AttachFile("d:\temp","test.txt",0,"iso-8859-1")
	if $$$ISERR(status) do $system.OBJ.DisplayError(status) quit
	set nestedm=m.AttachNewMessage()
	// Attach a binary file
	set status=nestedm.AttachFile("c:\irissys\bin","test.bin")
	if $$$ISERR(status) do $system.OBJ.DisplayError(status) quit
	write !,"m.Parts.Count()="_m.Parts.Count()
	write !,"m.Parts.GetAt(3).Parts.GetAt(1).FileName="_m.Parts.GetAt(3).Parts.GetAt(1).FileName
	write !,"m.Parts.GetAt(3).Parts.Count()="_m.Parts.GetAt(3).Parts.Count()
	set status=s.Send(m)
	if $$$ISERR(status) do $system.OBJ.DisplayError(status)


Parameters Properties Methods Queries Indices ForeignKeys Triggers
2 19 33


AllowHeaderEncoding AuthFrom ContinueAfterBadSend Debug
Error FailedSend SSLCheckServerIdentity SSLConfiguration
ShowBcc UseSTARTTLS authenticator bufcount
localhost port smtpserver timezone

%%OIDGet %AddToSaveSet %BindExport %BuildObjectGraph
%ClassIsLatestVersion %ClassName %Close %ConstructClone
%DispatchClassMethod %DispatchGetModified %DispatchGetProperty %DispatchMethod
%DispatchSetModified %DispatchSetMultidimProperty %DispatchSetProperty %Extends
%GetParameter %IncrementCount %IsA %IsModified
%New %NormalizeObject %ObjectModified %OriginalNamespace
%PackageName %RemoveFromSaveSet %SerializeObject %SetModified
%ValidateObject EncodeXtext Login Send
portGet zone


• parameter Base64Seq = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
• parameter PrintableAscii = " !""""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~";


• property AllowHeaderEncoding as %Boolean [ InitialExpression = 1 ];
If true, the Send method will encode non-ASCII header text according to the rules specified by RFC 2047. This is the default. Some mail readers do not accept the encoding specified by RFC 2047 and thus we allow disabling this encoding by setting AllowHeaderEncoding=false.
• property AuthFrom as %String(MAXLEN=255,TRUNCATE=1);
AuthFrom specifies the address to be used for the AUTH parameter of the MAIL FROM SMTP command for SMTP authenticated session. If specified, this property will be the argument of the AUTH= extension to the MAIL FROM command. This property may be specified as "<>" to indicate that the original submitter of the messge is not known.
• property ContinueAfterBadSend as %Boolean [ InitialExpression = 0 ];
If true, sending the email will continue if a send fails and failed email addresses will be added to the FailedSend list.
• property Debug as %Integer [ InitialExpression = 0 ];
• property Error as %String(MAXLEN=255,TRUNCATE=1);
If Send is called and returns an error status, the error message is in the Error property.
• property FailedSend as list of %String(MAXLEN=8000,TRUNCATE=1);
A list of email addresses for which the Send failed. If the Send for any address is successful, then a %Status of $$$OK is returned by Send and this list contains any failed addresses. If Send is not successful for any email address, then an %Status of $$$SMTPNoSend and all address on this list. Use (sender.FailedSend.Count()=0) to test if all sends succeeded.
• property HeaderCharset as %String(TRUNCATE=1) [ Private ];
The charset to be used for header fields
• property HeaderTable as %String(TRUNCATE=1) [ Private ];
The translate table to be used for header fields
• property SSLCheckServerIdentity as %Boolean [ InitialExpression = 0 ];
When making an SSL connection check the server identity in the server certificate matches the name of the system we are connecting to. This defaults to being on and matches based on the rules layed out in section 3.1 of RFC 2818.
• property SSLConfiguration as %String;
The name of the activated TLS/SSL configuration to use for smpts requests.
• property ShowBcc as %Boolean;
If ShowBcc = true (1), then Bcc headers will be written to the email message. The Bcc headers will usually be filtered out by the SMTP server.
• property Status as %Status [ Private ];
The %Status to be returned by send. Do not set directly, use SetStatus.
• property UseSTARTTLS as %Boolean;
If true then the STARTTLS extension to SMTP (RFC 3207) should be used to authenticate to the SMTP server on the normal SMTP port. The SSLConfiguration must be specified.
• property authenticator as %Net.Authenticator;
To do SMTP authentication with the SMTP server (as defined by RFC 2554), instantiate a %Net.Authenticator object, set UserName and Password properties of the authenticator and assign it to this property. An example of the use of authenticator follows.
	#include %occOptions
	#include %occStatus
	authtestmailsend ;
	;  Replace information marked with [[ ]]
	new auth,m,s,status
	set s=##class(%Net.SMTP).%New()
	set auth=##class(%Net.Authenticator).%New() ; use default authentication list
	set auth.UserName=[["myUser"]]
	set auth.Password=[["myPassword"]]
	set s.authenticator=auth
	set s.smtpserver=[["SMTP server name"]]
	set s.timezone=[["-0400"]]  may remove this line to get Universal Time
	set m=##class(%Net.MailMessage).%New()
	set m.From=[["test@company.com"]]
	do m.To.Insert([["receiver@another.com"]])
	do m.To.Insert([["Joe Smith <jsmith@another.com>"]])
	set m.Subject="Sent by InterSystems IRIS mail"
	set m.Charset="iso-8859-1"
	do m.TextData.Write("This message has been sent using an SMTP server with Authentication.")
	set status=s.Send(m)
	if $$$ISERR(status) do $system.OBJ.DisplayError(status)
• property bufcount as %Integer [ InitialExpression = 1 ];
• property localhost as %String(TRUNCATE=1) [ InitialExpression = $ZU(110) ];
The sending host, default is $ZU(110).
• property port as %String(MAXLEN=100,TRUNCATE=1);
The port of the SMTP server, the default is 25 for plain text and 465 for SSL.
• property smtpserver as %String(MAXLEN=100,TRUNCATE=1);
the name of the SMTP server
• property timezone as %String(MAXLEN=100,TRUNCATE=1);
timezone as specified by RFC822, for example "EST", "PDT", "-0400". If timezone is "LOCAL", then the local timezone expressed as "+nnnn" or "-nnnn" is used. If timezone is not set, then "UT" is used for the timezone and universal time is used in the message.


• private method AppendToOutput(ByRef out As %String, str As %String)
Append to current output line. If the line becomes longer than 75 charcaters, then start a new line.
• private method Base64Encode(b1 As %String, b2 As %String, b3 As %String) as %String
Base64 encode a string.
• private method EncodeB(input As %String) as %String
Encode header using base64 encoding
• private method EncodeHeaderPart(header As %String, part As %String, addr As %String, first As %Boolean, termChar As %String, sepChar As %String = " ") as %String
• private method EncodeQ(input As %String) as %String
Encode header using special quoted printable encoding defined in RFC 2045 for header fields.
• private method EncodeQuotedHeader(header As %String, input As %String) as %String
Handle the structured headers in RFC 2045 that contain quoted strings which may be encoded, but no other part of the header is encoded.
Return the encoded header.
• private method EncodeQuotedHeaderPart(input As %String) as %String
Handle the ; separated parts of the structured headers in RFC 2045 that contain quoted strings which may be encoded, but no other part of the header is encoded.
Return the encoded header part.
• private method EncodeStreamBase64(stream As %Stream.Object)
Output stream to SMTP server with base64 encoding
• private method EncodeStreamQuotedPrintable(stream As %Stream.Object)
Encode a stream as quoted printable and output the stream.
• private method EncodeStructuredHeader(header As %String, input As %String, keywords As %Boolean) as %String
Handle of large subset of encoding required for structured headers in RFC 2045.
Return the encoded header.
The following formats are supported:
  • address comma separated list: display [<addr>],...
  • message id (not comma separated list: <addr> ..
  • keyword comma separated list: display, ...
keyword list is different from address list because display part
of address list part is considered an address if no address is specified.
Parenthesized comments are not supported for any of these formats.
• method EncodeXtext(text As %String) as %String
xtext encoding is defined in RFC 1891 as:

"xtext" is formally defined as follows:
xtext = *( xchar / hexchar )
xchar = any ASCII CHAR between "!" (33) and "~" (126) inclusive, except for "+" and "=".
;"hexchar"s are intended to encode octets that cannot appear
;as ASCII characters within an esmtp-value. hexchar = ASCII "+" immediately followed by two upper case hexadecimal digits

• private method GetEmail(s As %String) as %String
Get the email part of a full address.
• private method GetResponse(timeout As %Integer, ByRef responseArray As %String) as %String
Get response to mail command. Use timeout as specified by RFC1123.
• private method GetStatus() as %Status
Return %Status object
• private classmethod IsAscii(stream As %Stream.Object) as %Integer
Scan text to see if any non-ascii chars
• private method IsPartEmpty(msg As %Net.MailMessagePart) as %Boolean
Check if message part is empty
• method Login(ByRef authenticated As %Boolean)
Setup session with the SMTP server. We will use the EHLO command and SMTP authentication as supplied by the authenticator property where possible. If EHLO is not accepted or authentication fails, we will attempt to use the HELO command.
• private method OutputNoEncoding(stream As %Stream.Object)
Output stream to SMTP server with no encoding
• private method ProcessLine(line As %String)
Send as many lines together as will fit in 512 byte buffer
• method Send(msg As %Net.MailMessage) as %Status
Used to send msg to SMTP server.

Returns a %Status to indicate success or failure.

The send supports the following small subset of permissible message header fields. Set the corresponding MailMessage properties before invoking send.

  • Date - set from msg.Date; will be set to the current date and time if not specified
  • From - set from msg.From
  • Subject - set from msg.Subject
  • To - set from msg.To by converting to "," separated list
  • Cc - optionally set from msg.Cc by converting to "," separated list
  • Bcc - optionally set from msg.Bcc by converting to "," separated list
  • Sender - optionally set from msg.Sender
  • Reply-To - optionally set from msg.ReplyTo

The "MAIL FROM:" SMTP command uses the Sender field if specified, otherwise the From field.
The "RCPT TO:" SMTP command uses the To and Cc lists joined by commas.
simple e-mail address must be passed to MAIL and RCPT. Therefore if the address is of the form name <email>, the value passed to the SMTP command is just email.

• private method SendMessage(msg As %Net.MailMessage)
Send the mail message data to the SMTP server
• private method SendMessagePart(msg As %Net.MailMessagePart)
Send a single (non multi-part message part.
• private method SendMultiPart(msg As %Net.MailMessagePart, boundary As %String)
Send a, possibly multi-part, message part,
• private method SetHeaderCharset(msg As %Net.MailMessagePart)
Find the translate table for any non ASCII headers
• private method SetStatus(status As %Status)
Set Status for Send function.
• private method UnexpectedResponse(msg As %String, response As %String) as %String
Generate message for unexpected response.
• private method WriteHeader(name As %String, text As %String)
Encode headers according to rules in RFC 2045.
• private method endJISInASCII(input As %String) as %String
Force JIS string to end in ASCII mode per RFC 1468.
• private method extractJIStext(len As %Integer, ByRef text As %String, ByRef JIStext As %String) as %String
Extract and base64 encode enough JIS text to fill out the available space on this line.
• private method pad2(n As %String) as %String
Return integer or hex padded to 2 place with leading zeros
• method portGet() as %String
Default port is 25 for plain text and 465 for SSL.
• method zone() as %String
Return timezone converted to RFC822 format
• private method zzErrorTrap() as %String
Error trap