Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. Sending Calendar Events Using .ICS File in ASP.NET

Sending Calendar Events Using .ICS File in ASP.NET

Date- Mar 11,2024 Updated Jan 2026 6556 Free Download
ICS Event

Sending Calendar Events Using .ICS File in ASP.NET

In this article, we'll explore how to send calendar events via email using .ICS files in an ASP.NET application. We'll walk through the process step-by-step and explain the provided code snippet along the way.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  1. Visual Studio or any other preferred code editor.
  2. Basic knowledge of ASP.NET MVC framework.
  3. Access to an SMTP server to send emails.

Implementation

We'll create a method in our ASP.NET MVC controller that generates an .ICS file representing the event and attaches it to an email. Let's break down the provided code snippet:

<!-- 
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web.Mvc;

namespace ICSEvent.Controllers
{
    public class HomeController : Controller
    {
        // Index action method
        public ActionResult Index()
        {
            return View();
        }

        // Action method to create and send an event
        public ActionResult CreateEvent(string receiverEmail)
        {
            try
            {
                // Retrieve sender's email credentials and mail server settings from configuration
                string senderEmail = ConfigurationManager.AppSettings["SenderEmail"];
                string senderPassword = ConfigurationManager.AppSettings["SenderPassword"];
                string mailServer = ConfigurationManager.AppSettings["Host"];
                string attendeesEmail = ConfigurationManager.AppSettings["Attendees"];

                // Define email subject and body
                string subject = "Appointment Invite";
                string body = "Please find the attached invite";

                // Create an email message
                MailMessage message = new MailMessage(senderEmail, receiverEmail, subject, body);

                // Load attendees from configuration
                List<string> attendees = new List<string>() { attendeesEmail };

                // Generate meeting request content
                string calendarContent = GenerateICSInviteBody("Code2night", attendees, "Testing Calendar Event", "Add Email body along with event", "Test Location", DateTime.Now.AddHours(2), DateTime.Now.AddHours(5), isCancel: false);
                byte[] calendarBytes = Encoding.UTF8.GetBytes(calendarContent);

                // Create attachment
                Attachment calendarAttachment = new Attachment(new MemoryStream(calendarBytes), "AppointmentInvite.ics", "text/calendar");

                message.Attachments.Add(calendarAttachment);

                // Create SMTP client and send email
                using (SmtpClient client = new SmtpClient(mailServer))
                {
                    client.UseDefaultCredentials = false;
                    client.Credentials = new NetworkCredential(senderEmail, senderPassword);
                    client.Send(message);
                    ViewBag.Message = "Email sent successfully.";
                }
            }
            catch (Exception ex)
            {
                ViewBag.Error = "Failed to send email. Error: " + ex.Message;
            }

            return View("Index");
        }

        // Method to generate meeting request content in .ICS format
        private static string GenerateICSInviteBody(string organizer, List<string> attendees, string subject, string description, string location, DateTime startTime, DateTime endTime, int? eventID = null, bool isCancel = false)
        {
            StringBuilder str = new StringBuilder();

            // Begin calendar
            str.AppendLine("BEGIN:VCALENDAR");
            str.AppendLine("PRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN");
            str.AppendLine("VERSION:2.0");
            str.AppendLine(string.Format("METHOD:{0}", (isCancel ? "CANCEL" : "REQUEST")));
            str.AppendLine("BEGIN:VEVENT");

            // Event details
            str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", startTime.ToUniversalTime()));
            str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmss}", DateTime.UtcNow));
            str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", endTime.ToUniversalTime()));
            if (isCancel)
            {
                str.AppendLine("STATUS:CANCELLED");
            }
            str.AppendLine(string.Format("LOCATION: {0}", location));
            str.AppendLine(string.Format("UID:{0}", (eventID.HasValue ? "Event" + eventID : Guid.NewGuid().ToString())));
            str.AppendLine(string.Format("DESCRIPTION:{0}", description.Replace("\n", "<br>")));
            str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", description.Replace("\n", "<br>")));
            str.AppendLine(string.Format("SUMMARY:{0}", subject));

            // Organizer and attendees
            str.AppendLine(string.Format("ORGANIZER;CN=\"{0}\":MAILTO:{1}", organizer, "test@123.com"));
            str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", string.Join(",", attendees), string.Join(",", attendees)));

