Thursday, May 31, 2012

Ax utility function for sending mail via SMTP

The following is a quick utility function that can be used to send an email via a configured SMTP server. See comment in the code for the structure of the 'attachments' parameter. This was adapted from another code-sample, and should work with version 2009 and later.

static public void sendMail(
    str         fromAddress,        // NB single address only
    str         toAddress,          // " "
    str         ccAddress,          // " "
    str         subject,
    str         body,
    container   attachments = conNull())
{

    // Send mail via SMTP
    // Attachments is a container of format:
    // [ Source file 1, Attachment name 1, Source file 2, Attachment name 2, ... ]

    SysEmailParameters                          emailParams = SysEmailParameters::find();

    System.Net.Mail.MailMessage                 message;
    System.Net.Mail.Attachment                  attachment;
    System.Net.Mail.AttachmentCollection        attachementCollection;
    System.Net.Mail.SmtpClient                  mailClient;
    System.Net.Mail.MailAddressCollection       addressCollection;
    str                                         mailServer;
    int                                         mailServerPort;
    str                                         attachmentFilename;
    str                                         attachmentName;
    int                                         idx;

    System.Exception                            clrException;
    InteropPermission                           perm;
    ;

    if(!fromAddress)
        throw error("From address has not been specified");
    if(!toAddress)
        throw error("To address has not been specified");

    try
    {
        perm = new InteropPermission(InteropKind::ClrInterop);
        perm.assert();

        mailServer      = emailParams.SMTPRelayServerName;
        mailServerPort  = emailParams.SMTPPortNumber;

        if(!mailServerPort)
            mailServerPort = 25;    // default SMTP port

        message = new System.Net.Mail.MailMessage(
            new System.Net.Mail.MailAddress(fromAddress,''),
            new System.Net.Mail.MailAddress(toAddress,''));

        addressCollection = message.get_CC();
        if(ccAddress)
            addressCollection.Add(ccAddress);

        message.set_Subject(subject);

        message.set_Body(body);
        attachementCollection = message.get_Attachments();

        if((conlen(attachments) mod 2) != 0)
            throw error(error::wrongUseOfFunction(funcName()));

        for(idx = 1;idx <= conLen(attachments);idx += 2)
        {
            attachmentFilename  = conPeek(attachments,idx);
            attachmentName      = conpeek(attachments,idx + 1);

            attachment = new System.Net.Mail.Attachment(attachmentFilename);
            attachment.set_Name(attachmentName);
            attachementCollection.Add(attachment);
        }

        mailClient = new System.Net.Mail.SmtpClient(mailServer,mailServerPort);
        mailClient.Send(message);

    }
    catch(Exception::CLRError)
    {
        clrException = CLRInterop::getLastException();
        error(clrException.get_Message());
        if(clrException.get_InnerException() != null)
        {
            clrException = clrException.get_InnerException();
            error(clrException.get_Message());
        }
        throw Exception::Error;
    }

}

And to test it out (assuming the method has been added to a new class called MailHelper):
MailHelper::sendMail(
  'admin@bigbusiness.com',
  'client@gmail.com',
  'linemanager@bigbusiness.com',
  'Congratulations!!',
  'You have just won an email.');

A note for developers - A handy tool for testing mailers or email-related processes can be downloaded at http://smtp4dev.codeplex.com/. It allows you to run a light-weight SMTP server locally for development and testing, and is definitely worth a look.

No comments:

How to identify the user that was used to change an object from AOT in AX2012

Get the object name for which we need to track these (user and date&time) information's. Login to SQL Server Management Studio an...