- Make sure the user has an O365 license.
- Make sure you are using the application context to send mail on behalf of the user, not the delegated context.
Refer to the complete sample code:
final ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
.clientId("xxxxxxxxxxxxxx")
.clientSecret("xxxxxxxxxxxxx")
.tenantId("xxxxxxxxxxxxxxxxxxxx")
.build();
List<String> scopes = new ArrayList<>();
scopes.add("https://graph.microsoft.com/.default");
final TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(scopes, clientSecretCredential);
final GraphServiceClient graphClient =
GraphServiceClient
.builder()
.authenticationProvider(tokenCredentialAuthProvider)
.buildClient();
Message message = new Message();
message.subject = "xxxxxxxxxxxxxx";
ItemBody body = new ItemBody();
body.contentType = BodyType.TEXT;
body.content = "xxxxxxxxxxxx";
message.body = body;
LinkedList<Recipient> toRecipientsList = new LinkedList<Recipient>();
Recipient toRecipients = new Recipient();
EmailAddress emailAddress = new EmailAddress();
emailAddress.address = "xxxxxxxxxxxxx";
toRecipients.emailAddress = emailAddress;
toRecipientsList.add(toRecipients);
message.toRecipients = toRecipientsList;
LinkedList<Recipient> ccRecipientsList = new LinkedList<Recipient>();
Recipient ccRecipients = new Recipient();
EmailAddress emailAddress1 = new EmailAddress();
emailAddress1.address = "xxxxxxxxxxxxxxxxx";
ccRecipients.emailAddress = emailAddress1;
ccRecipientsList.add(ccRecipients);
message.ccRecipients = ccRecipientsList;
boolean saveToSentItems = false;
graphClient.users("xxxxxxxxxxxxxxxxx")
.sendMail(UserSendMailParameterSet
.newBuilder()
.withMessage(message)
.withSaveToSentItems(saveToSentItems)
.build())
.buildRequest()
.post();
Hope this helps.
If the reply is helpful, please click Accept Answer and kindly upvote it. If you have additional questions about this answer, please click Comment.