            // Alarm
            str.AppendLine("BEGIN:VALARM");
            str.AppendLine("TRIGGER:-PT15M");
            str.AppendLine("ACTION:DISPLAY");
            str.AppendLine("DESCRIPTION:Reminder");
            str.AppendLine("END:VALARM");

            // End event and calendar
            str.AppendLine("END:VEVENT");
            str.AppendLine("END:VCALENDAR");

            return str.ToString();
        }

        // About action method
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

        // Contact action method
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
    }
}
-->

Explanation

The GenerateICSInviteBody method generates the meeting request content in .ICS format based on the provided parameters.

The CreateEvent action method is invoked when a request is made to create an event. It takes the recipient's email address as a parameter.<,p>

Inside the method:

Sender's email credentials and mail server settings are retrieved from the application configuration.

An email message is created with the provided subject, body, and recipient's email address.

Attendees' email addresses are loaded from configuration.

A .ICS file representing the event is generated using the GenerateICSInviteBody method.

The .ICS file is attached to the email message.

The email is sent using an SMTP client configured with sender's credentials and mail server settings.

Exceptions are caught, and an error message is displayed if sending fails.

The GenerateICSInviteBody method generates the meeting request content in .ICS format based on the provided parameters.

Other action methods (Index, About, Contact) are provided as placeholders for the respective views.

Here's an explanation of what each part of the method does:

  • Begin calendar: Specifies the start of the calendar file.
  • Event details: Specifies the details of the event, including start and end times, location, description, summary, etc.
  • Organizer and attendees: Specifies the organizer and attendees of the event.
  • Alarm: Specifies an alarm to remind attendees of the event.
  • End event and calendar: Specifies the end of the event and calendar sections.

Add textbox to add receiver email on view

Copy following code on the view. From here we will add on which email we will send the email. So that will be receiver email

<main>
    @using (Html.BeginForm("CreateEvent", "Home"))
    {
        <input type="text" class="form-control" name="receiverEmail" placeholder="Receiver Email"/>
<input type="submit" class="btn btn-success" value="Send Event Invite"/> } </main>

Add SMTP Keys to Web.config

You have to add following keys in the web.config file. Don't forget to replace the values with your original values.

   <add key="SenderEmail" value="YourSenderEmail" />
   <add key="SenderPassword" value="YourPassword" />
   <add key="Host" value="YourMailServer" />
   <add key="Attendees" value="Test@gmail.com" />


Run-

Now run the application and you will notice this screenSending Calendar Events Using ICS File in ASPNET


Here you have to add any email id, and click on send Event invite. Following is the .ics content that you can see

Sending Calendar Events Using ICS File in ASPNET 2

Check email on Receiver email account

Sending Calendar Events Using ICS File in ASPNET 3

Conclusion

In this article, we learned how to send calendar events via email using .ICS files in an ASP.NET MVC application. By following these steps, you can easily integrate calendar event scheduling features into your web applications.This is how we can create appointments using .ics file in asp.net.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

How to Encrypt and Decrypt Password in Asp.Net
May 15, 2022
Exception Handling Asp.Net Core
Aug 05, 2020
HTTP Error 500.31 Failed to load ASP NET Core runtime
Aug 23, 2022
How to implement Paypal in Asp.Net Core
Oct 30, 2022
Previous in ASP.NET Core
How to read json file in asp.net Core
Next in ASP.NET Core
How to fix Xml Injection vulnerability in asp.net (CWE-91)
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,925 views
  • 2
    Error-An error occurred while processing your request in .… 11,259 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 216 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,449 views
  • 5
    Mastering Unconditional Statements in C: A Complete Guide … 21,488 views
  • 6
    Mastering JavaScript Error Handling with Try, Catch, and F… 147 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,217 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • Task Scheduler in Asp.Net core 17573 views
  • Implement Stripe Payment Gateway In ASP.NET Core 16822 views
  • Send Email With HTML Template And PDF Using ASP.Net C# 16580 views
  • How to implement Paypal in Asp.Net Core 8.0 12956 views
  • HTTP Error 502.5 - ANCM Out Of Process Startup Failure 12816 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor