You need to meet the following points:
- You must have Mail.Send delegation permissions, you can use jwt.ms to parse your access token to view
scp
claims:
2.Ensure that your account has an Exchange online license under O365 subscription. See: assign licenses to one user.
My code for your reference:
using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace devicecode
{
class Program
{
static async Task Main(string[] args)
{
string graphScope = "User.Read User.ReadBasic.All Mail.Send Mail.Send.Shared";
var graphScopes = graphScope.Split(' ').ToArray();
// Build a client application.
IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
.Create("My clienid")
.Build();
DeviceCodeProvider authProvider = new DeviceCodeProvider(publicClientApplication, graphScopes);
// Create an authentication provider by passing in a client application and graph scopes.
// Create a new instance of GraphServiceClient with the authentication provider.
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var message = new Message
{
Subject = "Meet for lunch?",
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = "The new cafeteria is open."
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "mytestaccount"
}
}
}
};
var saveToSentItems = false;
await graphClient.Me
.SendMail(message, saveToSentItems)
.Request()
.PostAsync();
}
}
}
print:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…