Automate Email Distribution of Income Tax Reports from Excel using C#
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (175).NET Core  (29).NET MAUI  (208)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (220)BoldSign  (15)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (67)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (101)Streamlit  (1)Succinctly series  (131)Syncfusion  (920)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (37)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (151)Chart  (132)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (633)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (41)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (508)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (11)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (597)What's new  (333)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Simplify Income Tax Reporting Automate Email Distribution from Excel Data in C#

Automate Email Distribution of Income Tax Reports from Excel using C#

The modernization of income tax report distribution has seen a significant shift towards automation and efficiency.

The Syncfusion Excel Library (XlsIO) is a C# library that provides a high-level API for creating and editing Excel files. Using this library, we’ll see how to fetch income tax reports from Excel data and send them through email automatically.

Note: If you are new to our Excel Library, it is highly recommended that you follow our Getting Started guide.

Getting started

For this blog, we’ll use an Excel document with taxpayer details like the image below.

Excel document showing taxpayer data
Excel document showing taxpayer data

Follow these steps to automate the income tax report email-sending process:

Step 1: First, let’s create a Windows application using Visual Studio.Create a Windows Forms Application

Step 2: Install the Syncfusion.XlsIO.WinForms NuGet package from NuGet package manager.Install Syncfusion.XlsIO.WinForms NuGet

Step 3: Add labels and text boxes in the Windows Forms UI using the WinForms ToolBox to get the input data from the Excel document.Add labels and text boxes to get the input data from Excel

  • The Taxpayer ID Column gets the column ID from the Excel document that contains the taxpayer ID.
  • The Email ID Column gets the column ID from the Excel file that contains the taxpayer’s email address.
  • The Excel File Path gets the file path of the Excel file containing the two previously listed details.
  • The Part A File Path gets the folder path of the income tax report—part A documents.
  • The Part B File Path gets the folder path of the income tax report—part B documents.
  • The Send Emails button will distribute the emails with proper attachments using the Excel data and attachment folder path details.

Enjoy a smooth experience with Syncfusion’s Excel Library! Get started with a few lines of code and without Microsoft or interop dependencies.

Step 4: Now, add the following code in the Form1.Designer.cs file to read the Excel documents and prepare an email with the income tax reports as attachments.

private void button1_Click(object sender, EventArgs e)
{
    string tinColumnId = panColumnIdTxtBox.Text.Trim('"');

    string emailColumnId = emailColumnIdTxtBox.Text.Trim('"');

    string excelFilePath = excelPathTxtBox.Text.Trim('"');

    string[] partAPathFiles = Directory.GetFiles(partAPathTxtBox.Text.Trim('"'));

    string[] partBPathFiles = Directory.GetFiles(partBPathTxtBox.Text.Trim('"'));

    if(partAPathFiles != null && partAPathFiles.Length == 0)
    {
        MessageBox.Show("No files found in Part A Path");
        return;
    }
    if(partBPathFiles != null && partBPathFiles.Length == 0)
    {
        MessageBox.Show("No files found in Part B Path");
        return;
    }
    if(!File.Exists(excelFilePath))
    {
        MessageBox.Show("Excel File not found");
        return;
    }
            
    using(ExcelEngine excelengine = new ExcelEngine())
    {
        IApplication application = excelengine.Excel;
        IWorkbook workbook = application.Workbooks.Open(excelFilePath);

        IWorksheet worksheet = workbook.Worksheets[0];

        IRange used = worksheet.UsedRange;

        int startRow = used.Row + 1;
        int endRow = used.LastRow;
        int statusColumn = used.LastColumn + 1;


        for(int row = startRow;row <= endRow;row++)
        {
            //Check the automation status of the tax payer report.
            if (worksheet.Range[row, statusColumn].Value == "Sent")
            {
                continue;
            }

            //Converting the Column Id to Column Index.
            IRange tinRange = worksheet[tinColumnId + row.ToString()];

            string tinID = worksheet.Range[row, tinRange.Column].Value;

            if(string.IsNullOrEmpty(tinID))
            {
                worksheet[row, statusColumn].Value = "TIN not found";
                continue;
            }
                    
            IRange emailRange = worksheet[emailColumnId + row.ToString()];

            string emailId = worksheet.Range[row, emailRange.Column].Value;

            string partAPath = partAPathFiles.Where(x => x.Contains(tinID + "_")).FirstOrDefault();

            if (partAPath == null)
            {
                worksheet[row, statusColumn].Value = "Part A File not found";
                continue;
            }
                    
            string partBPath = partBPathFiles.Where(x => x.Contains(tinID + "_")).FirstOrDefault();

            if (partBPath == null)
            {
                worksheet[row, statusColumn].Value = "Part B File not found";
                continue;
            }
            try
            {
                //Your mail ID.
                string from = "Yourmail@abc.com";

                string subject = "Form 16 for the financial year 2022- 2023";

                string mailBody = "<p>Hi,</p>\r\n<p>Thank you for your kind cooperation</p>\r\n<p>We have attached the form 16 document pertaining to the financial year (2022-2023) tax deduction. Employees are requested to review and file their Income tax return before due date.</p>\r\n<p>The last date of filing of Income Tax return is July 31, 2023.</p>\r\n<p>For further assistance, please feel free to get back to us.</p>\r\n<p>Thanks and Regards,</p>\r\n<p>Accounts Team.</p>";

                SendEMail(from, emailId, subject, mailBody, partAPath, partBPath);

                worksheet[row, statusColumn].Value = "Sent";
            }
            catch(Exception ex){
                worksheet[row, statusColumn].Value = ex.ToString();
            }
        }

        Thread.Sleep(1000);

        // Saving the workbook containing successful and failed records.

        string filePath = Path.GetFileNameWithoutExtension(excelFilePath) + "_Updated_" + DateTime.Now.ToString().Replace(":", "-") + Path.GetExtension(excelFilePath); 
               
        workbook.SaveAs(filePath);
                
    }
    Close();
            
}

