我有一个JavaSpring项目,它使用Retrofit 2从微软API调用图形API。我能够进行身份验证,阅读邮箱和检索/阅读电子邮件。然而,我正在努力发送邮件。
我有以下发送电子邮件的代码:
权限:包含Mail. send
private String[] scopes = [
"openid",
"email",
"profile",
"User.Read",
"Mail.Read",
"Mail.Send",
"Mail.ReadWrite",
"Calendars.Read",
"Calendars.ReadWrite",
"Contacts.Read",
"Contacts.ReadWrite",
"offline_access"
];
改造电话:
@Headers("Content-Type: application/json")
@POST("/v1.0/me/sendMail")
Call<Message> sendMessage(
@Body String messageObject
);
发送的字符串是JSONString:
"{\"Message\":{\"toRecipients\":[{\"address\":\"test@test.be\",\"name\":\"test@test.be\"}],\"Body\":{\"ContentType\":\"text/html\",\"Content\":\"value(Email_body)=%3Cp%3Etesttext%3C%2Fp%3E\"},\"Subject\":\"testsubject\"},\"SaveToSentItems\":\"true\"}"
HTTP回应:
<-- 400 Bad Request https://graph.microsoft.com/v1.0/me/sendMail (101ms)
Cache-Control: private
Transfer-Encoding: chunked
Content-Type: application/json
request-id: 94d19c39-4b84-4ee9-98d2-d42d36886e40
client-request-id: 0c9d2c63-28bf-49c4-9ad6-08d81c6fd4b0
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"West Europe","Slice":"SliceC","Ring":"5","ScaleUnit":"003","RoleInstance":"AGSFE_IN_27"}}
Strict-Transport-Security: max-age=31536000
Date: Wed, 09 Oct 2019 07:41:54 GMT
{
"error": {
"code": "ErrorInvalidParameter",
"message": "The value of the parameter 'Message' is empty.",
"innerError": {
"request-id": "94d19c39-4b84-4ee9-98d2-d42d36886e40",
"date": "2019-10-09T07:41:54"
}
}
}
<-- END HTTP (253-byte body)
知道是什么导致了错误吗?
我相信当json数据实际发送时,您不应该使用双引号的转义字符。
因此,发出的字符串应该是未转义的,看起来像这样。
{"Message":{"toRecipients":[{"address":"test@test.be","name":"test@test.be"}],"Body":{"ContentType":"text/html","Content":"value(Email_body)=%3Cp%3Etesttext%3C%2Fp%3E"},"Subject":"testsubject"},"SaveToSentItems":"true"}
此外,你会发现
地址
不是toRecipients
的有效属性,您应该在emailAddress
属性name
属性无效,应删除。ContentType
值可以是text
或html
因此,发出的json应该看起来像这样。
{
"Message": {
"toRecipients": [
{
"emailAddress": {
address:"test@test.be"
}
}
],
"Body": {
"ContentType": "html",
"Content": "value(Email_body)=%3Cp%3Etesttext%3C%2Fp%3E"
},
"Subject": "testsubject"
},
"SaveToSentItems": "true"
}
您还可以在以下链接中阅读有关sendMail api的更多信息
https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0
所以我想通了,用改造2发布原始json的正确方法是:
@Headers("Content-Type: application/json")
@POST("/v1.0/me/sendMail")
Call<Message> sendMessage(
@Body HashMap<String, Object> messageObject
);