Pages

Wednesday, January 25, 2012

How to send emails from AX without requiring Outlook

Sending emails from AX has been somewhat of a pain when it tries to use Outlook.  This post is a simple code modification to one method in \Classes\Info\reportSendMail.  I did not develop this code, I merely tweaked it.  The original poster's blog has disappeared, and I can only find non-working remnants all around the web of this, but it is just too useful not to repost.

If you have Outlook 64bit edition, you might get the "Either there is no default mail client or the current mail client cannot fulfill the messaging request.  Please run Microsoft Outlook and set it as the default mail client."  Followed by an AX MAPI error.

Or sometimes you may get the "A program is trying to access e-mail address information stored in Outlook."...Allow/Deny/Hlep.

This change basically bypasses outlook.  Put it in and give it a shot.



void reportSendMail(PrintJobSettings p1)
{
    //SysINetMail m = new SysINetMail();
    System.Net.Mail.MailMessage mailMessage;
    System.Net.Mail.Attachment attachment;
    System.Net.Mail.AttachmentCollection attachementCollection;
    System.Net.Mail.SmtpClient myMail;
    System.Net.Mail.MailAddress mailFrom;
    System.Net.Mail.MailAddress mailTo;
    str userMailAddress;
    str receiverMailAddress;
    str mailBody;
    str smtpServer;
    fileNameOpen fileNameForEmail;
    str mail;
    FileIOPermission perm;
    userinfo userInfo;
    //end Declaration
    str fileName = 'axaptareport';

    ;
    if (p1.format() == PrintFormat::ASCII)
        fileNameForEmail = subStr(p1.fileName(),strLen(p1.fileName())-3,-999)+'TXT';
    else if (p1.format() == PrintFormat::RTF)
        fileNameForEmail = subStr(p1.fileName(),strLen(p1.fileName())-3,-999)+'RTF';
    else if (p1.format() == PrintFormat::HTML)
        fileNameForEmail = subStr(p1.fileName(),strLen(p1.fileName())-3,-999)+'HTM';
    else if (p1.format() == PrintFormat::PDF || p1.format() == PrintFormat::PDF_EMBED_FONTS)
        fileNameForEmail = subStr(p1.fileName(),strLen(p1.fileName())-3,-999)+'PDF';

    mail = subStr(fileNameforEmail,(strlen(fileNameforEmail)-8),9);

    select firstonly name from userInfo where userInfo.id == SysuserInfo::find().Id; // to find the user name

    if (isRunningOnServer())
        fileNameforEmail = winApiServer::getTempPath() + mail; // store attachment in a temp location
    else
        fileNameforEmail = winApi::getTempPath() + mail; // store attachment in a temp location


    perm = new FileIOPermission(fileNameforEmail,'w');
    if(!perm)
    {
        throw error("Cannot move attachment to temp location.");
        return;
    }
    try
    {
        perm.assert();
    }
    catch
    {
        throw error("Cannot gain access to Temp location.");
        return;
    }

    userMailAddress = SysUserInfo::find().Email; // find current users email address setup up in user //options
    receiverMailAddress = p1.mailTo();

    mailFrom = new System.Net.Mail.MailAddress(userMailAddress,userInfo.name);

    mailTo = new System.Net.Mail.MailAddress(receiverMailAddress,"");

    mailBody = "Email sent from " + CompanyInfo::name() + ", using Dynamics AX";

    smtpServer = SysEmaiLParameters::find(false).SMTPRelayServerName;// using the SMTP server ip //setup in email Parameters

    mailMessage = new System.Net.Mail.MailMessage(mailFrom,mailTo);
    mailmessage.set_Subject(p1.mailSubject());
    mailmessage.set_Body(mailBody);

    //move attachment file to Temp folder, might need to create WinAPIServer::moveFile
    winapi::moveFile(p1.fileName(), fileNameforEmail);

    attachementCollection = mailMessage.get_Attachments();
    attachment = new System.Net.Mail.Attachment(fileNameforEmail);
    attachementCollection.Add(attachment);

    myMail = new System.Net.Mail.SmtpClient(smtpServer);
    mymail.Send(mailmessage);

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

    if (isRunningOnServer())
        WinAPIServer::deleteFile(fileNameForEmail);
    else
        winApi::deleteFile(fileNameforEmail);

    CodeAccessPermission::revertAssert();
}

/*
void reportSendMail(PrintJobSettings p1)
{
    SysINetMail m = new SysINetMail();

    str fileName = 'axaptareport';

    if (p1.format() == PrintFormat::ASCII || p1.format() == PrintFormat::TEXTUTF8)
        fileName = fileName + '.txt';
    else if (p1.format() == PrintFormat::RTF)
        fileName = fileName + '.rtf';
    else if (p1.format() == PrintFormat::HTML)
        fileName = fileName + '.htm';
    else if (p1.format() == PrintFormat::PDF || p1.format() == PrintFormat::PDF_EMBED_FONTS)
        fileName = fileName + '.pdf';

    m.sendMailAttach(p1.mailTo(),p1.mailCc(), p1.mailSubject(),'Medulla Report', true, p1.fileName(), fileName);
}
*/

9 comments:

  1. After importing the code ,i tried to send report directly using SMTP but I dont receive any e-mail.
    I though it is issue woth smtp settings so ,I tried using alert through e-mail which is working fine .so there is no issue with SMTP settings.
    can you let me know what can be the issue

    ReplyDelete
    Replies
    1. Have you tried stepping through the code? This has worked for me at many clients. I wonder if there was a problem during copy/paste.

      Delete
  2. great post!

    the only thing i changed was added these lines ( specific to our environment but still potentially helpful for others ) after
    "userMailAddress = SysUserInfo::find().Email; // find current users email address setup up in user //options"

    if the SysUserInfo record is missing an email addresss, you will get a CLRObject creation failure.

    userMailAddress = SysUserInfo::find().Email; // find current users email address setup up in user //options
    if(userMailAddress == "")
    {
    select * from userInfo where userInfo.id == curUserId();
    if(userInfo)
    {
    userMailAddress = strfmt("%1@%2",UserInfo.networkAlias, userInfo.networkDomain);
    }
    }

    ReplyDelete
  3. also, one thing to look at is this line:

    if (p1.format() == PrintFormat::ASCII)

    i changed it to this:

    if (p1.format() == PrintFormat::ASCII || p1.format() == PrintFormat::TEXTUTF8)


    without that or, if a user attempts to email a report as UTF8 output, there will get an error

    ReplyDelete
  4. The above solution will only work for MorphX reports. SSRS reports in AX 2012 use a different framework. If they are run in batch they will use SMTP and if they are run interactive they will use MAPI by design. If you want to always use SMTP the SRSReportMailer.initMailer() method can be modified to accomplish this requirement.

    ReplyDelete
    Replies
    1. Paul,

      What is the SRSReportMailer that you are referencing? I'm not able to locate it. Is it from a later update/release of AX 2012?

      Delete
  5. I think Paul Marten talk about SrsReportRunMailer class.

    ReplyDelete
  6. This comment has been removed by a blog administrator.

    ReplyDelete
  7. Thank you very much for helpful post. I will give it a try.

    ReplyDelete