Knowledgebase (2300)

Sending emails from a C# application is a common task in business and enterprise development. Whether you're delivering a project update, sending alerts, or automating reporting workflows, reliable email functionality is essential.
In this article, we’ll walk through how to send emails in C# using Spire.Email for .NET, a powerful component that simplifies SMTP communication and email formatting. We'll explore SMTP configuration, Gmail integration, HTML and plain-text content, file attachments, and multiple recipients.
Table of Contents
- 1. Project Setup
- 2. Send a Plain-Text Email via SMTP
- 3. Send HTML Email with Attachments via Gmail SMTP
- 4. Advanced Email Features with Spire.Email
- 5. Common Errors and Troubleshooting
- 6. Use Cases for Spire.Email
- 7. Free License
- 8. FAQ
1. Project Setup
To begin, create a .NET project (Console App or ASP.NET) and add the Spire.Email for .NET package.
Install via NuGet:
Install-Package Spire.Email
Or manually download the Spire.Email package and reference the Spire.Email.dll from your local installation package.
2. Send a Basic Email via SMTP in C#
The example below shows how to use Spire.Email to send a plain-text email through an SMTP server.
using Spire.Email;
using Spire.Email.Smtp;
// Configure the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.example.com";
smtp.Port = 587;
smtp.Username = "your@example.com";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Create maill addresses
MailAddress sender = new MailAddress("your@example.com", "Sender Name");
MailAddress recipient = new MailAddress("recipient@example.com", "Recipient Name");
MailMessage message = new MailMessage(sender, recipient);
// Set the email content
message.Subject = "Test Email";
message.BodyText = "This is a plain-text test email.";
// Send the email
smtp.SendOne(message);
Explanation:
- Uses MailAddress and MailMessage from Spire.Email
- Establishes a secure SMTP connection using ConnectionProtocols.StartTls
The screenshot below shows the actual email received using the above SMTP code.

3. Send HTML Email with Attachments via Gmail SMTP in C#
The following C# code example demonstrates how to send an HTML-formatted email using Gmail SMTP, including multiple recipients, a file attachment, and plain-text fallback for clients that do not support HTML.
using Spire.Email;
using Spire.Email.Smtp;
// Create MailAddress objects
MailAddress from = new MailAddress("your@gmail.com", "Your Name");
MailAddress to1 = new MailAddress("user1@example.com", "User One");
MailAddress to2 = new MailAddress("user2@example.com", "User Two");
// Create a mail message
MailMessage message = new MailMessage(from, to1);
message.To.Add(to2);
message.Cc.Add(new MailAddress("cc@example.com", "CC Person"));
message.Bcc.Add(new MailAddress("bcc@example.com"));
// Set the body HTML and text for the message
message.Subject = "Monthly Report - June 2025";
message.BodyHtml = "<h2 style='color:#2E86C1;'>Report Summary</h2><p>Please see the attached PDF report.</p>";
message.BodyText = "Report Summary - please see the attached PDF.";
// Add an attachment to the email
Attachment attachment = new Attachment(@"Sample.pdf");
message.Attachments.Add(attachment);
// Configure the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Username = "your@gmail.com";
smtp.Password = "your_app_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Sen the email
smtp.SendOne(message);
Explanation:
- Uses MailAddress, MailMessage, Attachment, and SmtpClient from Spire.Email
- Combines BodyHtml and BodyText to support HTML and plain-text email clients
- Adds multiple recipients via To.Add(), Cc.Add(), and Bcc.Add()
- Sends email securely through Gmail using ConnectionProtocols.StartTls
Gmail requires App Passwords if 2FA is enabled.
The following screenshot shows the HTML-formatted email with rich text, CC and BCC recipients, and a PDF attachment, as received from Gmail SMTP.

