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);
}
*/

19 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
  8. This code modification is very helpful for bypassing Outlook issues.

    ReplyDelete
  9. How to Send Emails from AX Without Requiring Outlook is like using Beach Buggy Racing Shortcuts Just as bypassing Outlook speeds up email processes, finding hidden paths in the game gives you an edge. Skip obstacles, take the fastest route, and race ahead—whether in workflows or on the track!

    ReplyDelete

  10. How to Send Emails from AX Without Requiring Outlook—Easily automate emails in AX using SMTP instead of Outlook. Just like bypassing Outlook, users look for Prank Paytm App No Watermark Free Download to skip restrictions. But beware—unverified apps can be risky. Always choose trusted sources to keep your data safe!

    ReplyDelete
  11. Sending emails from AX without Outlook boosts efficiency—just like unlocking unlimited cars in CarX Street Drive. Both remove limits, offering seamless control and flexibility. Whether streamlining workflows or racing with CarX Street Drive mod apk unlimited carshaving the right tools ensures a smoother, faster, and more powerful experience!

    ReplyDelete
  12. Sending emails from AX without Outlook requires configuring SMTP settings, similar to how Traffic Rider Mod APK bypasses standard restrictions for an enhanced experience. Just as the mod unlocks unlimited resources, setting up direct email sending in AX removes dependencies, ensuring smooth, efficient communication without needing external applications.

    ReplyDelete
  13. Your blog is an incredible source of well-researched and structured content! The clarity in writing makes even complicated topics easy to grasp. I truly appreciate the time and effort behind each post. Keep up the great work! Looking forward to more informative content. Thanks for consistently sharing high-quality posts! Your dedication to educating readers is highly appreciated.

    ReplyDelete
  14. Alex Kwitny, known as "Alex on DAX," is a Microsoft MVP specializing in Dynamics AX and Dynamics 365. His blog features technical insights and solutions for these platforms.

    For wasp removal ottawa services in Ottawa, companies like Capital Wildlife Control

    and Wayne’s Pest Extermination
    offer professional assistance.

    ReplyDelete
  15. Great tip on sending emails from AX without Outlook! Just like streamlining communication systems, Pharmaceutical Manufacturing Equipment helps optimize production processes by reducing dependency on outdated methods—ensuring efficiency, compliance, and seamless operation in today’s fast-paced industrial landscape.

    Website :- https://sterinoxsystems.com/pharmaceutical-equipment-manufacturer/

    ReplyDelete
  16. Get tailored quotes  from 3PL providers for your business and compare the capabilities, service  levels and prices of over 200+ fulfillment services providers worldwide in just 10  minutes

    ReplyDelete