Thursday, July 29, 2010

Sending Emails From Dynamics AX without Outlook

  
Recently we had a need to have Dynamics AX send emails without the use of Outlook. I was presented with the following blog by Mohammed Rasheed titled Sending Emails From Dynamics AX without Outlook, which proved to be extremely useful. There was however an issue with the code (perhaps simply related to our environment) which was puzzling. The problem was that the email would send successfully, but afterward, an error was thrown stating:

ClrObject static method invocation error

The line of code that appeared to be the culprit was basically the last line in the function:

CodeAccessPermission::revertAssert();

However, after analyzing things more closely the problematic line was actually the line just above:

winApi::deleteFile(fileNameforEmail); // delete temp file

As it turns out, the deleteFile() function was failing because the file had not been released by a previous process. Though it was a bit painful to figure out what was going on, the solution itself was rather simple.

Immediately after sending the email, I modified the code to dispose the objects that may have been clinging to the file

mymail.Send(mailmessage);


mailmessage.Dispose();
attachment.Dispose();

After this, the file was released, and was able to be deleted, and the error went away!
  

3 comments:

  1. small remark, when sending from a batch task (the server tier) you may want to replace the winapi calls with the System.Io calls since the winapi fails to run on the server.

    But nice post !

    ReplyDelete
  2. I vaguely remember using this code last year sometime and I think the issue might actually be related to WinAPI:: vs. WinAPIServer:: where different permissions are required. Try using "if (isRunningOnServer())".

    Perhaps this might have only been my issue and not yours...but it may help someone else. :)

    ReplyDelete
  3. Not able to access the link by Mohammed Rasheed. Please help.

    ReplyDelete