Sending Emails in ASP.NET and C# Console Applications Using SMTP Server

Sending Emails in ASP.NET and C# Console Applications Using SMTP Server
In this article [Show more]

    Sending Emails in ASP.NET and C# Console Applications Using SMTP Server

    Sending emails programmatically is a common requirement for many applications. In this guide, we'll explore how to send emails using an SMTP server in both ASP.NET applications and C# console applications. We’ll also cover how to attach files to your emails.

    1. Sending Email in ASP.NET Using SMTP Server

    ASP.NET applications often need to send emails for notifications, alerts, or user communication. Here's a step-by-step guide to sending an email using an SMTP server in an ASP.NET application.

    Step 1: Set Up SMTP Configuration

    First, you need to configure your SMTP settings in the appsettings.json file of your ASP.NET application.

     

    {
      "SmtpSettings": {
        "Host": "smtp.example.com",
        "Port": 587,
        "Username": "your-email@example.com",
        "Password": "your-email-password",
        "UseSsl": true
      }
    }
    

    Step 2: Create the Email Service

    Now, create a service class to handle email sending.

    using System.Net;
    using System.Net.Mail;
    
    public class EmailService
    {
        private readonly SmtpClient _smtpClient;
    
        public EmailService(IConfiguration configuration)
        {
            var smtpSettings = configuration.GetSection("SmtpSettings");
            _smtpClient = new SmtpClient(smtpSettings["Host"], int.Parse(smtpSettings["Port"]))
            {
                Credentials = new NetworkCredential(smtpSettings["Username"], smtpSettings["Password"]),
                EnableSsl = bool.Parse(smtpSettings["UseSsl"])
            };
        }
    
        public void SendEmail(string to, string subject, string body)
        {
            var mailMessage = new MailMessage
            {
                From = new MailAddress("your-email@example.com"),
                Subject = subject,
                Body = body,
                IsBodyHtml = true
            };
            mailMessage.To.Add(to);
    
            _smtpClient.Send(mailMessage);
        }
    }
    
    

    Step 3: Use the Email Service

    You can inject and use the EmailService in your controllers or services.

    public class HomeController : Controller
    {
        private readonly EmailService _emailService;
    
        public HomeController(EmailService emailService)
        {
            _emailService = emailService;
        }
    
        public IActionResult SendEmail()
        {
            _emailService.SendEmail("recipient@example.com", "Test Subject", "Test Body");
            return View();
        }
    }

     

    2. How to Send Email in C# Console Application

    Sending emails from a C# console application is similar to doing so in an ASP.NET application, but you don't have the ASP.NET infrastructure.

    Step 1: Configure SMTP Settings

    You can hardcode your SMTP settings or retrieve them from a configuration file.

     

    var smtpClient = new SmtpClient("smtp.example.com", 587)
    {
        Credentials = new NetworkCredential("your-email@example.com", "your-email-password"),
        EnableSsl = true
    };
    
    

    Step 2: Create and Send the Email

    Here’s a simple example of sending an email with a console application.

    using System;
    using System.Net;
    using System.Net.Mail;
    
    class Program
    {
        static void Main()
        {
            var smtpClient = new SmtpClient("smtp.example.com", 587)
            {
                Credentials = new NetworkCredential("your-email@example.com", "your-email-password"),
                EnableSsl = true
            };
    
            var mailMessage = new MailMessage
            {
                From = new MailAddress("your-email@example.com"),
                Subject = "Test Subject",
                Body = "Test Body",
                IsBodyHtml = true
            };
            mailMessage.To.Add("recipient@example.com");
    
            smtpClient.Send(mailMessage);
            Console.WriteLine("Email sent successfully!");
        }
    }
    

    3. C# Send Email with Attachment

    Adding attachments to your email is straightforward. Here’s how to do it in both ASP.NET and C# console applications.

    Sending Email with Attachment in ASP.NET

    Update your EmailService class to include an attachment.

    public void SendEmailWithAttachment(string to, string subject, string body, string attachmentPath)
    {
        var mailMessage = new MailMessage
        {
            From = new MailAddress("your-email@example.com"),
            Subject = subject,
            Body = body,
            IsBodyHtml = true
        };
        mailMessage.To.Add(to);
    
        if (!string.IsNullOrEmpty(attachmentPath))
        {
            var attachment = new Attachment(attachmentPath);
            mailMessage.Attachments.Add(attachment);
        }
    
        _smtpClient.Send(mailMessage);
    }
    

    Sending Email with Attachment in C# Console Application

    Similarly, you can modify the console application example to include an attachment.

    using System;
    using System.Net;
    using System.Net.Mail;
    
    class Program
    {
        static void Main()
        {
            var smtpClient = new SmtpClient("smtp.example.com", 587)
            {
                Credentials = new NetworkCredential("your-email@example.com", "your-email-password"),
                EnableSsl = true
            };
    
            var mailMessage = new MailMessage
            {
                From = new MailAddress("your-email@example.com"),
                Subject = "Test Subject",
                Body = "Test Body",
                IsBodyHtml = true
            };
            mailMessage.To.Add("recipient@example.com");
    
            var attachment = new Attachment("path-to-your-file");
            mailMessage.Attachments.Add(attachment);
    
            smtpClient.Send(mailMessage);
            Console.WriteLine("Email sent with attachment successfully!");
        }
    }
    

     

     

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments