Showing posts with label GraphServiceClient. Show all posts
Showing posts with label GraphServiceClient. Show all posts

Monday, March 10, 2025

Actionable Email Developer Dashboard

 Actionable Email Developer Dashboard:

Source:
Get started with actionable messages in Office 365: https://learn.microsoft.com/en-us/outlook/actionable-messages/get-started

Register your service with the actionable email developer dashboard: https://learn.microsoft.com/en-us/outlook/actionable-messages/email-dev-dashboard

1. Create Provider in ''Actionable Email Developer Dashboard - https://outlook.office.com/connectors/oam/publish "

2. Save "Provider Id (originator)" in notepad.

3. Approve submitted provider here: https://outlook.office.com/connectors/oam/admin





4. Prepare Json as below: 

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <script type="application/adaptivecard+json">{
    "type": "AdaptiveCard",
    "version": "1.0",
    "hideOriginalBody": true,
    "originator": "Provider Id (originator) : GUID from Previous step",
    "body": [
      {
        "type": "TextBlock",
        "text": "Visit the Outlook Dev Portal",
        "size": "large"
      },
      {
        "type": "TextBlock",
        "text": "Click **Learn More** to learn more about Actionable Messages!"
      },
      {
        "type": "Input.Text",
        "id": "feedbackText",
        "placeholder": "Let us know what you think about Actionable Messages"
      }
    ],
    "actions": [
      {
        "type": "Action.Http",
        "title": "Send Feedback",
        "method": "POST",
        "url": "https://...",
        "body": "{{feedbackText.value}}"
      },
      {
        "type": "Action.OpenUrl",
        "title": "Learn More",
        "url": "https://learn.microsoft.com/outlook/actionable-messages"
      }
    ]
  }
  </script>
</head>
<body>
Visit the <a href="https://learn.microsoft.com/outlook/actionable-messages">Outlook Dev Portal</a> to learn more about Actionable Messages.
</body>
</html>

C# Code:
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Users.Item.SendMail;

public class Program
{
    public static async Task Main(string[] args)
    {
        var clientId = "6e4110e7-e5b0d411db60";
        var tenantId = "bb55f134-82bf54373c6d";
        var clientSecret = "imx8Q~Q~AHcGN";
        var userFromEmail = "user1@test.onmicrosoft.com";
        var userToEmails = "user2@test.onmicrosoft.com,user3@test.onmicrosoft.com";

        var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
        var graphClient = new GraphServiceClient(credential);

        string adaptiveCardJson = @"<html>
        <head>
          <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
          <script type='application/adaptivecard+json'>{
            'type': 'AdaptiveCard',
            'version': '1.0',
            'hideOriginalBody': true,
            'originator': 'a115aabe-03994fbaf1d',
            'body': [
              {
                'type': 'TextBlock',
                'text': 'Visit the Outlook Dev Portal',
                'size': 'large'
              },
              {
                'type': 'TextBlock',
                'text': 'Click **Learn More** to learn more about Actionable Messages!'
              },
              {
                'type': 'Input.Text',
                'id': 'feedbackText',
                'placeholder': 'Let us know what you think about Actionable Messages'
              }
            ],
            'actions': [
              {
                'type': 'Action.Http',
                'title': 'Send Feedback',
                'method': 'POST',
                'url': 'https://...',
                'body': '{{feedbackText.value}}'
              },
              {
                'type': 'Action.OpenUrl',
                'title': 'Learn More',
                'url': 'https://learn.microsoft.com/outlook/actionable-messages'
              }
            ]
          }
          </script>
        </head>
        <body>
        Visit the <a href='https://learn.microsoft.com/outlook/actionable-messages'>Outlook Dev
        Portal</a> to learn more about Actionable Messages.
        </body>
        </html>";

        List<string> userToEmailList = new List<string>(userToEmails.Split(','));
        var message = new Message
        {
            Subject = "Test Subject",
            Body = new ItemBody
            {
                ContentType = BodyType.Html,
                Content = $"{adaptiveCardJson}"
            },
            ToRecipients = userToEmailList.Select(email => new Recipient { EmailAddress =
            new EmailAddress { Address = email } }).ToList(),
        };
        var sendMailRequest = new SendMailPostRequestBody { Message = message };
        await graphClient.Users[userFromEmail].SendMail.PostAsync(sendMailRequest);

        Console.ReadKey();
    }
}



OutPut:






Monday, March 3, 2025

Connect SharePoint using Azure App Application/Delegate Authentication in C#

1. Connect SharePoint using Azure App Application Authentication in C#
Create Azure app and give below Application permissions. 


using Azure.Identity;
using Microsoft.Graph;

public class Program
{
    public static async Task Main(string[] args)
    {
        string tenantId = "";
        string clientId = "";
        string clientSecret = "";
        string siteId = "283f598a-6b0f-4ba5-af06-c72a0cef8f42";
        string listId = "e9609d64-1f36-45a2-8260-743998ea2cd4";
        var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
        var graphClient = new GraphServiceClient(credential);
        var items = await graphClient.Sites[siteId].Lists[listId].Items.GetAsync();
        foreach (var item in items.Value)
        {
            Console.WriteLine($"Item ID: {item.Id}, Created By: {item.CreatedBy?.User?.DisplayName}");
        }
        Console.ReadKey();
    }
}



2. Connect SharePoint using Azure App Delegate Authentication in C#

Friday, January 19, 2024

Sent Email in C#

Sent Email in C#:

//Option 1:
using System;
using System.Net.Mail;
using System.Security;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApp
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Start....");
            string password = "password"; //ConfigurationManager.AppSettings["EmailPassword"];
            SecureString secure_passWord = new SecureString();
            foreach (char c in password.ToCharArray()) { secure_passWord.AppendChar(c); }
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            client.UseDefaultCredentials = false;
            client.EnableSsl = true;
            //client.Credentials = new NetworkCredential("abc@xyz.com", secure_passWord);
            client.Credentials = new NetworkCredential("abc@xyz.com", "password");
            client.Port = 587; //replace with actual value
            client.Host = "smpt.mail.com"; //replace with actual value
            //client.DeliveryMethod = SmtpDeliveryMethod.Network;
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("abc@xyz.com");
            mail.To.Add("def@xyz.com");
            mail.Subject = "Test Mail";
            mail.Body = "Test body";
            mail.BodyEncoding = Encoding.UTF8;
            mail.IsBodyHtml = true;
            client.Send(mail);
            Console.WriteLine("End....");
        }
    }
}


//Option 2:
//https://learn.microsoft.com/en-us/azure/communication-services/quickstarts/email/send-email?tabs=windows%2Cconnection-string&pivots=programming-language-csharp
//Quickstart: How to send an email using Azure Communication Service
using Azure;
using Azure.Communication.Email;
 
namespace SendEmail
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            string connectionString = "connectionString";
            EmailClient emailClient = new EmailClient(connectionString);
            var subject = "Welcome to Azure Communication Service Email APIs.";
            var htmlContent = "<html><body><h1>Quick send email test</h1><br/><h4>This email message is sent from Azure Communication Service Email.</h4><p>This mail was sent using .NET SDK!!</p></body></html>";
            var sender = "DoNotReply@fcc11977-0b46-46c9-a657-4216db032070.azurecomm.net";
            var recipient = "abc@xyz.com";
            try
            {
                Console.WriteLine("Sending email...");
                EmailSendOperation emailSendOperation = await emailClient.SendAsync(Azure.WaitUntil.Completed, sender, recipient, subject, htmlContent);
                EmailSendResult statusMonitor = emailSendOperation.Value;
                Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}");
                string operationId = emailSendOperation.Id;
                Console.WriteLine($"Email operation id = {operationId}");
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
            }
        }
    }
}


//Option 3:
using Microsoft.Identity.Client;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApp
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            //Required Azure Application Permissions : Mail.Send
            string clientId = "clientId";
            string clientSecret = "clientSecret";
            string tenantId = "tenantId";
            string userEmail = "abc@xyz.com"; // The user on behalf of whom you want to send the email
 
            var confidentialClient = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithClientSecret(clientSecret)
                .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
                .Build();
 
            var authResult = await confidentialClient.
                AcquireTokenForClient(new[] { "https://graph.microsoft.com/.default" })
                .ExecuteAsync();
 
            string accessToken = authResult.AccessToken;
 
            using (var httpClient = new HttpClient())
            {
                //Required Azure Application Permissions : Mail.Send
                var apiUrl = $"https://graph.microsoft.com/v1.0/users/{userEmail}/sendMail"; //Mail.Send
 
                var message = new
                {
                    message = new
                    {
                        subject = "Subject of the email",
                        body = new
                        {
                            content = "Body of the email",
                            contentType = "Text"
                        },
                        toRecipients = new[]
                        {
                        new { emailAddress = new { address = "def@xyz.com" } }
                    }
                    }
                };
 
                var jsonContent = new StringContent(JsonConvert.SerializeObject(message), Encoding.UTF8, "application/json");
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 
                var response = await httpClient.PostAsync(apiUrl, jsonContent);
 
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Email sent successfully.");
                }
                else
                {
                    Console.WriteLine($"Error: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
                }
            }
        }
    }
}


//Option 4:
//https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth-ropc
Microsoft identity platform and OAuth 2.0 Resource Owner Password Credentials
 
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApp
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            var clientId = "clientId";
            var tenantId = "tenantId";
            var clientSecret = "clientSecret";
            var userName = "userName";
            var userPassword = "userPassword";
            var requestUri = "https://login.microsoftonline.com/" + tenantId + "/oauth2/v2.0/token";
            var apiUrl = "https://graph.microsoft.com/v1.0/me/sendmail";
 
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
            request.Headers.Add("Cookie", "fpc=AohS41ndFd5KswGP3EyyEk11dsNQAQAAADIbQ90OAAAA; stsservicecookie=estsfd; x-ms-gateway-slice=estsfd");
            List<KeyValuePair<string, string>> collection = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("client_id", clientId),
                new KeyValuePair<string, string>("client_secret", clientSecret),
                new KeyValuePair<string, string>("username", userName),
                new KeyValuePair<string, string>("password", userPassword),
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("scope", "mail.send")
            };
            FormUrlEncodedContent content = new FormUrlEncodedContent(collection);
            request.Content = content;
            HttpResponseMessage response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string responseContent = await response.Content.ReadAsStringAsync();
            //Console.WriteLine(responseContent);
            dynamic jsonData = JsonConvert.DeserializeObject(responseContent);
            string accessToken = jsonData.access_token;
            Console.WriteLine(accessToken);
 
            var message = new
            {
                message = new
                {
                    subject = "Subject of the email",
                    body = new
                    {
                        content = "Body of the email",
                        contentType = "Text"
                    },
                    toRecipients = new[]
                    {
                        new { emailAddress = new { address = "user1@gmail.com" } }
                    }
                }
            };
            var jsonContent = new StringContent(JsonConvert.SerializeObject(message), Encoding.UTF8, "application/json");
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            HttpResponseMessage response1 = await client.PostAsync(apiUrl, jsonContent);
            if (response1.IsSuccessStatusCode)
            {
                Console.WriteLine("Email sent successfully.");
            }
            else
            {
                Console.WriteLine($"Error: {response1.StatusCode} - {await response1.Content.ReadAsStringAsync()}");
            }
            Console.ReadKey();
        }
    }
}


//Option 5:
Authenticate an IMAP, POP or SMTP connection using OAuth
https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth


Method 1:
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Users.Item.SendMail;

public class Program
{
    public static async Task Main(string[] args)
    {
        string tenantId = "tenantid";
        string clientId = "clientid";
        string clientSecret = "secret";
        string userFromEmail = "user1@domain.com";
        string userToEmail = "user2@domain.com";

        var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
        var graphClient = new GraphServiceClient(credential);
        List<string> userToEmailList = new List<string> { userToEmail };
        var message = new Message
        {
            Subject = "Test Subject",
            Body = new ItemBody
            {
                ContentType = BodyType.Html,
                Content = "Test Body"
            },
            ToRecipients = userToEmailList.Select(email => new Recipient { EmailAddress =             new EmailAddress { Address = email } }).ToList(),
        };
        var sendMailRequest = new SendMailPostRequestBody { Message = message };
        await graphClient.Users[userFromEmail].SendMail.PostAsync(sendMailRequest);         //With out Await and Async         //var sendMailTask = graphClient.Users[userFromEmail].SendMail.PostAsync(sendMailRequest);         //sendMailTask.ConfigureAwait(false).GetAwaiter().GetResult();
        Console.ReadKey();
    }
}

Method 2:
using MailKit;
using MailKit.Net.Imap;
using MailKit.Security;
using Microsoft.Identity.Client;
using MimeKit;
 
class Program
{
    private static async Task Main(string[] args)
    {
        var clientId = "-5a53-4525-afda-";
        var tenantId = "-02f1-478e-bc6a-";
        var clientSecret = "~J2EOPVNjynt-~AHcGN";
        var userEmail = "sreekanth@.onmicrosoft.com";
        var smtpHost = "smtp.office365.com";
        var smtpPort = 587;
 
        var app = ConfidentialClientApplicationBuilder.Create(clientId)
            .WithClientSecret(clientSecret)
            .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}/v2.0"))
            .Build();
       
        string[] scopes = new[] { "https://outlook.office365.com/.default" };
        var authToken = await app.AcquireTokenForClient(scopes).ExecuteAsync();
        var accessToken = authToken.AccessToken;
        //Console.WriteLine("accessToken: " + accessToken);
 
        //oauth2 1
        var oauth2_1 = new SaslMechanismOAuth2(userEmail, authToken.AccessToken);
        using (var client = new ImapClient(new ProtocolLogger("imapLog.txt")))
        {
            client.Connect("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
            //client.AuthenticationMechanisms.Remove("XOAUTH2");
            client.Authenticate(oauth2_1);
            var inbox = client.Inbox;
            inbox.Open(MailKit.FolderAccess.ReadOnly);
            Console.WriteLine("Total messages: {0}", inbox.Count);
            Console.WriteLine("Recent messages: {0}", inbox.Recent);
            client.Disconnect(true);
        }
 
        //oauth2 2
        var oauth2_2 = new SaslMechanismOAuth2(userEmail, authToken.AccessToken);
        var message = new MimeMessage();
        message.From.Add(new MailboxAddress("Sreekanth", userEmail)); // Your email 
        message.To.Add(new MailboxAddress("Sreekanth", userEmail)); // Replace with recipient's email 
        message.Subject = "Test Email with OAuth2";
        message.Body = new TextPart("plain")
        {
            Text = "This is a test email sent using OAuth2 authentication with SMTP."
        };
 
        using (var client = new MailKit.Net.Smtp.SmtpClient())
        {
            try
            {
                await client.ConnectAsync(smtpHost, smtpPort, SecureSocketOptions.StartTls);
                client.Authenticate(oauth2_2);
 
                await client.SendAsync(message);
                Console.WriteLine("Email sent successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error sending email: {ex.Message}");
            }
            finally
            {
                await client.DisconnectAsync(true);
            }
        }
 
        //oauth2 3
        var oauth2_3 = new SaslMechanismOAuth2(userEmail, authToken.AccessToken);
        using (var client = new ImapClient(new ProtocolLogger("imapLog.txt")))
        {
            client.Connect("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
            //client.AuthenticationMechanisms.Remove("XOAUTH2");
            client.Authenticate(oauth2_3);
            var inbox = client.Inbox;
            inbox.Open(MailKit.FolderAccess.ReadOnly);
            Console.WriteLine("Total messages: {0}", inbox.Count);
            Console.WriteLine("Recent messages: {0}", inbox.Recent);
            client.Disconnect(true);
        }
        Console.ReadKey();
    }
}
 

 

Featured Post

Microsoft Copilot Studio: The Complete Beginner to Advanced Guide

Microsoft Copilot Studio: The Complete Beginner to Advanced Guide Version: July 2026 | Audience: Beginners, Citizen Developers, Busine...

Popular posts