我们有许多 EWS 集成在几天前开始失败,无法发送带有附件的电子邮件。 如果我们跳过添加文件附件的两行,则发送运行正常。如果我们不需要电子邮件附件,那就太好了..
当不跳过附件行时,我会得到一个异常:
Microsoft.Exchange.WebServices.Data.ServiceResponseException H结果=0x80131500 消息=由于该项目已过期,无法执行该操作。重新加载该项目并重试。 来源=Mnt.Microsoft.Exchange.WebServices.Data
在研究这个问题时,我认为这与陈旧的变更密钥有关,但我不确定。
我尝试在 .send 操作之前使用 message.Load(new PropertySet(BasePropertySet.IdOnly)) 重新加载 id,但这会抛出一个异常,告诉我该项目没有 id....
系统.InvalidOperationException H结果=0x80131509 Message=此操作无法执行,因为此服务对象没有 Id。
这一切都运行良好,直到前天,没有人做任何改变。
任何帮助将不胜感激。
代码如下所示:
private static void SendMailOAUTH(MemoryStream ms, string FileName, string DList, string eMailSubject, string eMailBody)
{
string clientId = clientidvalue;
string clientSecret = clientsecretvalue;
string tenantId = tenantidvalue;
string userEmail = emailtoimpersonate;
string authority = $"https://login.microsoftonline.com/{tenantId}";
string[] scopes = { "https://outlook.office365.com/.default" };
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri(authority))
.Build();
Microsoft.Identity.Client.AuthenticationResult authResult = app.AcquireTokenForClient(scopes).ExecuteAsync().Result;
string accessToken = authResult.AccessToken;
var credentials = new OAuthCredentials(accessToken);
var ews = new ExchangeService
{
Credentials = credentials,
ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, userEmail),
Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx", UriKind.Absolute)
};
EmailMessage serviceMail = new(ews)
{
Subject = eMailSubject,
Body = eMailBody
};
serviceMail.Body.BodyType = BodyType.HTML;
string[] distroList = DList.Split(',');
foreach (string distro in distroList)
{
serviceMail.ToRecipients.Add(new EmailAddress(distro));
}
FileAttachment attachment = serviceMail.Attachments.AddFileAttachment(FileName, ms);
attachment.ContentType = "text/plain";
try
{
serviceMail.Send();
}
catch (Exception ex)
{
_ = ex.Message;
}
finally
{
ms.Dispose();
}
}
如果我们不添加附件,则消息会发送。 我被困住了,希望得到任何帮助。
经过一番研究,发现了这篇文章:
Exchange Web 服务 - 发送电子邮件错误“项目已过期”
据此我更改了附件并发送至此:
ms.Position = 0;
FileAttachment attachment = serviceMail.Attachments.AddFileAttachment(FileName, ms);
attachment.ContentType = "text/csv";
try
{
serviceMail.Save(WellKnownFolderName.Drafts);
EmailMessage draftMessage = EmailMessage.Bind(ews, serviceMail.Id);
draftMessage.SendAndSaveCopy();
}
现在代码似乎可以工作了......