The following code example shows how to send emails using an Outlook SMTP server with the help of the MailMessage feature.

private static void SendEMail(string from, string recipients, string subject, string body, string attachmentPartA, string attachmentPartB)
{
    //Creates the email message.
    var emailMessage = new MailMessage(from, recipients);
    //Adds the subject for email.
    emailMessage.Subject = subject;
    //Sets the HTML string as email body.
    emailMessage.IsBodyHtml = true;
    emailMessage.Body = body;
    emailMessage.Attachments.Add(new Attachment(attachmentPartA));
    emailMessage.Attachments.Add(new Attachment(attachmentPartB));

    //Sends the email with prepared message.
    using (var client = new SmtpClient())
    {
        //Update your SMTP Server address here.
        client.Host = "outlook.office365.com";
        client.UseDefaultCredentials = false;
        //Update your email credentials here. Need to generate app password for your email ID.
        client.Credentials = new System.Net.NetworkCredential(from, "apppassword");
        client.Port = 587;
        client.EnableSsl = true;
        client.Send(emailMessage);                
    }
}

After executing the previous code examples, the automation status will be stored in the Excel document like in the following image.

Automating income tax report email distribution using the Syncfusion Excel Library
Automating income tax report email distribution using the Syncfusion Excel Library

The same Excel document can be reused as an input Excel document if there are any failures in the automation and you want to run the automation only for the failed cases. This program will check the status of each taxpayer and send emails if there is any status other than Sent in the last column of the report.

Experience Syncfusion's Excel Framework in action through interactive demos, giving you the confidence to implement it in your projects immediately.

GitHub reference

You can download the complete code example for automating income tax report distribution through email on GitHub.

Wrapping up

Thanks for reading! In this blog, we’ve seen how to automate income tax report distribution via email using the Syncfusion Excel Library (XlsIO). Take a moment to peruse the documentation, where you’ll find other options and features, all with accompanying code samples. Using the library, you can also export Excel data to PDFsimagesdata tablesCSVTSV, HTML, collections of objectsODS, and more.

From simple data tables to complex financial models, Syncfusion empowers you to unleash your creativity and design stunning Excel spreadsheets.

Are you already a Syncfusion user? You can download the product setup here. If you’re not yet a Syncfusion user, you can download a free, 30-day trial here.

If you have any questions about these features, please let us know in the comments below. You can also contact us through our support forum, support portal, or feedback portal. We are happy to assist you!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed