How to send an email with the microsoft java sdk in koltin using the Microsoft graph api V6

49 Views Asked by At

Here is a non-functional example to try to send an email with the Microsoft Graph V6 java sdk

Dependencies - Gradle Koltin DSL

    implementation("jakarta.annotation:jakarta.annotation-api:2.1.1")
    implementation("com.azure:azure-identity:1.11.4") //authentification
    implementation("com.microsoft.graph:microsoft-graph:6.4.0") // Microsoft graph for sending emails

V6 seems not to cause any errors here is the authentication and message creation part I followed the following example https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=java


val clientId = ""
val tenantId = ""
val clientSecret = ""

            val scopes = arrayOf("https://graph.microsoft.com/.default")

            val credential =
                ClientSecretCredentialBuilder().clientId(clientId).tenantId(tenantId).clientSecret(clientSecret).build()
                    ?: throw Exception("Unexpected error")

            val graphClient = GraphServiceClient(credential, *scopes)

            // ---------------------------------


            // Prepare the email message
            val message = Message()
            message.subject = "Meet for lunch?"
            val body = ItemBody()
            body.contentType = BodyType.Html // Set content type to text
            body.content = "The new cafeteria is open."
            message.body = body


            // Add recipient to the 'To' list
            val toRecipients = LinkedList<Recipient>()
            val toRecipient = Recipient()
            val toEmailAddress = EmailAddress()
            toEmailAddress.address = "[email protected]" // Recipient email address
            toRecipient.emailAddress = toEmailAddress
            toRecipients.add(toRecipient)
            message.toRecipients = toRecipients


            // Add recipient to the 'CC' list
            val ccRecipients = LinkedList<Recipient>()
            val ccRecipient = Recipient()
            val ccEmailAddress = EmailAddress()
            ccEmailAddress.address = "[email protected]" // CC recipient email address
            ccRecipient.emailAddress = ccEmailAddress
            ccRecipients.add(ccRecipient)
            message.ccRecipients = ccRecipients


            // Create SendMailPostRequestBody and set the message and other properties
            val sendMailPostRequestBody = SendMailPostRequestBody()
            sendMailPostRequestBody.message = message
            sendMailPostRequestBody.saveToSentItems = false // Do not save the email to 'Sent Items'


            val emailSender = "[email protected]"

V5 I can't build a functional email sender using the Microsoft V6 graph API I just put it there as an example of what I had before



        this.emailSender?.let {
            graphClient.users(it)
                .sendMail(
                    UserSendMailParameterSet
                        .newBuilder()
                        .withMessage(message)
                        .withSaveToSentItems(true)
                        .build()
                )
                .buildRequest()
                .post()
        }

How can I replace this piece of V5 code in V6 to send an email, I think the V6 authentication I performed works

additional information

I'm trying to send an email from a defined email address Sender if I try to follow the microsoft example, which doesn't do it I get the following error

graphClient.me().sendMail().post(sendMailPostRequestBody, null)
// me() is not correct
Exception in thread "main" com.microsoft.graph.models.odataerrors.ODataError: /me request is only valid with delegated authentication flow.
    at com.microsoft.graph.models.odataerrors.ODataError.createFromDiscriminatorValue(ODataError.java:36)
    at com.microsoft.kiota.serialization.JsonParseNode.getObjectValue(JsonParseNode.java:210)
    at com.microsoft.kiota.http.OkHttpRequestAdapter.lambda$throwIfFailedResponse$0(OkHttpRequestAdapter.java:672)
    at com.microsoft.kiota.ApiExceptionBuilder.<init>(ApiExceptionBuilder.java:26)
    at com.microsoft.kiota.http.OkHttpRequestAdapter.throwIfFailedResponse(OkHttpRequestAdapter.java:671)
    at com.microsoft.kiota.http.OkHttpRequestAdapter.sendPrimitive(OkHttpRequestAdapter.java:341)
    at com.microsoft.graph.users.item.sendmail.SendMailRequestBuilder.post(SendMailRequestBuilder.java:58)
    at be.neuronics.microsoftgraphdemo.Main$Companion.main(Main.kt:71)
    at be.neuronics.microsoftgraphdemo.Main.main(Main.kt)
````


2

There are 2 best solutions below

0
Abneco On BEST ANSWER

