Sending Email from X++ code - D365 AX

Hi,

Sending Email from X++ code  - D365 AX

Step 1: SMTP Settings in sysadmin

SMTP (Go to System Admin --> Setup  -->  Email --> Email Paramenters  -->Email providers and
 SMTP Settings)

Select Email providers 



SMTP Settings




Step 2: Sending mail thru coding

Add new runnable class  and below code.

class TestEmail
{     
    /// <summary>
    /// Runs the class with the specified arguments.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    { 
TestEmail  tEmail= new TestEmail();
           try
        {
            str sUserId;
            str userEmail;
         
            sUserId = curUserId();
             
            //Getting Email id from User Options --> Account --> Email Provider --> Email id
            userEmail = SysUserInfo::find(sUserId, false).Email;

            var builder = new SysMailerMessageBuilder();

             builder.setFrom("shyamkanna@test.net");
            builder.addTo(userEmail);
            builder.addTo("ToAdd@test.net");
            builder.setSubject("Hello from D365 - Test Email");
            builder.setBody("Email Test from D365");

//For attachment
 System.IO.Stream   _stream =tEmail.addfileattachment();
  builder.addAttachment(_stream,"test.xml");
         
            var message = builder.getMessage();

            SysMailerFactory::getNonInteractiveMailer().sendNonInteractive(message);

       
        }

        catch (Exception::Error)

        {

            throw error("@SYS33567");

        }
    }

public System.IO.Stream addfileattachment()
{

        System.IO.StreamReader          reader;
        System.IO.Stream                requestStream;
        System.Byte[]                   bytes;
        System.IO.Stream                readStream;
        System.Text.Encoding            utf8;
       
        str                         retVal;
        str _fileNamePath ="10.1.1.1\\test.xml";

         // Read file
            _fileNamePath = strReplace(_fileNamePath,"\\","/");
            reader = new System.IO.StreamReader(_fileNamePath);
            utf8 = System.Text.Encoding::get_UTF8();
            bytes = utf8.GetBytes( reader.ReadToEnd() );
            reader.Close();

 requestStream =(new System.IO.MemoryStream(bytes) );

return requestStream ;

}



}

Send Mail
Reference
Reference

With Attachment
Reference
Reference

Get Current User email id

SMTP Settings


For Office D365 

https://docs.microsoft.com/en-us/dynamics365/unified-operations/fin-and-ops/organization-administration/configure-email

 Outgoing mail server - smtp.office365.com
 PORT Number - 587
 User Name - Office 365 email account
 Password - Office 365 email password

 SSL - Yes









Comments

Post a Comment