Search code examples
intersystems-cacheobjectscript

Manually send mail from terminal console?


We have a class that builds and sends a mail message. I want to make some changes but before I do I want to test some things (like how URLs are displayed). I'm trying to manually send a message from the console but I'm getting some errors. Here is the SendMessage method of the class:

Method SendMessage(pSubject As %String, pMessage As %String, pEmailAddresses) As %Status
{
    set tSC=$$$OK
    set tMailMessage=##class(%Net.MailMessage).%New()
    do tMailMessage.To.Insert($PIECE(pEmailAddresses,",",1))
    for tI=2:1:$LENGTH(pEmailAddresses,",") {
        do tMailMessage.Cc.Insert($PIECE(pEmailAddresses,",",tI))
    }

    set tMailMessage.Subject=pSubject
    set tMailMessage.Charset="iso-8859-1"
    set tSC=tMailMessage.TextData.Write(pMessage)
    quit:'tSC
    Set tSC1=..Adapter.SendMail(tMailMessage)
    if 'tSC1 {
        //Log warning about being unable to send mail.
        do $SYSTEM.Status.DecomposeStatus(tSC1,.err)
        $$$LOGWARNING("Could not send email: "_err(err))
        kill err
    }

    quit tSC
}

From the terminal, I can instantiate the MailMessage class and set the body data but when I try to send I get an error:

USER>set tMailMessage=##class(%Net.MailMessage).%New()

USER>do tMailMessage.To.Insert("[email protected]")

USER>set tSC=tMailMessage.TextData.Write("This is a URL test http://www.google.com, thank you")

USER>set tMailMessage.Subject="This is a test"

USER>set tMailMessage.Charset="iso-8859-1"

USER>set tSC1=..Adapter.SendMail(tMailMessage)

SET tSC1=..Adapter.SendMail(tMailMessage)
^
<NO CURRENT OBJECT>

As you can see, when I try to SendMail it tells me NO CURRENT OBJECT

update I noticed these lines at the top of the class:

Parameter ADAPTER = "EnsLib.EMail.OutboundAdapter";

Property Adapter As EnsLib.EMail.OutboundAdapter;

So I tried USER>set tSC1=EnsLib.EMail.OutboundAdapter.SendMail(tMailMessage) but that resulted in <UNDEFINED> *EnsLib


Solution

  • As I think you working on Ensemble Service. But for testing, you should not use that classes. For sending emails you could use %Net.SMTP directly. So, instead of ..Adapter.SendMail use this code

    set s=##class(%Net.SMTP).%New()
    set s.smtpserver="SMTP server name"
    
    #; if SMTP server needs auth
    set auth=##class(%Net.Authenticator).%New() ; use default authentication list
    set auth.UserName="myUser"
    set auth.Password="myPassword"
    set s.authenticator=auth
    
    set status=s.Send(tMailMessage)
    if $$$ISERR(status) do $system.OBJ.DisplayError(status)