Related article: How to Send an Email with Attachments in C#
4. Advanced Email Features with Spire.Email
This section demonstrates advanced C# email-sending capabilities using Spire.Email, including embedded images and batch dispatch.
// Prepare an email with embedded image
MailMessage message = new MailMessage(
new MailAddress("your@domain.com", "Sender"),
new MailAddress("client@domain.com", "Client"));
message.Subject = "Branding Update";
message.BodyHtml = "<h1>Our New Logo</h1><img src=\"cid:logo\">";
message.BodyText = "Please view this message in HTML to see the image.";
Attachment logo = new Attachment(@"C:\Images\logo.png");
logo.ContentId = "logo";
logo.DispositionType = "Inline";
message.Attachments.Add(logo);
// Prepare a second email
MailMessage message2 = new MailMessage(
new MailAddress("your@domain.com"),
new MailAddress("sales@domain.com"));
message2.Subject = "Weekly Summary";
message2.BodyText = "This is an automated weekly update.";
// Create SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.domain.com";
smtp.Port = 587;
smtp.Username = "your@domain.com";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Send one email
smtp.SendOne(message);
// Send emails in batch
smtp.SendSome(new List<MailMessage> { message, message2 });
Explanation:
Attachment.ContentIdandDispositionType = "Inline"allow inline images using CID references in HTML.SendOne()sends a single message.SendSome()sends multiple messages as a batch. Ideal for scheduled reports or group notifications.
The following screenshot shows an email with an embedded company logo and a plain-text fallback, demonstrating how Spire.Email renders HTML content with inline images.

You may also like: Creating MSG Files with RTF Body and Attachments Using C#
5. Common Errors and Troubleshooting
| Error | Likely Cause |
|---|---|
| Authentication failed | Incorrect credentials or missing app password |
| Secure connection required | Use StartTLS or SSL in ConnectionProtocols |
| HTML content not displaying | Ensure BodyHtml and fallback BodyText are set |
| File not found | Incorrect file path for attachment |
6. Use Cases for Spire.Email
Spire.Email for .NET is suitable for:
- Daily/weekly automated reporting
- User signup and notification emails
- Order confirmations with attachments
- Form submission alerts
- Embedded-image newsletters
Its clean API removes the need to manually handle SMTP headers, MIME formatting, and encoding issues.
Conclusion
With Spire.Email for .NET, developers can quickly build robust and flexible email-sending features directly into C# applications. Whether the goal is to deliver transactional messages, generate styled reports, or dispatch scheduled newsletters, this component provides a clean, reliable API that simplifies every step of the process.
By supporting plain-text and HTML formats, attachments, Gmail SMTP, embedded images, and batch sending, Spire.Email helps streamline email integration without the overhead of external dependencies.
7. Apply for a Free Temporary License
To remove the evaluation warning in the email body or attachment footer, you can apply for a free temporary license:
Request a Free 1-Month License
Simply fill out the form and follow the instructions to apply the license in your project. This enables full feature access during evaluation.
8. FAQ
How to send HTML email in C#?
You can set the BodyHtml property of the MailMessage object to send an HTML email using Spire.Email. You can also include BodyText as a fallback for clients that don't support HTML.
How to send email to multiple recipients in C#?
Add multiple recipients using message.To.Add(), message.Cc.Add(), and message.Bcc.Add() methods. Spire.Email supports To, Cc, and Bcc fields.
How to use SMTP to send email in ASP.NET or MVC projects?
The SMTP usage in ASP.NET or MVC is the same as in Console applications. Simply configure the SmtpClient with host, port, credentials, and use the same SendOne() or SendSome() methods to dispatch your message.

Modern business systems, from retail checkout lanes to warehouse inventory tracking, rely heavily on barcode scanning, and Python-based solutions have become a popular choice due to their versatility and ease of use. In this article, we’ll explore how to read barcodes in Python using the Spire.Barcode for Python library, covering setup, scanning from image files or bytes, and customization options for improved accuracy.
Table of Contents:
- Python Library for Reading Barcodes
- Integrate Spire.Barcode into Your Python Application
- Read a Barcode from an Image File
- Read Multiple Barcodes from an Image File
- Read Barcodes from Image Bytes
- Adjust Barcode Recognition Settings
- Conclusion
- FAQs
Python Library for Reading Barcodes
Spire.Barcode for Python is a powerful library specifically crafted for creating and reading barcodes in Python applications. The library supports a variety of barcode formats, including:
- 1D Barcodes : Such as Code 128, Code 39, EAN-13, and UPC-A.
- 2D Barcodes : Including QR Code, DataMatrix, and PDF417.
Notable Features of Spire.Barcode
- Format Support : Capable of reading barcodes from various image formats, including PNG, JPG, BMP, GIF, and TIFF.
- Batch Scanning : Enables the detection of multiple barcodes within a single image file.
- Recognition Accuracy : Utilizes advanced algorithms to deliver reliable barcode detection.
- Customization : Allows users to specify barcode types and enable checksum verification for enhanced recognition efficiency.
This library provides the capability to read barcodes from both image files and bytes, along with extensive customization options to meet diverse requirements.
Integrate Spire.Barcode into Your Python Application
To get started with Spire.Barcode, you first need to install the library. You can do this via pip. Open your terminal and run:
pip install spire.barcode
Once you have installed the library, you will need a license key to unlock its full capabilities. You can obtain a trial license from our website. and set up the library in your Python script:
from spire.barcode import *
License.SetLicenseKey("your license key")
Now that you have the library in place, you can begin reading barcodes using Python.
Read a Barcode from an Image File in Python
Reading a single barcode from an image file is straightforward with Spire.Barcode. Here's how you can do it:
from spire.barcode import *
# Apply license key to unlock full capabilities
License.SetLicenseKey("your license key")
# Read barcode from an image file
result = BarcodeScanner.ScanOneFile("C:/Users/Administrator/Desktop/qr_code.png")
# Print the result
print(result)
Explanation
- License.SetLicenseKey() : Initializes the library with your license key.
- BarcodeScanner.ScanOneFile() : Reads a single barcode from the specified image file.
- The result is printed to the console, displaying the barcode's data.
Output:

Read Multiple Barcodes from an Image File in Python
If you need to read multiple barcodes from a single image file, Spire.Barcode makes this easy as well. Here’s an example:
from spire.barcode import *
# Apply license key to unlock full capabilities
License.SetLicenseKey("your license key")
# Read multiple barcodes from stream
results = BarcodeScanner.ScanFile("C:/Users/Administrator/Desktop/barcodes.jpg")
# Print results
print(results)
Explanation
- BarcodeScanner.ScanFile() : Scans the entire image for multiple barcodes.
- The results are stored as a list. Each element in the list contains the data from a detected barcode.
Output:

