How to Send Emails Using Microsoft 365 Graph API in .NET Apps
Integrate secure mail-sending capabilities into your .NET applications with support for message composition, OAuth2 authentication, and file attachments.
Download Free TrialSend an Email in C# with Microsoft 365 Graph API
Integrating the Microsoft Graph API into .NET applications enables developers to streamline the process of sending messages via Microsoft 365 services. Aspose.Email for .NET simplifies this process, offering enhanced features such as attachment handling, tracking and secure communication. The library enables you to create and deliver personalised, high-performance email communications directly from your .NET applications.
Key Advantages of Using Aspose.Email with Microsoft Graph
No SMTP or Basic Authentication Required - Use secure modern token-based authentication (OAuth2).
Microsoft 365 & Outlook Integration - Connect to Microsoft 365 mailboxes and services easily.
Enterprise-Ready for .NET Developers - Designed for scalability, reliability, and corporate mail workflows.
Fully Managed API - No External Dependencies - All-in-one .NET library, no need for Graph SDK or third-party clients.
Supports .NET Framework & .NET Core / .NET 6+ - Compatible with modern and legacy .NET environments.
Quick Deployment with Minimal Configuration - Easy-to-use API with sample code for fast implementation.
Code Sample
Experience the ease of integrating Microsoft 365 email sending into your .NET application with the built-in Graph client from Aspose.Email.
Send email sample code - C#
var client = GraphClient.GetClient(authProvider);
var message = new MailMessage(...);
client.Send(message);
How It Works
Microsoft Graph is a RESTful web API that enables access to Microsoft 365 services, including the ability to send emails. When sending emails via Microsoft Graph, requests are sent using HTTP POST to the /sendMail endpoint, along with the message payload. This payload is typically a JSON object that contains the message content (recipients, subject, body, etc.) and any attached files.
Upon receiving the request, MS Graph processes it and responds with an HTTP status code. A successful sending operation returns a 202 Accepted response, indicating the message has been queued for delivery. Handling these responses allows developers to ensure successful communication or debug any issues that may arise.
Authenticating Microsoft Graph Requests
Calling Microsoft Graph isn’t as simple as sending an HTTP request—you first need to handle authentication. The Graph API is protected by Azure Active Directory (Azure AD), which means you must obtain an access token before making any request. This access token specifies what operations you’re allowed to perform, based on permissions granted during the authentication process.
To authenticate, you first need to set up an app registration in Azure AD, define the required permissions, and then request an access token using the appropriate OAuth flow. Once you have the token, include it in the Authorization header of your requests.
Aspose.Email for .NET simplifies the process of obtaining and managing the access token, ensuring that the application can securely interact with Microsoft Graph. By implementing its ITokenProvider interface, developers can efficiently retrieve the OAuth 2.0 token required for authentication. Once an app registration has been set up in the Azure portal and the necessary permissions, such as Mail.Send, have been granted, developers can use the library features to incorporate extensive email functionalities into their applications.
Begin with a few essential steps:
- Register your application in the Azure portal and grant permissions such as
Mail.Sendfor sending emails. - Obtain an Access Token: Implement the ITokenProvider interface of the Aspose.Email for .NET to retrieve the OAuth 2.0 token required for authentication.
- Install Aspose.Email for .NET via NuGet or by downloading its DLL file.
By following these steps you’ll be well-equipped to start coding.
Understanding Microsoft Graph Request and Response
Request: The data such as message subject, body, recipient details, and attachments, is structured in a JSON format. When the Send method is called, this data is serialized and sent as a POST request to the Microsoft Graph /sendMail endpoint.
Response: The response from the Graph API is returned as a status code. A 202 Accepted response indicates successful transmission, while error codes such as 401 Unauthorized or 403 Forbidden may suggest issues with authentication or permissions.
The .NET library provides built-in features for forming, sending requests, and parsing responses when interacting with external services like Microsoft Graph. These functionalities allow developers to streamline communication with Microsoft 365 services (e.g., Outlook, Calendar, Contacts) without needing to manually craft HTTP requests or parse raw JSON responses.
Forming Requests:
Aspose.Email simplifies the creation of requests by providing specific classes and methods that abstract the complexity of request formation. For instance, developers can interact with emails, calendars, and contacts through intuitive APIs without manually building the required Graph requests.Sending Requests:
The library includes built-in mechanisms to send requests directly to services like Microsoft Graph. Instead of dealing with authentication and HTTP methods manually, Aspose.Email handles the process behind the scenes. This includes adding necessary headers like authorization tokens and content types, ensuring the request is properly formatted for successful communication with Microsoft services.Parsing Responses:
With support for response parsing, it can convert raw JSON or XML responses into structured objects, such as MailMessage, CalendarEvent, or Contact. This eliminates the need for developers to handle JSON parsing directly. The parsed data can be used immediately within the application, making the integration process more seamless and efficient.
These features allow developers to focus more on business logic rather than managing the underlying complexities of interacting with mail services.
Full C# Code Example for Sending Emails with OAuth2 and Aspose.Email
The following example shows the complete process of sending an email using the Graph API via Aspose.Email for .NET. A few lines of code allow you to generate an OAuth2 access token, initialize the Graph client, compose a message, and send it:
- Create an instance of IGraphClient by calling GetClient method.
- Initialize an eml object of MailMessage class, set its properties.
- Send the message using the Send method of the library.
Full OAuth2 and Microsoft Graph integration example
using Aspose.Email;
using Aspose.Email.Clients.Graph;
// Generate the access token
AccessTokenProvider tokenProvider = new AccessTokenProvider();
// Create a Graph client
IGraphClient client = GraphClient.GetClient(tokenProvider, "tenant ID");
// Create a new message
var eml = new MailMessage(fromAddress, toAddress, subject, body);
// Send message
client.Send(eml);
Send Emails with Attachments
Sending emails with attachments through Microsoft Graph is simple and efficient with the Aspose.Email for .NET library. Attachments can be any file type, such as documents, images, or PDFs, which are sent alongside the email message. This is particularly useful for sharing resources like reports, presentations, or other vital documents directly through your .NET application.
In the following code snippet, attachments are added to the MailMessage object before the email is sent:
Send email sample code - C#
// Add attachments to the message
Attachment attachment = new Attachment("path_to_attachment");
eml.Attachments.Add(attachment);
How Attachments Are Processed
- Loading Attachments: The attachment is loaded from the file path specified (“path_to_attachment”), which could be a local file or a stream. The Attachment class allows you to add any file type as an attachment, making it highly flexible.
- Adding to the Email: Once the attachment is created, it is added to the email message using the Attachments.Add() method. This method appends the file to the MailMessage object’s attachment collection, which is automatically included when the message is sent via MS Graph.
- Sending the Email: Once the attachments have been added to the message, the Send method from the IGraphClient interface sends the email with all attached files.
Handling Multiple Attachments
You can easily add multiple attachments by repeating the process for each file. Here’s how to attach more than one file:
Attachment attachment1 = new Attachment("file1.pdf");
Attachment attachment2 = new Attachment("image.png");
eml.Attachments.Add(attachment1);
eml.Attachments.Add(attachment2);
Attachment Size Limits
It’s important to note that Microsoft Graph enforces size limits for email messages. The total size of an email, including attachments, must not exceed 25 MB. If you need to send larger files, consider uploading them to a cloud storage service (like OneDrive) and sending the file link instead.
Want More? Explore Full Microsoft Graph Support
Aspose.Email for .NET offers an extended Microsoft 365 integration via Graph API. You can also:
Manage folders, messages, and drafts
Work with attachments and categories
Handle contacts, calendar events, notebooks, and more
Explore full Microsoft Graph features.
Install the .NET API
Spare a minute to install the library into your project and start building secure, scalable Microsoft 365 email solutions with Aspose.Email for .NET. Choose the most convenient way:
- Use NuGet Package Manager
- Reference the required assemblies
- Or simply use the following command within the Package Manager Console in Visual Studio:
Command
PM> Install-Package Aspose.Email