Chapter 5 adding attachments to emails

Posted by eth0g on Tue, 08 Feb 2022 20:21:51 +0100

Chapter 5 adding attachments to emails

Add attachments to messages

Attachments can be added to an email or message part (specifically, to an instance of% Net.MailMessagePart or% Net.MailMessage). To do this, use the following method:

Each of these methods adds an attachment to the Parts array of the original message (or part of the message) and automatically sets the IsMultiPart property to 1.

AttachFile()

method AttachFile(Dir As %String, 
                  File As %String, 
                  isBinary As %Boolean = 1, 
                  charset As %String = "", 
                  ByRef count As %Integer) as %Status

Attach the given file to the email. By default, files are sent as binary attachments, but you can specify them as text. If the file is text, you can also specify the character set used by the file.

Specifically, this method creates% net An instance of mailmessagepart, put the file content in BinaryData or TextData attribute as needed, and set CharSet attribute and TextData as needed Translatetable property. This method returns by reference an integer indicating the position of the new message part in the part array.

This method also sets the Dir and FileName properties of the message or message part.

AttachStream()

method AttachStream(stream As %Stream.Object, 
                    Filename As %String, 
                    isBinary As %Boolean = 1, 
                    charset As %String = "", 
                    ByRef count As %Integer) as %Status

Attach the given stream to the email. If Filename is specified, the attachment is considered a file attachment. Otherwise, it will be treated as an inline attachment.

AttachNewMessage()

method AttachNewMessage() as %Net.MailMessagePart

Create% net A new instance of mailmessage, add it to the message, and return the newly modified parent message or message part.

AttachEmail()

Given an e-mail message (% instance of Net.MailMessage), this method will add it to the message. This method also sets the Dir and FileName properties of the message or message part.

Set this method to "content82rf2". In this case, no other attachments can be added.

Example: MessageWithAttach()

The following example generates a simple email with a hard coded attachment. It does not provide any address for mail; This information can be provided when the mail is actually sent

