skip to Main Content

I am trying to send e-mail using graph API in the software. The message section of the e-mail I send is full, and there does not seem to be any problem there. But when sending it gives the error "Object reference not set to an instance of an object". After passing the Task.Delay method, I get this error. What am I doing wrong? I couldn’t figure it out.
This code :

try
{

  
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;


    //var url = GetMailConfig(configGroup: "EWS", configName: "EwsUrl");
    var username = GetMailConfig(configGroup: "EWS", configName: "Email");
    var password = GetMailConfig(configGroup: "EWS", configName: "Password");
    var fromAddress = GetMailConfig(configGroup: "SMTP", configName: "From");
    //var traceEnabled = GetMailConfig(configGroup: "EWS", configName: "TraceEnabled");
    var tenantId = GetMailConfig(configGroup: "EWS", configName: "TenantId");
    var clientId = GetMailConfig(configGroup: "EWS", configName: "ClientId");
    var access_token = "";
    var redirect_uri = "https://example.example.com/";
    var clienSecretId = "This is secret key";
    //var scopes = new[] { "https://outlook.office365.com/SMTP.Send" };
    var scopes = new[] {"https://graph.microsoft.com/.default" };



    var pca = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithClientSecret(clienSecretId)
    .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
    .Build();



    var authProvider = new DelegateAuthenticationProvider(async (request) =>
    {

        try
        {


            var result = await pca.AcquireTokenForClient(scopes).ExecuteAsync();

            

            request.Headers.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
        }
        catch (Exception exp)
        {
            
        }

    });


    GraphServiceClient graphClient = new GraphServiceClient(authProvider);

    var message = new Message
    {
        Subject = mailTemplate.Subject,
        From = new Recipient() { EmailAddress = new Microsoft.Graph.EmailAddress { Address = "[email protected]" } },
        Body = new ItemBody
        {
            ContentType = Microsoft.Graph.BodyType.Html,
            Content = mailTemplate.Body
        },

    };

    MailMessage mail = new MailMessage();


    var attachments = new MessageAttachmentsCollectionPage();

    if (mailTemplate.Cc != null && mailTemplate.Cc.Any())
        message.CcRecipients = mailTemplate.Cc.Select(x => new Recipient()
        {
            EmailAddress = new Microsoft.Graph.EmailAddress
            {
                Address = x
            }
        });



    if (mailTemplate.To != null && mailTemplate.To.Any())
        message.ToRecipients = mailTemplate.To.Select(x => new Recipient()
        {
            EmailAddress = new Microsoft.Graph.EmailAddress
            {
                Address = x
            }
        });

    var saveToSentItems = false;


    System.Threading.Tasks.Task.Run(async () =>
    {
        try
        {
            
            await Task.Delay(TimeSpan.FromSeconds(5));
            await graphClient.Me
           .SendMail(message, saveToSentItems)
           .Request()
           .PostAsync();
        }
        catch (Exception ex)
        {

            
        }

    });


}
catch (Exception exp)
{

    isSentMailSuccess = false;
}
return isSentMailSuccess;

 
            await Task.Delay(TimeSpan.FromSeconds(5));
            await graphClient.Me
           .SendMail(message, saveToSentItems)
           .Request()
           .PostAsync();

This code has exception.

I examined the code lines one by one, but I couldn’t find a way.

2

Answers


  1. Chosen as BEST ANSWER

    This is stacktrace :

       at Microsoft.Graph.HttpProvider.<SendAsync>d__18.MoveNext()
    

    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Graph.BaseRequest.d__35.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Graph.BaseRequest.d__30.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at Infrastructure.Services.MailManager.<>c__DisplayClass6_0.<b__3>d.MoveNext() in C:UsersNuevosourcereposDevelopmentsrcInfrastructureServicesMailManager.cs:line 249


  2. You can’t call /me endpoint (graphClient.Me.xxx) when using authentication with client id and client credentials.

    Your are not authenticated as any user.

    So, either change the code to

    await graphClient.Users["{user-id}"]
               .SendMail(message, saveToSentItems)
               .Request()
               .PostAsync();
    

    or change the authentication to get access on behalf of a user.

    Also the stack trace would be useful, it’s not clear what exactly is null and throws the exception.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search