create mailbox along with Create users graph api in o365 - microsoft-graph-api

We have a requirement to create office 365 user with mail account through create_user graph api. But user has been created successfully but mail account did not created.
Let us know api name to create user with mail account directly through api.

Microsoft Graph API doesn't has the feature. For mailbox creation, you need to use Exchange PowerShell to do it using New-Mailbox cmdlet. You can automate the Exchange PowerShell with .Net as well :)
For example,
$password = Read-Host "Enter password" -AsSecureString
New-Mailbox -UserPrincipalName chris#contoso.com -Alias chris -Database "Mailbox Database 1" -Name ChrisAshton -OrganizationalUnit Users -Password $password -FirstName Chris -LastName Ashton -DisplayName "Chris Ashton" -ResetPasswordOnNextLogon $true

To do this through the graph API you need to have a license that has Exchange Online as a service plan like Microsoft 365 F3 (SPE_F1), assign your new user one these licenses on creation and a Mailbox will be created for them:
Post the following:
{
"addLicenses": [
{
"skuId": "your SPE_F1 skuId number"
}
],
"removeLicenses": []
}
to:
https://graph.microsoft.com/v1.0/users/{user - id}/assignLicense/

Related

Graph Api to add external users to a group chat

is there a way to add an external member to the group [not the guest user who is part of the ADD]
the graph api seems to accept only the ADDconversation member ,
is it possible to add an external user ?
You need to invite them first, you can do so via the Azure AD (preview) module:
To send an invitation to your test email account, run the following PowerShell command (replace "John Doe" and john#contoso.com with your test email account name and email address):
New-MgInvitation -InvitedUserDisplayName "John Doe" -InvitedUserEmailAddress John#contoso.com -InviteRedirectUrl "https://myapplications.microsoft.com" -SendInvitationMessage:$true
The command sends an invitation to the email address specified.
Ref: https://learn.microsoft.com/en-us/azure/active-directory/external-identities/b2b-quickstart-invite-powershell
Or the corresponding Graph API endpoint:
POST https://graph.microsoft.com/v1.0/invitations
Content-type: application/json
{
"invitedUserEmailAddress": "admin#fabrikam.com",
"inviteRedirectUrl": "https://myapp.contoso.com"
}
Ref: https://learn.microsoft.com/en-us/graph/api/invitation-post?view=graph-rest-1.0&tabs=http

How do you (quickly) count AAD B2C users?

We're trying to count the number of user objects in a B2C tenant, which is somewhat large. When it was small, the simple/obvious hack of just reading all the users worked easily and quickly.
Get-AzADUser | Measure-Object
Now this takes an absurd amount of time (30+ mins, and wastes AAD processing, network bandwidth, etc). Handily, the Graph API includes an endpoint to request the number of objects! Hooray! ;) https://learn.microsoft.com/en-us/graph/api/user-list?view=graph-rest-beta&tabs=http#example-6-get-only-a-count-of-users
Connect-AzAccount
Set-AzContext -Tenant <your 'normal' AAD tenant>
$AzToken = Get-AzAccessToken -ResourceUrl https://graph.microsoft.com
Invoke-RestMethod -Method Get -Authentication Bearer -Token (ConvertTo-SecureString -AsPlainText -Force -String $AZAccess.Token) -Headers #{ConsistencyLevel = 'eventual'} -Uri https://graph.microsoft.com/beta/users/`$count
1234
But! When using this method to attempt to find how many B2C accounts we have:
Connect-AzAccount
Set-AzContext -Tenant <your 'B2C' AAD tenant>
$AzToken = Get-AzAccessToken -ResourceUrl https://graph.microsoft.com
Invoke-RestMethod -Method Get -Authentication Bearer -Token (ConvertTo-SecureString -AsPlainText -Force -String $AZAccess.Token) -Headers #{ConsistencyLevel = 'eventual'} -Uri https://graph.microsoft.com/beta/users/`$count
Invoke-RestMethod: {"error":{"code":"Request_BadRequest","message":"$count is not currently supported.","innerError":{"date":"2021-04-29T07:06:09","request-id":"xxx","client-request-id":"xxx"}}}
So, how do you count users in a large B2C tenant?
Unfortunately the endpoint is not supported yet for B2C tenant. Neither does https://graph.microsoft.com/beta/users?$count=true.
It's only available in normal AAD tenant.
Currently you need to list all the users and get their count using method/function from other library.
A similar post and answer here for your reference.
This is a bit manual, but whenever I need a quick count, I do the following:
Go to Azure Portal (for B2C Tenant)
All Users
Bulk operations
Download users (This will get me an excel pretty quick)
Start
Takes about 2 minutes to finish (~40k users)
Go to Bulk operation results in page menu on the left
Download Excel
sum of UPNs in the excel
This should work for a B2C Tenant , using Connect-AzureAD in the AzureAD Module
Connect-AzureAD -tenant xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
(Get-AzureADUser -all $true).Count

How to get RecipientTypeDetails through the MS Graph API

Is it possible to get the RecipientTypeDetails property of a mailbox through any (Graph) REST API? From my research I've been seeing No's as answers, but I didn't find any recent confirmation.
Thanks in advance!
I use exchange-online-powershell to get RecipientTypeDetails to retrieve all the mailboxes of a recipient type. I couple this with MS Graph. However, I couldn't retrieve the mailboxes of a certain type using MS graph.
So you can do something like this in powershell.
$recipientTypes = Get-Recipient -ResultSize unlimited
Then use it to retrieve mailboxes of a type and output to file. Unsure how you want to use it.
foreach($recType in $recipientTypes)
{
$mailboxes = (Get-Mailbox -Filter '(RecipientTypeDetails -eq $($recType))')
ConvertTo-Json -InputObject $mailboxes | Out-File ".\Mailboxes-$($recType).json"
}
The module I use is:
Install-Module -Name ExchangeOnlineManagement -RequiredVersion 2.0.4-Preview2 -AllowPrerelease`
it seems to be something exposed for Exchange on premises via a powershell cmlet named Get-Recipient. It is not exposed via Graph Rest Apis after inspecting the docs and playing around with graph explorer. The user object doesn't have a mailbox property, it has a messages collection.
In the docs there is guidance indicating that for cloud environments you can invoke the cmdlet with the RecipientTypeDetails set to GroupMailBox.

GET Channel ID using Youtube API v3 with Service Account

Good Day, I Try to Get Channel ID using service account, because I´m using it on other scopes on my project. But when I do request process its give me the service account information. i´m using php btw
Many thanks in advance and any help will be appreciated.
p.d. i´m replace real account info for dummy text.
And of Course the code :
$credentials_file = $this->key_dir . $this->key_file['title'];
$client = new \Google_Client();
$client->setAuthConfig($credentials_file);
$client->addScope('https://www.googleapis.com/auth/youtube');
$client->setApplicationName("Youtube Analytics");
$client->refreshTokenWithAssertion();
$token = $client->getAccessToken();
$accessToken = $token['access_token'];
if (!empty($accessToken)) {
$service = new \Google_Service_YouTube($client);
$data = $service->channels->listChannels('id,snippet', array('mine' => 'true'));
echo "id: " . $data->items[0]->id . "<br>";
echo "Kind: " . $data->items[0]->kind . "<br>";
echo "Snippet -> title : " . $data->items[0]->snippet['title'] . "<br>";
}
AFAIK, Youtube API doesn't support Service Account Flow. As described in the document :
The service account flow supports server-to-server interactions that do not access user information. However, the YouTube Data API does not support this flow. Since there is no way to link a Service Account to a YouTube account, attempts to authorize requests with this flow will generate a NoLinkedYouTubeAccount error.
Also in the Youtube v3 Google Service Account Access issue, "There are no plans to add support for Service Account authorization to YouTube Data API v3 calls." As stated in the related SO question #21890982 and #21057358 : you'll need your own account for that and you can create an authentication for services using V3 without user intervention.
Hope this helps.

Powershell EWS Send Email from Shared Mailbox

I am using Powershell and the Exchange Web Service (v1.2) to send an email through Office 365. As long as I use my credentials the script is able to send without an issue. However, for tracking purposes, on script errors I need to send the email from a shared mailbox instead of through my account. The error I get is:
Exception calling "AutodiscoverUrl" with "2" argument(s): "The Autodiscover service couldn't be located."
At F:\Scripting\1-Dev\Modules\Include.ps1:387 char:31
+ $service.AutodiscoverUrl <<<< ($Credential.UserName, {$true})
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
I'm sure the problem is authentication. How can I authenticate and send from a shared mailbox in o365?
EDIT:
Here is the code that I'm using to send the email:
Function Send-O365Email {
[CmdletBinding()]
param(
[Parameter(Position=1, Mandatory=$true)]
[String[]] $To,
[Parameter(Position=2, Mandatory=$true)]
[String] $Subject,
[Parameter(Position=3, Mandatory=$true)]
[String] $Body,
[Parameter(Position=4, Mandatory=$true)]
[System.Management.Automation.PSCredential] $Credential,
[Parameter(Mandatory=$false)]
[String]$PathToAttachment
)
begin {
#Load the EWS Managed API Assembly
Add-Type -Path 'C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll'
}
process {
#Create the EWS service object
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList Exchange2010_SP1
#Set the credentials for Exchange Online
$service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials -ArgumentList `
$Credential.UserName, $Credential.GetNetworkCredential().Password
#Determine the EWS endpoint using autodiscover
$service.AutodiscoverUrl($Credential.UserName, {$true})
#Create the email message and set the Subject and Body
$message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service
$message.Subject = $Subject
$message.Body = $Body
$message.Body.BodyType = 'HTML'
if (Test-Path $Attachment) {
$message.Attachments.AddFileAttachment("$Attachment");
}
#Add each specified recipient
$To | ForEach-Object {
$null = $message.ToRecipients.Add($_)
}
#Send the message and save a copy in the users Sent Items folder
try {
$message.SendAndSaveCopy()
}
catch [exception] {
Add-Content -Path $LOGFILE -Value "$_"
}
} # End Process
}
You may want to try the 2.0 assembly, though I don't think that is the issue http://www.microsoft.com/en-us/download/details.aspx?id=35371
My environment is a little different, in that our credentials and email address are not the same name. (one is initialLastName#Comp.com and the other is first.Last#Comp.com) so I have to be a little different in how I approach names, always needing a Credential and a MailBox name.
When I try to use a Resource account, I have to use my email for the autodiscovery. Possibly because the Service account doesn't have a user license. I am speculating.
I found a good amount of resources at http://gsexdev.blogspot.com/.
Specifically, this may be what you need:
## Optional section for Exchange Impersonation
# http://msdn.microsoft.com/en-us/library/exchange/dd633680(v=exchg.80).aspx
$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, "SupportResource#comp.com")
#or clear with
#$service.ImpersonatedUserId = $null
similar 'discussion' # EWS Managed API: how to set From of email? also.

Resources