Skip to main content

Send email from AX using live or gmail exchange server

You may find few more posts over this topic to send emails from AX using live (Hotmail) or gmail exchange server. This is really helpful when we don’t have exchange is in place sometimes due to high cost or you just want to send emails for testing or demo purpose.

Let’s see what parameters need to setup and how can we achieve this requirement.
Go to System Administration | Setup | System | E-mail parameters

P.S. I am using a dedicated email account at outlook (Hotmail) domain for this example. NTLM option can also be used; TechNet article is more helpful to get more information on these parameters.

Here is the job I wrote to send email for selected user. I name it SendTextMail as in my following post I will be writing to send invitation from AX using Hotmail or Gmail exchange server.


//SmtpSSL
static void SendTextMail(Args _args)
{
    System.Net.Mail.MailMessage             mailMessage;
    System.Net.Mail.SmtpClient              myMail;
    System.Net.Mail.MailAddressCollection   mailcoll;
    System.Net.Mail.MailAddress             mailFrom;
    System.Net.Mail.MailAddress             mailTo;
    System.Net.Mail.MailAddress             mailCC;
    str                                     receiverMailAddress;
    str                                     mailBody;
    str                                     smtpServer;
    str                                     mailSubject;
    str                                     CcMailAddress;
    int                                     SMTPPort;
    #File
    str                                     mail;
    str                                     pwd;

    Dialog dialog = new Dialog('Email');
    Dialogfield     person, emailSubject, emailBody;
    HcmWorker       hcmWorker;
    UserInfo        userInfo;
    DirPersonUser   dirPersonUser;
    SysUserInfo     sysUserInfo;
    SysEmailParameters parameters;

    // dialog field to select user to whom email will be send
    person          = dialog.addField(extendedTypeStr(HcmWorkerRecId ), 'Person :' );   
    emailSubject    = dialog.addField(extendedTypeStr(Description), 'Subject :' );      // Email Subject
    emailBody       = dialog.addField(extendedTypeStr(Notes), 'Body :' );               // Email Body

    if(dialog.run())
    {
        parameters = SysEmailParameters::find();   // Find values from Email Parameters

        new InteropPermission(InteropKind::ClrInterop).assert();

        // gets HcmWorker record based on person selected from user dialog
        hcmWorker = hcmWorker::find(person.value()); 

        if(!hcmWorker.RecId)   // Verify either user exist or not
        {
            throw error('User not found');
        }

        select firstOnly dirPersonUser
            join userInfo
                where dirPersonUser.PersonParty == DirPartyTable::findByName(hcmWorker.name()).RecId &&
                 userInfo.id == dirPersonUser.User;

        select firstOnly sysUserInfo
            where sysUserInfo.Id == userInfo.id;      // Retrieve user info record for selected user

        mailSubject         = emailSubject.value();
        mailFrom            = new  System.Net.Mail.MailAddress(parameters.SMTPUserName ,"Name");
        mailTo              = new  System.Net.Mail.MailAddress(sysUserInfo.Email);
        //mailTo            = new  System.Net.Mail.MailAddress("test1@gmail.com");
        //mailCC            = new  System.Net.Mail.MailAddress("test2@gmail.com";
        mailcoll            = new  System.Net.Mail.MailAddressCollection();
        mailBody            = emailBody.value();

        try
        {
            // using the SMTP server ip //setup in email Parameters
            smtpServer          = SysEmaiLParameters::find(false).SMTPRelayServerName;  
            mailMessage         = new System.Net.Mail.MailMessage(mailFrom,mailTo);
            mailmessage.set_Subject(mailSubject);
            mailmessage.set_Body(mailBody);

            SMTPPort            = SysEmaiLParameters::find(false).SMTPPortNumber;
            myMail              = new System.Net.Mail.SmtpClient(smtpServer, SMTPPort);

           // For SSL enabled mail servers. Ex: gmail, smtp.gmail.com, port 465 or 587
            myMail.set_EnableSsl(true); 

            pwd = SysEmaiLParameters::password();

            mymail.set_Credentials(New System.Net.NetworkCredential(parameters.SMTPUserName, pwd));

            mymail.Send(mailmessage);
        }
        catch(Exception::CLRError)
        {
            throw Exception::CLRError;
        }

        mailMessage.Dispose();
        CodeAccessPermission::revertAssert();
    }
}

UI of the utility


Comments

  1. I configured gmail smtp in email parameters and your code is perfectly working. However, when I am trying to execute following code which is using default SysMailer class I am getting error:

    SysMailer sysMailer = new SysMailer();
    ;

    sysMailer.quickSend('sender email address', 'recipient email address', 'test email alert', 'test email alert');

    I am getting following error:

    Method 'send' in COM object of class 'CDO.Message' returned error code 0x8004020E () which means: .

    Any help would be highly appreciated.

    ReplyDelete
  2. Gmail helps in advancing organizations of various kinds by giving them online crowd. Low spam scores

    ReplyDelete

Post a Comment

I will appreciate your comments !

Popular posts from this blog

The Dual Write implementation - Part 1 - Understand and Setup

What is Dual-write? Tightly couples – complete at one transaction level Near real time Bi-directional Master data and business documents – Customer records you are creating and modifying and at this document we are talking about sales orders or quotes and invoice. Master data could be reference data e.g. customer groups and tax information Why Dual-write and why not Data Integrator? Data Integrator is Manual or Scheduled One directional Now, Let's deep dive and understand what is required for Dual-write setup and from where to start. First thing first, check you have access to https://make.powerapps.com/ Choose right environment of CDS (CE) Make sure you have access to the environment too, click on gear icon and Admin Center  Look for required environment and Open it, you must have access as going forward you are going to configure dual write steps in the environment user the same user you are logged in now. Now, go back to power platform admin center and...

D365FO: Entity cannot be deleted while dependent Entities for a processing group exist. Delete dependent Entities for a processing group and try again.

Scenario: There are times when you want to delete an entity from target entity list and when you do so, you face an error message which does not tell you where exactly the entity has been used.  "Entity cannot be deleted while dependent Entities for the processing group exist. Delete dependent Entities for a processing group and try again. " Solution: Browse the environment by appending this part  /?mi=SysTableBrowser&TableName=DMFDefinitionGroupEntity&cmp=USMF   at the end.  For example; if the environment URL is  https://daxture.sandbox.operations.dynamics.com then the complete URL will be https://daxture.sandbox.operations.dynamics.com/?mi=SysTableBrowser&TableName=DMFDefinitionGroupEntity&cmp=USMF Filter for Entity and it will give you the DefinitionGroup where the entity has been added or used in data management import/export projects. Get the DefinitionGroup name and search in the export/import projects under data management and either del...

Dual-write connection set error: An item with the same key has already been added

If you happen to see this error message then you have duplicate records in cdm_company entity in CDS environment. Check for cdm_companycode field this is normally not allowed but have a look and delete the ones with duplicates.