web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics AX (Archived)

send e-mails via smtp

(0) ShareShare
ReportReport
Posted on by

hello all,

i am trying to send mail from ax 2012 via smtp by using this job.but before run this job, i setup parameters configuration in system administration > setup > system > email parameters and set fields like capture below.

i used this job:

static void  sendemail(Args _args)
{
SysMailer mailer = new SysMailer();
SysEmailParameters parameters = SysEmailParameters::find();
;

if (parameters.SMTPRelayServerName)
{
mailer.SMTPRelayServer(parameters.SMTPRelayServerName,
parameters.SMTPPortNumber,
parameters.SMTPUserName,
SysEmailParameters::password(),
parameters.NTLM);
}
else
{
mailer.SMTPRelayServer(parameters.SMTPServerIPAddress,
parameters.SMTPPortNumber,
parameters.SMTPUserName,
SysEmailParameters::password(),
parameters.NTLM);
}

mailer.fromAddress('acd@gmail.com');
mailer.tos().appendAddress('adf@gmail.com');
mailer.htmlBody('AZZZ');
mailer.subject('Hello');

mailer.sendMail();
}

****************************

6076.Capture.PNG

but when run this error appear:

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

*This post is locked for comments

I have the same question (0)
  • Community Member Profile Picture
    on at

    but when run this error appear:

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

  • Suggested answer
    axk Profile Picture
    925 on at

    Hey Mostafa,

    Here is the link to similar problem, which got solved - https://community.dynamics.com/ax/f/33/t/12848.

    There is also complete list of error codes so it's easier to find the problem.

  • Jos Litjens Profile Picture
    1 on at

    When you add a try/catch for CLR exceptions you'll get more details on the error.

    See msdn.microsoft.com/.../ee677495.aspx for an example.

  • Community Member Profile Picture
    on at

    i added try/catch like this :

     static void hegazyemailThruSysMailer(Args _args)

       {

           CopyOfSysMailer   mailer = new CopyOfSysMailer();

           SysEmailParameters parameters = SysEmailParameters::find();

            System.Exception         e;

           ;

          try{

           if (parameters.SMTPRelayServerName)

           {

               mailer.SMTPRelayServer(parameters.SMTPRelayServerName,

                                  parameters.SMTPPortNumber,

                                  parameters.SMTPUserName,

                                  SysEmailParameters::password(),

                                  parameters.NTLM);

           }

           else

           {

               mailer.SMTPRelayServer(parameters.SMTPServerIPAddress,

                                  parameters.SMTPPortNumber,

                                  parameters.SMTPUserName,

                                  SysEmailParameters::password(),

                                  parameters.NTLM);

           }

           mailer.fromAddress('mostafa.hegazy@mufaddal.com');

           mailer.tos().appendAddress('mostafahegazy80@gmail.com');

           mailer.htmlBody('AZZZ');

           mailer.subject('Comunicazione AX');

           mailer.sendMail();

           info("sent");

    }

    catch (Exception::CLRError)

    {

    e = ClrInterop::getLastException();

    while (e)

    {

    info(e.get_Message());

    e = e.get_InnerException();

    }

    CodeAccessPermission::revertAssert();

    info ("Failed to Send Email ");

    }

       }

    but the same error exists.

  • Suggested answer
    Vilmos Kintera Profile Picture
    46,149 on at

    You cannot use free service providers out of the box I am afraid, since AX does not support the communication protocol they require by default with the DLL they use for sending mails via SMTP. It was also mentioned in the first posters' linked topic.

    This question has been asked recently, see the whitepaper I've linked in the topic:

    community.dynamics.com/.../652327

    You need to use an Exchange server with relaying, or set up your own SMTP server as per the documentation.

  • Jos Litjens Profile Picture
    1 on at

    Hi Mostafa,

    try info-ing the innerException, that usually contains the detailed information. Like so:

       catch(Exception::CLRError)

       {

           exception = ClrInterop::getLastException();

           while(exception.get_InnerException() != null)

           {

               exception = exception.get_InnerException();

           }

           s = exception.get_Message();

           warning(s);

       }

  • Community Member Profile Picture
    on at

    thanks all for replay,

    after override new() and sendmail() methods in sysmailer class. the previous error disappear but this warning appear:

    Error sending mail in : The server rejected the sender address. The server response was: 530 5.7.0 Must issue a STARTTLS command first. a197sm15117536wma.1 - gsmtp

    (0x8004020E)

  • Vilmos Kintera Profile Picture
    46,149 on at

    Same issue as explained above, Google does not support the protocol which AX does and vice versa. Why are you not reading the posts which we are linking?

  • AX 2012 r3 Profile Picture
    2,426 on at

    Hi Mostafa,

    Try this code

    static void Mail(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;

      //Edited for attachment

       System.Net.Mail.Attachment              attachment;

       System.Net.Mail.AttachmentCollection        attachementCollection;

       //Editing Ended

       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 ,curext());

           mailTo              = new  System.Net.Mail.MailAddress("Giveyourmail@gmail.com");//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);

               //Edited For Attachment

           attachementCollection = mailMessage.get_Attachments();

      attachment = new System.Net.Mail.Attachment(@"c:\temp\00a1f4c8-9055-41bb-b75c-dfe8eaa9d11e.eml"); //file to attach

      attachment.set_Name("Test.eml"); //name to display file as in email

      attachementCollection.Add(attachment);

               ////Editing Ended

               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();

       }

    }

    If you got stuck .let me know.

    Regards.

  • Aamir Shakeel Profile Picture
    190 on at

    I am getting following error when calling send method of STMPClient.

    Exception has been thrown by the target of an invocation.
       at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
       at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at Microsoft.Dynamics.AX.ManagedInterop.ClrBridgeImpl.InvokeClrInstanceMethod(ClrBridgeImpl* , ObjectWrapper* objectWrapper, Char* pszMethodName, Int32 argsLength, ObjectWrapper** arguments, Boolean* argsAreByRef, Boolean* isException)
    Failure sending mail.
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
    Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
       at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
       at System.Net.DelegatedStream.Read(Byte[] buffer, Int32 offset, Int32 count)
       at System.Net.BufferedReadStream.Read(Byte[] buffer, Int32 offset, Int32 count)
       at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
       at System.Net.Mail.EHelloCommand.Send(SmtpConnection conn, String domain)
       at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
    An existing connection was forcibly closed by the remote host
       at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)

     Any idea how to get rid of this error. It was working, but from yesterday it is giving me error.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics AX (Archived)

#1
Martin Dráb Profile Picture

Martin Dráb 4 Most Valuable Professional

#1
Priya_K Profile Picture

Priya_K 4

#3
MyDynamicsNAV Profile Picture

MyDynamicsNAV 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans