Skip to main content

%Net.SMTP

Class %Net.SMTP Extends %RegisteredObject [ System = 3 ]

For information on using this class, see Sending and Receiving Email.

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) quit

Parameters

Base64Seq

Parameter Base64Seq = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

PrintableAscii

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

Properties

localhost

Property localhost As %String(TRUNCATE = 1) [ InitialExpression = {$ZU(110)} ];

The sending host, default is $ZU(110).

port

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.

smtpserver

Property smtpserver As %String(MAXLEN = 100, TRUNCATE = 1);

the name of the SMTP server

SSLConfiguration

Property SSLConfiguration As %String;

The name of the activated TLS/SSL configuration to use for smpts requests.

UseSTARTTLS

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.

SSLCheckServerIdentity

Property SSLCheckServerIdentity As %Boolean [ InitialExpression = 1 ];

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.

IgnoreFailedAuth

Property IgnoreFailedAuth As %Boolean [ InitialExpression = 0 ];

If false (as is the default), Send() will fail if there is an authenticator present but authentication with the server fails. If true, Send() will ignore a failure to authenticate and proceed with sending without authentication. If no authenticator is present, authentication is never attempted and so this property is ignored.

timezone

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.

ShowBcc

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.

authenticator

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) quit

AuthFrom

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.

AllowHeaderEncoding

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.

Error

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.

ContinueAfterBadSend

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.

FailedSend

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.

IPVersion

Property IPVersion As %Integer [ InitialExpression = 0 ];

IPVersion specifies the versin of IP address to be used to connect SMTP server. The valid values are:
0 - Try to connect with IPV4 first if failed then try it again with IPV6.
4 - Connect to SMTP server with IPV4 address.
6 - Connect to SMTP server with IPV6 address.
All other values are treated as 0.

Status

Property Status As %Status [ Internal, Private ];

The %Status to be returned by send. Do not set directly, use SetStatus.

HeaderCharset

Property HeaderCharset As %String(TRUNCATE = 1) [ Internal, Private ];

The charset to be used for header fields

HeaderTable

Property HeaderTable As %String(TRUNCATE = 1) [ Internal, Private ];

The translate table to be used for header fields

bufcount

Property bufcount As %Integer [ InitialExpression = 1 ];

Debug

Property Debug As %Integer [ InitialExpression = 0 ];

Methods

portGet

Method portGet() As %String [ CodeMode = expression, Internal ]

Default port is 25 for plain text and 465 for SSL.

GetResponse

Method GetResponse(timeout As %Integer, ByRef responseArray As %String) As %String [ Internal, Private ]

Get response to mail command. Use timeout as specified by RFC1123.

GetEmail

Method GetEmail(s As %String) As %String [ Internal, Private ]

Get the email part of a full address.

Send

Method Send(msg As %Net.MailMessage) As %Status [ ProcedureBlock = 1 ]

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 , the value passed to the SMTP command is just email.

SendMessage

Method SendMessage(msg As %Net.MailMessage) [ Internal, Private ]

Send the mail message data to the SMTP server

Login

Method Login(ByRef authenticated As %Boolean) [ ProcedureBlock = 1 ]

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.

WriteHeader

Method WriteHeader(name As %String, text As %String) [ Internal, Private ]

Encode headers according to rules in RFC 2045.

EncodeStructuredHeader

Method EncodeStructuredHeader(header As %String, input As %String, keywords As %Boolean) As %String [ Internal, Private ]

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 [],...
  • message id (not comma separated list: ..
  • 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.

EncodeQuotedHeader

Method EncodeQuotedHeader(header As %String, input As %String) As %String [ Internal, Private ]

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.

EncodeQuotedHeaderPart

Method EncodeQuotedHeaderPart(input As %String) As %String [ Internal, Private ]

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.

EncodeHeaderPart

Method EncodeHeaderPart(header As %String, part As %String, addr As %String, first As %Boolean, termChar As %String, sepChar As %String = " ") As %String [ Private ]

endJISInASCII

Method endJISInASCII(input As %String) As %String [ Internal, Private ]

Force JIS string to end in ASCII mode per RFC 1468.

extractJIStext

Method extractJIStext(len As %Integer, ByRef text As %String, ByRef JIStext As %String) As %String [ Internal, Private ]

Extract and base64 encode enough JIS text to fill out the available space on this line.

EncodeQ

Method EncodeQ(input As %String) As %String [ Internal, Private ]

Encode header using special quoted printable encoding defined in RFC 2045 for header fields.

EncodeB

Method EncodeB(input As %String) As %String [ CodeMode = expression, Internal, Private ]

Encode header using base64 encoding

SetHeaderCharset

Method SetHeaderCharset(msg As %Net.MailMessagePart) [ Internal, Private ]

Find the translate table for any non ASCII headers

UnexpectedResponse

Method UnexpectedResponse(msg As %String, response As %String) As %String [ Internal, Private ]

Generate message for unexpected response.

zone

Method zone() As %String

Return timezone converted to RFC822 format

pad2

Method pad2(n As %String) As %String [ CodeMode = expression, Internal, Private ]

Return integer or hex padded to 2 place with leading zeros

GetStatus

Method GetStatus() As %Status [ CodeMode = expression, Internal, Private ]

Return %Status object

SetStatus

Method SetStatus(status As %Status) [ Internal, Private ]

Set Status for Send function.

zzErrorTrap

Method zzErrorTrap() As %String [ CodeMode = generator, Private ]

Error trap

OutputNoEncoding

Method OutputNoEncoding(stream As %Stream.Object) [ Internal, Private ]

Output stream to SMTP server with no encoding

EncodeStreamBase64

Method EncodeStreamBase64(stream As %Stream.Object) [ Internal, Private ]

Output stream to SMTP server with base64 encoding

Base64Encode

Method Base64Encode(b1 As %String, b2 As %String, b3 As %String) As %String [ Internal, Private ]

Base64 encode a string.

ProcessLine

Method ProcessLine(line As %String) [ Internal, Private ]

Send as many lines together as will fit in 512 byte buffer

SendMultiPart

Method SendMultiPart(msg As %Net.MailMessagePart, boundary As %String) [ Internal, Private ]

Send a, possibly multi-part, message part,

IsPartEmpty

Method IsPartEmpty(msg As %Net.MailMessagePart) As %Boolean [ Internal, Private ]

Check if message part is empty

SendMessagePart

Method SendMessagePart(msg As %Net.MailMessagePart) [ Internal, Private ]

Send a single (non multi-part message part.

EncodeStreamQuotedPrintable

Method EncodeStreamQuotedPrintable(stream As %Stream.Object) [ Internal, Private ]

Encode a stream as quoted printable and output the stream.

EncodeXtext

Method EncodeXtext(text As %String) As %String [ ProcedureBlock = 1 ]

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

AppendToOutput

Method AppendToOutput(ByRef out As %String, str As %String) [ Internal, Private ]

Append to current output line. If the line becomes longer than 75 charcaters, then start a new line.

IsAscii

ClassMethod IsAscii(stream As %Stream.Object) As %Integer [ Internal, Private ]

Scan text to see if any non-ascii chars