Send email in AX 2012 using X++

Hi Readers,

Today, in this post we are going to share a X++ code to send email in AX 2012 using X++.





// Create By: Chirag Gupta
// Created Date: 2-Apr-2020
// Summary: This job will be used to send an email using AX 2012.
static void PKA_TestEmail(Args _args)
{
    // Set these variables.
    str                                   sender = 'axsupport@domain_name.com';
    str                                   recipient = 'test_emailTo@domain_name.com';
    str                                   cc = 'test_emailCC@domain_name.com';
    str                                   subject = 'Email Testing through AX 2012 R2';
    str                                   body = 'Hi There! This is a test email from AX 2012.';
    str                                   fileName = @'C:\test.txt';

    List                                  toList;
    List                                  ccList;
    ListEnumerator                        le;

    Set                                   permissionSet;
    System.Exception                      e;

    str                                   mailServer;
    int                                   mailServerPort;
    System.Net.Mail.SmtpClient            mailClient;
    System.Net.Mail.MailMessage           mailMessage;
    System.Net.Mail.MailAddress           mailFrom;
    System.Net.Mail.MailAddress           mailTo;
    System.Net.Mail.MailAddressCollection mailToCollection;
    System.Net.Mail.MailAddressCollection mailCCCollection;
    System.Net.Mail.AttachmentCollection  mailAttachementCollection;
    System.Net.Mail.Attachment            mailAttachment;
    ;

    try
    {
        toList = strSplit(recipient, ';');
        ccList = strSplit(cc, ';');

        permissionSet = new Set(Types::Class);
        permissionSet.add(new InteropPermission(InteropKind::ClrInterop));
        permissionSet.add(new FileIOPermission(filename, 'rw'));
        CodeAccessPermission::assertMultiple(permissionSet);

        mailServer = SysEmaiLParameters::find(false).SMTPRelayServerName;
        mailServerPort = SysEmaiLParameters::find(false).SMTPPortNumber;
        mailClient = new System.Net.Mail.SmtpClient(mailServer, mailServerPort);

        le = toList.getEnumerator();
        le.moveNext();

        mailFrom = new System.Net.Mail.MailAddress(sender);
        mailTo  = new System.Net.Mail.MailAddress(strLTrim(strRTrim(le.current())));
        mailMessage = new System.Net.Mail.MailMessage(mailFrom, mailTo);

        mailToCollection = mailMessage.get_To();
        while (le.moveNext())
        {
            mailToCollection.Add(strLTrim(strRTrim(le.current())));
        }

        le = ccList.getEnumerator();
        mailCCCollection = mailMessage.get_CC();
        while (le.moveNext())
        {
            mailCCCollection.Add(strLTrim(strRTrim(le.current())));
        }

        mailMessage.set_Priority(System.Net.Mail.MailPriority::High);
        mailMessage.set_Subject(subject);
        mailMessage.set_Body(body);

        // Uncomment below code to send an attachment in email and specify the file path.
        //mailAttachementCollection = mailMessage.get_Attachments();
        //mailAttachment = new System.Net.Mail.Attachment(fileName);
        //mailAttachementCollection.Add(mailAttachment);

        mailClient.Send(mailMessage);
        mailMessage.Dispose();

        CodeAccessPermission::revertAssert();

        info("Email sent successfully.");
    }
    catch (Exception::CLRError)
    {
        e = ClrInterop::getLastException();
        while (e)
        {
            info(e.get_Message());
            e = e.get_InnerException();
        }
        CodeAccessPermission::revertAssert();
    }
}

We hope this solution helped you to send email in AX 2012 using X++. Please comment your valuable feedback for this article...

Author:
Chirag Gupta
Microsoft Dynamics D365/AX 2012
Senior Technical Consultant at IBM Bangalore

Date:
1-Apr-2020

Happy Learning !!

Comments

Popular posts from this blog

[Solved] : Error: String or binary data would be truncated. Cannot execute a data definition language command on Vendor (VendLedgerReconciliationTmp)

AX 2012 - Command prompt compilation / AxBuild.exe for Parallel Compile on AOS of X++ to P-code / Parallel Compilation

AX 2012 - How to send SSRS report in email as an attachment using X++

AX 2012 - How to stop AOS when services got stuck at stopping status

Error: There was no endpoint listening at net.tcp://your_server_name:8201/Dynamics AX/Services…

AX 2012 - How to make a form field mandatory

Fetch vendor address using X++ in AX 2012

[Error] - Error in unit of amount in currency KES. Must be rounded to 0.01 | The unit of 37.563.5343100000000000 KES being posted to account 32710001-- is outside the current penny rounding threshold | Posting has been canceled

AX 2012 - How to print current date and time on SSRS Report

For more information about this error navigate to the report server on the local server machine, or enable remote errors in AX 2012