Friday, September 9, 2011

NAV Mail Issues

In NAV often times (depending on your user population) you may need to have NAV send emails based on an specific user action. NAV uses CodeUnit 397 (Mail) to serve this purpose. In my environment, we often need to send emails that are multiline. To facilitate this a minor addition can be made to the mail codeunit. I recommend adding a new function when this is necessary. This can be done by modifying a copy of the NewMessage function. I have listed the code below. Changed code is in RED. If you have questions, please feel free to post a comment.

Source:
Function Name: Typically I name this function NewMessageMultBody
Other Considerations:
  • The Body Paramater should be changed to an array. The corresponding variable in any calling functions needs to be an array of the same size. I use 200 as my default.
  • The CH variable is a CHAR giving it a value of 13 represents a carriage return.
NewMessageMultBody:

IF ISCLEAR(OApplication) THEN
CREATE(OApplication,TRUE,TRUE);

IF (NOT OApplication.Logon(TRUE,'','',FALSE,FALSE)) THEN BEGIN
OApplication.Logoff;
EXIT
END;
IF ISCLEAR(OSendMail) THEN
CREATE(OSendMail,TRUE,TRUE);

ErrorNo := 0;

OSendMail."To" := ToName;
OSendMail.CC := CCName;
OSendMail.Subject := Subject;
OSendMail.BodyFormat := 2;
MailGUIDValue := CREATEGUID;
OSendMail.SetUserProperty(GetMailGUIDFieldName,1,FORMAT(MailGUIDValue));

IF ISCLEAR(BSTRConverterBody) THEN
CREATE(BSTRConverterBody,TRUE,TRUE);

CH :=13;

BSTRConverterBody.ResetBSTR; // This code moved from within the below revised if. The process will not work if this code is not outside that IF
FOR X := 1 TO 200 DO BEGIN
IF Body[X] <> '' THEN BEGIN
Body[X] := Body[X] + FORMAT(CH);
BSTRConverterBody.AppendNextStringPortion(Body[X]);
END;
END;

OSendMail.Body := BSTRConverterBody;
IF ISCLEAR(BSTRConverterAttachFileName) THEN
CREATE(BSTRConverterAttachFileName,TRUE,TRUE);

IF AttachFileName <> '' THEN BEGIN
BSTRConverterAttachFileName.ResetBSTR;
BSTRConverterAttachFileName.AppendNextStringPortion(AttachFileName);
OAttachments := OSendMail.Attachments;
OAttachment := OAttachments.Add(BSTRConverterAttachFileName);
END;

OSendMail.OpenDialog := OpenDialog;
MailSent := OSendMail.Send;
ErrorNo := OSendMail.ErrorStatus;
OApplication.Logoff;

These simple changes will work along with Outlook 2003 as well as Outlook 2007.