我正在尝试使用Outlook / Office 365 REST API发送电子邮件,我正在尝试将其作为一个地址发送给我作为"连接帐户"。尝试发送消息会返回“错误”。但是,API 将让我创建一个包含此地址的草稿。
此外,我可以发送API创建的草稿,我也可以从网络界面创建和发送此帐户。
有没有办法授权API能够将邮件作为已连接帐户的地址发送?
答案 0 :(得分:1)
不,API今天不支持此功能。它与您同意的权限范围有关。 “允许此应用随时发送邮件”涵盖从您的帐户发送,但不会从其他帐户发送,即使您已被授予访问权限。
答案 1 :(得分:0)
您可以考虑的另一件事是利用仅限App的身份验证。您可以将Azure AD App配置为仅具有应用程序身份验证。在此之后,所有请求都将代表该应用ID,您应该能够委派该应用ID以代表您想要的用户向任何人发送电子邮件。 以下是步骤:
配置Azure AD应用程序后,您可以参考 以下代表特定用户发送电子邮件的代码。
string tenantId = "yourtenant.onmicrosoft.com";
string clientId = "your client id";
string resourceId = "https://outlook.office.com/";
string resourceUrl = "https://outlook.office.com/api/v2.0/users/service@contoso.com/sendmail"; //this is your on behalf user's UPN
string authority = String.Format("https://login.windows.net/{1}", AUTHORITYURL, tenantId);
string certificatPath = @"c:\test.pfx"; //this is your certficate location.
string certificatePassword = "xxxx"; // this is your certificate password
var itemPayload = new
{
Message = new
{
Subject = "Test email",
Body = new { ContentType = "Text", Content = "this is test email." },
ToRecipients = new[] { new { EmailAddress = new { Address = "test@cotoso.com" } } }
}
};
//if you need to load from certficate store, use different constructors.
X509Certificate2 certificate = new X509Certificate2(certficatePath, certificatePassword, X509KeyStorageFlags.MachineKeySet);
AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);
ClientAssertionCertificate cac = new ClientAssertionCertificate(clientId, certificate);
//get the access token to Outlook using the ClientAssertionCertificate
var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceId, cac);
string token = authenticationResult.AccessToken;
//initialize HttpClient for REST call
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
client.DefaultRequestHeaders.Add("Accept", "application/json");
//setup the client post
HttpContent content = new StringContent(JsonConvert.SerializeObject(itemPayload));
//Specify the content type.
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
HttpResponseMessage result = await client.PostAsync(url, content);
if(result.IsSuccessStatusCode)
{
//email send successfully.
}else
{
//email send failed. check the result for detail information from REST api.
}
如需完整说明,请参阅我的博客Send email on behalf of a service account using Office Graph API
我希望它有所帮助,如果您有疑问,请告诉我。