Read Barcodes from Image Bytes in Python
In addition to reading barcodes directly from files, Spire.Barcode for Python supports decoding barcodes from in-memory image bytes . This approach is useful when working with dynamically loaded images (e.g., from APIs, databases, or user uploads).
Here’s how to do it:
from spire.barcode import *
# Apply license key to unlock full capabilities
License.SetLicenseKey("your license key")
# Read an image file into bytes
image_path = "C:/Users/Administrator/Desktop/barcodes.jpg"
with open(image_path, "rb") as file:
image_bytes = file.read()
# Wrap bytes in Spire.Barcode's Stream object
stream = Stream(image_bytes)
# Read one barcode from stream
# result = BarcodeScanner.ScanOneStream(stream)
# Read multiple barcodes from stream
results = BarcodeScanner.ScanStream(stream)
# Print results
print(results)
Explanation
- image_bytes: Raw binary data read from an image file (e.g., PNG, JPG) or other sources like APIs or databases.
- Stream (Spire.Barcode class): Converts image_bytes into an in-memory stream compatible with Spire.Barcode’s scanner.
- BarcodeScanner.ScanStream() : Scans the stream for barcodes and returns a list of detected barcodes.
Adjust Barcode Recognition Settings
The BarcodeScanner class provides various methods to customize barcode recognition settings. This can help improve detection accuracy and efficiency. Some of the key methods include:
- ScanOneFileBarCodeTypeIncludeCheckSum(fileName: str, barcodeType: BarCodeType, IncludeCheckSum: bool)
- ScanFileBarCodeTypeIncludeCheckSum(fileName: str, barcodeType: BarCodeType, IncludeCheckSum: bool)
- ScanOneStreamBarCodeTypeIncludeCheckSum(stream: Stream, barcodeType: BarCodeType, IncludeCheckSum: bool)
- ScanStreamBarCodeTypeIncludeCheckSum(stream: Stream, barcodeType: BarCodeType, IncludeCheckSum: bool)
Here’s an example of how to specify a barcode type and include checksum verification:
from spire.barcode import *
# Apply license key to unlock full capabilities
License.SetLicenseKey("your license key")
# Specify the barcode type (e.g., EAN13)
barcode_type = BarCodeType.EAN13
# Read a barcode from an image file with checksum included
result = BarcodeScanner.ScanOneFileBarCodeTypeIncludeCheckSum("C:/Users/Administrator/Desktop/EAN_13.png", barcode_type, True)
# Print the result
print(result)
Explanation
- BarcodeType : Specifies the type of barcode you want to scan.
- IncludeCheckSum (bool): Determines whether to verify the checksum during scanning. Setting it to True can help catch errors in data.
Conclusion
In this article, we explored how to read barcodes in Python using the Spire.Barcode library. We covered the setup process, reading single and multiple barcodes from image files, and reading from image bytes. Additionally, we discussed how to customize barcode detection settings for improved accuracy. With these tools at your disposal, you can easily integrate barcode scanning capabilities into your Python applications.
FAQs
Q1: What types of barcodes can I read with Spire.Barcode?
Spire.Barcode supports a wide range of barcode formats, including QR codes, UPC, EAN, Code 128, Code 39, and many others.
Q2: Do I need a license to use Spire.Barcode?
Yes, a license key is required to unlock the full functionality of the library. You can obtain a free 30-day trial license from our website.
Q3: Can I read barcodes from a webcam using Spire.Barcode?
While Spire.Barcode does not directly support webcam input, you can capture images from a webcam and then read barcodes from those images using the library.
Q4: How can I improve barcode scanning accuracy?
You can improve accuracy by specifying the barcode type and enabling checksum verification during scanning. Additionally, ensure that the images are clear and well-lit.
Q5. Can I generate barcodes using Spire.Barcode for Python?
Yes, Spire.Barcode supports both barcode recognition and generation. For detailed instructions, check out this tutorial: How to Generate Barcodes in Python: A Step-by-Step Guide.

QR codes have become a common part of modern applications — from user authentication and digital payments to product packaging and event tickets. In many of these scenarios, developers often need to read QR codes in C# as part of their workflow, especially when working with image-based inputs like scanned documents or uploaded files.
To handle such tasks reliably, a decoding method that’s both accurate and easy to implement is essential. In this tutorial, we’ll walk through a straightforward approach to reading QR codes from images using C#, with minimal setup and clean integration.
Quick Navigation
- Project Setup
- Read QR Code from Image Using C#
- Read QR Code from Stream Using C#
- Improve Accuracy and Handle Errors
- Bonus: Get QR Code Coordinates
- FAQ
- Final Thoughts
1. Project Setup
To begin, we’ll use a .NET barcode library that supports QR code decoding. In this guide, we demonstrate with Spire.Barcode for .NET, which provides a simple API for reading QR codes from image files and streams.
1.1 Install the Library via NuGet
You can install the library through NuGet Package Manager:
Install-Package Spire.Barcode
For basic scenarios, you can also use Free Spire.Barcode for .NET:
Install-Package FreeSpire.Barcode
1.2 Create a New Console Project
For demonstration, create a C# Console App in Visual Studio:
- Target .NET Framework, .NET Core/.NET 6+, ASP.NET, or Xamarin for cross-platform mobile development
- Add reference to Spire.Barcode.dll (if not using NuGet)
2. Read QR Code from Image in C#
To read QR codes from an image file in C#, you can simply use the static BarcodeScanner.Scan() method provided by the library. This method takes an image path and the BarCodeType as input and returns all decoded results that match the specified barcode type — in this case, QR codes.
This method supports scanning images in formats like JPG, PNG, and EMF. It’s the most direct way to scan QR code data in desktop applications or backend services that receive uploaded files.
2.1 Sample Code: Decode QR Code from an Image File
using Spire.Barcode;
class Program
{
static void Main(string[] args)
{
// Load the QR code image
string imagePath = @"C:\qr-code.png";
// Barcode scanner reads QR code from image file
string[] results = BarcodeScanner.Scan(imagePath, BarCodeType.QRCode);
// Display QR code result(s)
foreach (string result in results)
{
Console.WriteLine("QR Code Data: " + result + "\n");
}
}
}
The QR code image and the scan results from C# code:

2.2 Explanation
- Scan() reads and decodes all barcodes found in the image.
- BarCodeType.QRCode ensures only QR codes are detected (you can change it to detect other types).
- Returns an array in case the image contains multiple QR codes.
You may also like: How to Generate QR Codes Using C#
3. Read QR Code from Stream in C#
In web APIs or modern applications where images are processed in memory, you’ll often deal with Stream objects—such as when handling file uploads or reading from cloud storage.
The BarcodeScanner.Scan() method also accepts a Stream directly, allowing you to decode QR codes from memory streams without converting them to Bitmap.
using Spire.Barcode;
using System.IO;
class Program
{
static void Main(string[] args)
{
using (FileStream fs = new FileStream(@"C:\qr-code.png", FileMode.Open, FileAccess.Read))
{
// Directly scan the QR codes from the image stream
string[] results = BarcodeScanner.Scan(fs, BarCodeType.QRCode, false);
foreach (string result in results)
{
Console.WriteLine("QR Code Data: " + result);
}
}
}
}
This method is useful for WPF or ASP.NET Core apps that handle QR code images in memory.
Related article: Scan Barcodes from PDF Using C#
4. Improve Accuracy and Handle Errors
In real-world scenarios, QR code recognition may occasionally fail due to image quality or unexpected input issues. Here are best practices to improve decoding accuracy and handle failures in C#:
4.1 Boost Recognition Accuracy
- Use high-resolution images. Avoid blurred or overcompressed files.
- Ensure quiet zone (white space) around the QR code is preserved.
- Use formats like PNG for better clarity.
- Avoid perspective distortion — use straight, scanned images.
4.2 Add Robust Error Handling
Wrap your decoding logic in a try-catch block to prevent crashes and inform the user clearly:
try
{
string[] results = BarcodeScanner.Scan(imagePath, BarCodeType.QRCode);
if (results.Length == 0)
{
Console.WriteLine("No QR code found.");
}
else
{
Console.WriteLine("QR Code: " + results[0]);
}
}
catch (Exception ex)
{
Console.WriteLine("Error decoding QR code: " + ex.Message);
}
5. Bonus: Get QR Code Coordinates
Sometimes, you may need to locate the QR code’s exact position in the image—for cropping, overlay, or annotation. The ScanInfo() method helps retrieve bounding boxes:
BarcodeInfo[] results = BarcodeScanner.ScanInfo(imagePath, BarCodeType.QRCode);
foreach (BarcodeInfo result in results)
{
Console.WriteLine("Data: " + result.DataString);
Console.WriteLine($"Coordinates: " + string.Join(",", result.Vertexes.Select(p => $"({p.X},{p.Y})")) + "\n");
}
This provides both the data and the coordinates of each detected QR code.
The reading results:

6. FAQ
How to read QR code in C#?
You can use the Spire.Barcode for .NET library and its BarcodeScanner.Scan() method to read QR codes from image files or memory streams in just a few lines of code.
How do I read my own QR code image?
Load your QR code image file path into the scanner, or open it as a stream if you're working in a web or WPF application. The scanner will decode all readable QR codes in the image.
How to read barcodes in C# (not just QR codes)?
You can simply pass the image path to the Scan() method, and it will automatically detect and read all supported barcode types. To restrict detection to a specific type (e.g., only QR codes or Code128), pass the corresponding BarCodeType as the second parameter.
What is the best barcode reader library for C#?
Spire.Barcode for .NET is a popular choice for its simplicity, format support, and clean API. It supports both free and commercial use cases.
7. Final Thoughts
Reading QR codes in C# can be implemented with just a few lines of code using Spire.Barcode for .NET. It supports image and stream-based decoding, works well for desktop, server-side, or WPF applications, and offers solid performance with minimal setup.
You can further explore QR code generation, document integration, and real-time scanning workflows based on this foundation.
Need to unlock full barcode reading features?
Request a free temporary license and try the full capabilities of Spire.Barcode for .NET without limitations.