Friday, March 5, 2010

CLR Interop in X++ Example 2: Sending Email with an Attachment

Continuing from my first post, “CLR Interop in X++ Example 1: Obtaining a Screen Shot”, the next step in my error reporting routine would be to send the newly created PNG file in an email. Once again, for the .NET Developer, it is easy to first create and test the function in .NET, and use it as a basis for translation into X++. Below is a rather simple C#.NET function which sends an email message with one attachment. The parameters of the function are self-explanatory:

bool SendEmail(string ToAddress, string FromAddress, string SMTPServer, string Username, string Password, string Subject, string Body, string FileToAttach)
{
bool success = true;

try
{
MailMessage mail = new MailMessage(FromAddress, ToAddress);
if (FileToAttach.Length > 0)
{
mail.Attachments.Add(new Attachment(FileToAttach));
}

mail.Subject = Subject;
mail.Body = Body;

SmtpClient smtp = new SmtpClient(SMTPServer);

NetworkCredential networkCred = new NetworkCredential(Username, Password);
smtp.UseDefaultCredentials = false;
smtp.Credentials = networkCred;

smtp.Send(mail);
}
catch
{
success = false;
}

return success;
}


The next snippet is the X++ translation:

boolean SendEmail(str ToAddress, str FromAddress, str SMTPServer, str Username, str Password, str Subject, str Body, str FileToAttach)
{
System.Net.Mail.MailMessage mail;
System.Net.Mail.Attachment attach;
System.Net.Mail.AttachmentCollection ac;
System.Net.Mail.SmtpClient smtp;
System.Net.NetworkCredential networkCred;
boolean success;
;

success = true;

try
{
mail = new System.Net.Mail.MailMessage(FromAddress, ToAddress);
if (strlen(FileToAttach) > 0)
{
attach = new System.Net.Mail.Attachment(FileToAttach);
ac = mail.get_Attachments();
ac.Add(attach);
}

mail.set_Subject(Subject);
mail.set_Body(Body);

smtp = new System.Net.Mail.SmtpClient(SMTPServer);

networkCred = new System.Net.NetworkCredential(Username,Password);
smtp.set_UseDefaultCredentials(false);
smtp.set_Credentials(networkCred);

smtp.Send(mail);
}
catch(Exception::CLRError)
{
success = false;
}

return success;
}

No comments:

Post a Comment