Send an email with SPHttpClient
-
05-02-2021 - |
Domanda
I'm working on a web part for SharePoint 2016 on-prem and I want to send an email from the current user. I cannot use @pnp/sp
library as it's not supported with TypeScript 2.2.2 and I'm unable to upgrade it. I'm using SPHttpClient post method, but it gives me error 400:
The property '__metadata' does not exist on type 'SP.Utilities.EmailProperties'. Make sure to only use property names that are defined by the type
const siteUrl = this.context.pageContext.web.absoluteUrl;
const emailUrl = siteUrl + '/_api/SP.Utilities.Utility.SendEmail';
const reqOptions: ISPHttpClientOptions = {
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose"
},
body: JSON.stringify({
'properties': {
'__metadata': { 'type': 'SP.Utilities.EmailProperties' },
'To': { 'results': ['email@email.com'] },
'Body': 'Ignore this test email.',
'Subject': 'Invoice Uploader Test Email'
}
})
};
this.context.spHttpClient.post(emailUrl, SPHttpClient.configurations.v1, reqOptions)
.then((response: SPHttpClientResponse) => {
console.log(`Status code: ${response.status}`);
console.log(`Status text: ${response.statusText}`);
response.json().then((responseJSON: JSON) => {
console.log(responseJSON);
});
})
.catch((err) => {
console.log(err);
});
What is the corect syntax of such request?
Soluzione
You need to add an additional header, odata-version
and set it to 3
.
This error happens because SPFx's built-in SPHttpClient uses the odata-version
header whose value is set to 4.
So, simply change it as below and check:
const reqOptions: ISPHttpClientOptions = {
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"odata-version":"3.0",
},
// rest of your code
}
Referenced from:
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange