Prerequisites
- Install packages:
Azure.IdentityandMicrosoft.Graph. - Register an application in Azure Entra ID and grant
Mail.Sendpermissions (Application or Delegated)
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Users.Item.SendMail;
// Credentials
string tenantId = "YOUR_TENANT_ID";
string clientId = "YOUR_CLIENT_ID";
string clientSecret = "YOUR_CLIENT_SECRET";
string userId = "sender@yourdomain.com"; // User ID or User Principal Name
string filePath = "C:\\document.pdf";
byte[] fileBytes = await File.ReadAllBytesAsync(filePath);
string base64Content = Convert.ToBase64String(fileBytes);
var attachment = new FileAttachment
{
OdataType = "#microsoft.graph.fileAttachment",
Name = "document.pdf",
ContentType = "application/pdf",
ContentBytes = Convert.FromBase64String(base64Content)
};
var scopes = new[] { "https://graph.microsoft.com/.default" };
// Authenticate using Client Secret
var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(credential, scopes);
// Create the message
var requestBody = new SendMailPostRequestBody
{
Message = new Message
{
Subject = "Hello from Microsoft Graph",
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = "This is a test email sent using C# and Microsoft Graph."
},
ToRecipients = new List<Recipient>
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "recipient@example.com"
}
}
},
Attachments = new List<Attachment> { attachment }
},
SaveToSentItems = true
};
// Send the email
await graphClient.Users[userId].SendMail.PostAsync(requestBody);
1031300cookie-checkC# Send mail with Microsoft Graph