/// w ##class(PHA.TEST.HTTP).MessageWithAttachment()
ClassMethod MessageWithAttachment() As %Net.MailMessage
{
	Set msg = ##class(%Net.MailMessage).%New()
	Set msg.Subject="Message with attachment "_$h
	Set msg.IsBinary=0
	Set msg.IsHTML=0
	Do msg.TextData.Write("This is the main message body.")

	//add an attachment
	Set status=msg.AttachFile("E:\", "HttpDemo.pdf")
	If $$$ISERR(status) {
		Do $System.Status.DisplayError(status)
		Quit $$$NULLOREF
	}
	b
	Quit msg
}

Send email using SMTP server

If you have access to the SMTP server, you can send e-mail. The SMTP server must be running and must have the required permissions to use it. To send an email:

  1. Create% net SMTP instance and set its properties as needed, especially the following properties:
  • Smtpserver is the name of the SMTP server being used.
  • Port is the port used on the SMTP server; The default value is 25.
  • Time zone specifies the server time zone specified in RFC 822, such as "EST" or "- 0400" or "LOCAL". If not set, the message will use universal time.

This object describes the SMTP server that will be used.

  1. If the SMTP server requires authentication, specify the necessary credentials. To this end:

a. Create% net An instance of authenticator.

b. Set the user name and password properties for this object.

c. Will. Net% The verifier property of the SMTP instance is set equal to this object.

d. If the message itself has an authorized sender, set% net AuthFrom property of SMTP instance.

  1. To use an SSL/TLS connection to an SMTP server:

a. Set the SSLConfiguration property to the name of the activated SSL/TLS configuration to use.

SSL/TLS configuration includes an option called Configuration Name, which is the string used in this setting.

b. Set the usestattls property to 0 or 1.

In most cases, the value 0 is used. If the server interaction starts on a normal TCP socket and then switches to TLS on the same port as the normal socket, a value of 1 is used.

Alternatively, set the sslccheckserveridentity property to 1. Do this if you want to verify the host server name in the certificate.

  1. Create an e-mail message to send (as described in "creating a single part e-mail message" and "creating a multi part e-mail message").
  2. Call the send() method of the SMTP instance. This method returns a status that should be checked.
  3. If the returned status indicates an Error, check the Error property, which contains the Error message itself.
  4. Check the FailedSend property, which contains the list of email addresses where the send operation failed.

The examples in the following sections use two different free SMTP services that were available at the time of writing this manual. Choosing these services does not mean special recognition. Also note that these examples do not show the actual password.

There are other examples in the Samples namespace. To find them, search the namespace for% net SMTP.

Important:% net SMTP writes the message body to a temporary file stream. By default, the file is written to the namespace directory. If the directory requires special write permission, the file will not be created, and you will get an empty message body.

You can define new paths for these temporary files and choose a path that does not restrict write access (for example, / tmp). To do this, set the global node% SYS("StreamLocation",namespace), where NAMESPACE is the NAMESPACE where the code runs. For example:

Set ^%SYS("StreamLocation","SAMPLES")="/tmp" 

If% SYS("StreamLocation",namespace) is NULL, InterSystems IRIS uses the directory specified by% SYS("TempDir",namespace). If% SYS("TempDir",namespace) is not set, IRIS uses the directory specified by% SYS("TempDir")

Example 1: hotpopas smtp() and SendSimpleMessage()

This example consists of two methods used together. First create% net An instance of SMTP that uses the test account set up on the HotPOP SMTP server:

/// w ##class(PHA.TEST.HTTP).HotPOPAsSMTP()
ClassMethod HotPOPAsSMTP() As %Net.SMTP
{
  Set server=##class(%Net.SMTP).%New()
  Set server.smtpserver="smtp.hotpop.com"
  //The HotPOP SMTP server uses the default port (25)
  Set server.port=25
  
  //Create objects for authentication
  Set auth=##class(%Net.Authenticator).%New()
  Set auth.UserName="isctest@hotpop.com"
  Set auth.Password="123pass"
  
  Set server.authenticator=auth
  Set server.AuthFrom=auth.UserName
  b
  Quit server
}

The next method uses the SMTP server provided as a parameter to send a simple and unique message:

ClassMethod SendSimpleMessage(server As %Net.SMTP) As %List
{
  Set msg = ##class(%Net.MailMessage).%New()
  Set From=server.authenticator.UserName
  Set:From="" From="xxx@xxx.com"
  Set msg.From = From
  
  Do msg.To.Insert("xxx@xxx.com")
  //Do msg.Cc.Insert("yyy@yyy.com")
  //Do msg.Bcc.Insert("zzz@zzz.com")
  Set msg.Subject="Unique subject line here "_$H
  Set msg.IsBinary=0
  Set msg.IsHTML=0
  Do msg.TextData.Write("This is the message.")
  
  Set status=server.Send(msg)
  If $$$ISERR(status) {
    Do $System.Status.DisplayError(status)
    Write server.Error
    Quit ""
  }
  Quit server.FailedSend
}

Example 2: YPOPsAsSMTP()

This example creates a% net. Net using YPOPS Ypops is a client software that provides SMTP and POP3 access to Yahoo e-mail accounts. It uses a test account that has been set up for this purpose:

ClassMethod YPOPsAsSMTP() As %Net.SMTP
{
  Set server=##class(%Net.SMTP).%New()
  //local host acts as the server
  Set server.smtpserver="127.0.0.1"
  //YPOPs uses default port, apparently
  Set server.port=25
  
  //Create object to carry authentication
  Set auth=##class(%Net.Authenticator).%New()
  //YPOPs works with a Yahoo email account
  Set auth.UserName="isc.test@yahoo.com"
  Set auth.Password="123pass"
  
  Set server.authenticator=auth
  Set server.AuthFrom=auth.UserName
  Quit server
}

You can use it with the SendSimpleMessage method shown in the above example.

Example 3: SendMessage()

The following more flexible methods accept both SMTP server and e-mail. The email should already contain the subject line (if required by the SMTP server), but it does not have to contain the address. This method then sends the email to a set of hard coded test destinations:

ClassMethod SendMessage(server As %Net.SMTP, msg As %Net.MailMessage) As %Status
{
  Set From=server.authenticator.UserName
  //make sure From: user is same as used in authentication
  Set msg.From = From
  
  //finish addressing the message
  Do msg.To.Insert("xxx@xxx.com")
  //send the message to various test email addresses
  Do msg.To.Insert("isctest@hotpop.com")
  Do msg.To.Insert("isc_test@hotmail.com")
  Do msg.To.Insert("isctest001@gmail.com")
  Do msg.To.Insert("isc.test@yahoo.com")
  
  Set status=server.Send(msg)
  If $$$ISERR(status) {
    Do $System.Status.DisplayError(status)
    Write server.Error
    Quit $$$ERROR($$$GeneralError,"Failed to send message")
  }
  Quit $$$OK
}

%Net. Other properties of SMTP

%Net. The SMTP class also has some other properties that you may need, depending on the SMTP server you are using:

  • AllowHeaderEncoding specifies whether the Send() method encodes non ASCII header text. The default value is 1, which means that non ASCII header text is encoded as specified in RFC 2047.
  • ContinueAfterBadSend specifies whether to continue trying to send mail after a failed email address is detected. If ContinueAfterBadSend is 1, the system adds the failed email address to the list of FailedSend properties. The default value is 0.
  • ShowBcc specifies whether to write BCC headers to e-mail messages. These are usually filtered out by the SMTP server.

Topics: iris