Search your query

Friday, May 26, 2017

X++ code to attach the text file from local system directory and send an email.

class EmailTextFile
{      
   
    /// <summary>
    /// Attach the text file from local system directory and send an email using X++.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>

    public static void main(Args _args)
    {    
        EmailTextFile emailTextFile = new EmailTextFile();
       
        emailTextFile .sendMail();
    }
 
    private void sendMail()
    {
        SysMailerMessageBuilder     sysMailBuilder = new SysMailerMessageBuilder();
        SysMailerSMTP               smtp           = new SysMailerSMTP();
        System.IO.StreamReader      reader         = new System.IO.StreamReader(@"C:\test.txt");
        System.Byte[]               byte           = reader.CurrentEncoding.GetBytes(reader.ReadToEnd());
        System.IO.Stream            stream         = new System.IO.MemoryStream(byte);

        sysMailBuilder.setSubject("Regarding - sending mail");
        sysMailBuilder.setFrom("XXX@yyy.com");
        sysMailBuilder.addTo("yyy@zzz.com");
        sysMailBuilder.addAttachment(stream,'text file');
        smtp.sendNonInteractive(sysMailBuilder.getMessage());          
     
    }

}

Create and Save the text file in specific local directory

class CreateAndSaveTextFile
{      
   
    /// <summary>
    /// Create and Save the text file in specific local directory.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {    
        CreateAndSaveTextFile createAndSaveTextFile= new CreateAndSaveTextFile ();

        createAndSaveTextFile.generateFile();      
    }

    private void generateFile()
    {
        System.IO.StreamWriter sw;
        InteropPermission perm = new InteropPermission(InteropKind::ClrInterop);
       
        try
        {
            perm.assert();

            sw = new System.IO.StreamWriter(@"C:\test.txt"); // specify the local file path for new file.
            sw.WriteLine('line 1');
            sw.WriteLine('line2');
            sw.Dispose();

            CodeAccessPermission::revertAssert();
         
        }
        catch
        {
            error("Error");
        }
    }
}