I found how to make it work for those who are interested

useful link : https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=java#client-credentials-provider
https://github.com/microsoftgraph/msgraph-sdk-java/blob/dev/docs/upgrade-to-v6.md
https://learn.microsoft.com/en-us/graph/sdks/create-requests?tabs=java


            val clientId = ""
            val tenantId = ""; // or "common" for multi-tenant apps
            val clientSecret = ""


            val scopes = arrayOf("https://graph.microsoft.com/.default")

            val credential =
                ClientSecretCredentialBuilder().clientId(clientId).tenantId(tenantId).clientSecret(clientSecret).build()
                    ?: throw Exception("Unexpected error")

            val graphClient = GraphServiceClient(credential, *scopes)


//            val emailSender = "[email protected]"
//            val userList = graphClient.users().get()
//            for (user in userList.value) {
//                println(user.displayName)
//                println(user.mail)
//                println(user.id)
//                println("---")
//            }


            val emailSender = "[email protected]" // L'email à rechercher.
            val userList = graphClient.users().get()
            var userSelected: User? = null // Ce sera l'utilisateur trouvé, s'il existe.
            for (user in userList.value ) {
                if (user.mail == emailSender) {
                    userSelected = user
                    break
                }
            }

            if (userSelected != null) {
                println("Utilisateur trouvé !")
                println(userSelected.displayName)
                println(userSelected.mail)
                println(userSelected.id)
            } else {
                println("Aucun utilisateur trouvé avec l'email $emailSender.")
            }

            // ---------------------------------

            // Prepare the email message
            val message = Message()
            message.subject = "Meet for lunch?"
            val body = ItemBody()
            body.contentType = BodyType.Html // Set content type to text
            body.content = "The new cafeteria is open."
            message.body = body

            // Add recipient to the 'To' list
            val toRecipients = LinkedList<Recipient>()
            val toRecipient = Recipient()
            val toEmailAddress = EmailAddress()
            toEmailAddress.address = "[email protected]" // Recipient email address
            toRecipient.emailAddress = toEmailAddress
            toRecipients.add(toRecipient)
            message.toRecipients = toRecipients

            // Add recipient to the 'CC' list
            val ccRecipients = LinkedList<Recipient>()
            val ccRecipient = Recipient()
            val ccEmailAddress = EmailAddress()
            ccEmailAddress.address = "[email protected]" // CC recipient email address
            ccRecipient.emailAddress = ccEmailAddress
            ccRecipients.add(ccRecipient)
            message.ccRecipients = ccRecipients

            // Create SendMailPostRequestBody and set the message and other properties
            val sendMailPostRequestBody = SendMailPostRequestBody()
            sendMailPostRequestBody.message = message
            sendMailPostRequestBody.saveToSentItems = false // Do not save the email to 'Sent Items'

            graphClient.users().byUserId(userSelected?.id).sendMail().post(sendMailPostRequestBody)

10
Tanishq S On

Try this,

import com.microsoft.graph.authentication.TokenCredentialAuthProvider
import com.microsoft.graph.models.Message
import com.microsoft.graph.models.Body
import com.microsoft.graph.models.EmailAddress
import com.microsoft.graph.models.Recipient
import com.microsoft.graph.requests.GraphServiceClient

fun main() {
    // Replace with your information
    val clientId = "YOUR_CLIENT_ID"
    val clientSecret = "YOUR_CLIENT_SECRET"
    val tenantId = "YOUR_TENANT_ID"
    val scopes = listOf("https://graph.microsoft.com/.default")

    // Configure authentication provider
    val tokenCredentialAuthProvider = TokenCredentialAuthProvider(clientId, clientSecret, tenantId, scopes)

    // Initialize GraphServiceClient
    val graphClient = GraphServiceClient.builder()
        .authenticationProvider(tokenCredentialAuthProvider)
        .buildClient()

    // Create the email message
    val message = Message()
    message.subject = "Test Email"
    message.body = Body().content("This is a test email")

    // Set recipient
    val emailAddress = EmailAddress()
    emailAddress.address = "[email protected]"
    val recipient = Recipient()
    recipient.emailAddress = emailAddress
    message.toRecipients = listOf(recipient)

    // Send the email
    graphClient.me().sendMail(message).buildRequest().post()
}