Wednesday, July 30, 2014

Send email within AX/X++ via .NET objects or using built in SMTP objects

How to send email within AX/X++ while using the admin defined settings within AX via  .NET objects or using built in SMTP objects. Personally I prefer the system.net method.


System.Net.Mail method


static void SendEmailDotNet(Args _args)
{
    System.Net.Mail.MailMessage mailMessage;
    System.Net.Mail.SmtpClient smtpClient;
    System.Net.Mail.MailAddress mailFrom;
    System.Net.Mail.MailAddress mailTo;
    System.Net.Mail.MailAddressCollection       addressCollection;
    System.Net.Mail.Attachment                  attachment;
    System.Net.Mail.AttachmentCollection        attachementCollection;
    str    smtpServer;

    mailFrom = new System.Net.Mail.MailAddress('from@address.com',"Sender name");
    mailTo  = new System.Net.Mail.MailAddress('to@address.com',"Receipt Name");
    smtpServer = SysEmaiLParameters::find(false).SMTPRelayServerName;// using the SMTP server ip setup in Email Parameters
    mailMessage = new System.Net.Mail.MailMessage(mailFrom,mailTo);
    mailMessage.set_IsBodyHtml(true);
    mailmessage.set_Subject('This is email subject');
    mailmessage.set_Body('<html><body>This is email bodyamc</body></html>');
    addressCollection = mailMessage.get_CC();
    addressCollection.Add("cc1@address.com");
    addressCollection.Add("cc1@address.com");
   
   attachementCollection = mailMessage.get_Attachments();
   attachment = new System.Net.Mail.Attachment("C:\\test.txt"); //file to attach
   attachment.set_Name("adam.txt"); //name to display file as in email
   attachementCollection.Add(attachment);
    smtpClient = new System.Net.Mail.SmtpClient(smtpServer);
    smtpClient.Send(mailmessage);
    mailMessage.Dispose();
    info("sent");
}


AX SMTP method

static void TestEmailJob(Args _args)
{
SysEmailParameters parameters = SysEmailParameters::find();
SMTPRelayServerName relayServer;
SMTPPortNumber portNumber;
SMTPUserName userName;
SMTPPassword password;
Str subject,body;
InteropPermission interopPermission;
SysMailer mailer;
relayServer = parameters.SMTPServerIPAddress;
portNumber = parameters.SMTPPortNumber;
userName = parameters.SMTPUserName;
password = SysEmailParameters::password();
subject = "Subject line for the email";
body = "<B>Body of the email</B>";
CodeAccessPermission::revertAssert();
interopPermission = new InteropPermission(InteropKind::ComInterop);
interopPermission.assert();
mailer = new SysMailer();
mailer.SMTPRelayServer(relayServer,portNumber,userName,password, parameters.NTLM);
mailer.fromAddress("from@address.com");
mailer.tos().appendAddress("to@address.com");
mailer.subject(subject);
mailer.htmlBody(body);
mailer.attachments().add("C:\\test.txt");
mailer.sendMail();
CodeAccessPermission::revertAssert();
info("sent");
}

1 comment:

  1. Hi Adam! If you could send me a couple of screen shots of the final forms, that would be much appreciated! Thanks a lot.
    ritzell@yahoo.com

    ReplyDelete