我在服务器上运行作为预定作业的服务。它在一个没有自己邮箱的服务帐户下运行。我们希望它能够从团队的共享收件箱中发送电子邮件 在这里使用模仿是我尝试过的。
var service = new ExchangeService
{
TraceEnabled = true,
ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, Resources.EmailUsername)
};
service.AutodiscoverUrl(Resources.EmailUsername, RedirectionUrlValidationCallback);
var email = new EmailMessage(service);
if (!string.IsNullOrWhiteSpace(recipients))
{
foreach (var recipient in recipients.Split(','))
{
email.ToRecipients.Add(recipient.Trim());
}
}
email.Subject = subject;
email.Body = new MessageBody(BodyType.HTML, body);
if (attachmentName != null && attachment != null)
{
email.Attachments.AddFileAttachment(attachmentName, attachment);
}
email.Send();
它失败了,我得到一个例外说:
当您将请求作为没有邮箱的帐户发出时,您就是 必须为任何区分指定邮箱主smtp地址 文件夹ID。
答案 0 :(得分:0)
TraceEnabled
部分让我注意到xml中设置了MessageDisposition=SaveOnly
。我查了MessageDisposition,发现我想要SendOnly。
经过多次搜索,我最终来到这里:https://github.com/OfficeDev/ews-managed-api/blob/master/Core/ServiceObjects/Items/EmailMessage.cs
显示:
public void Send()
{
this.InternalSend(null, MessageDisposition.SendOnly);
}
那看起来就像我想要的那样......但是那时候:
private void InternalSend(FolderId parentFolderId, MessageDisposition messageDisposition)
{
this.ThrowIfThisIsAttachment();
if (this.IsNew)
{
if ((this.Attachments.Count == 0) || (messageDisposition == MessageDisposition.SaveOnly))
{
this.InternalCreate(
parentFolderId,
messageDisposition,
null);
}
else
{
// If the message has attachments, save as a draft (and add attachments) before sending.
this.InternalCreate(
null, // null means use the Drafts folder in the mailbox of the authenticated user.
MessageDisposition.SaveOnly,
null);
this.Service.SendItem(this, parentFolderId);
}
}
...
这两条评论是最具启发性的部分。附件将保存到运行该过程的用户的草稿文件夹中 为了解决这个问题,我们在调用Send时必须已经保存了该消息。让我们确保它保存在我们知道的邮箱中。因此,我们删除模拟,添加保存步骤,然后修改“发件人”字段。然后我们可以安全地发送消息,它将自己从草稿文件夹中删除。
var service = new ExchangeService
{
TraceEnabled = true
};
service.AutodiscoverUrl(Resources.EmailUsername, RedirectionUrlValidationCallback);
var email = new EmailMessage(service);
if (!string.IsNullOrWhiteSpace(recipients))
{
foreach (var recipient in recipients.Split(','))
{
email.ToRecipients.Add(recipient.Trim());
}
}
email.Subject = subject;
email.Body = new MessageBody(BodyType.HTML, body);
if (attachmentName != null && attachment != null)
{
email.Attachments.AddFileAttachment(attachmentName, attachment);
}
var folderId = new FolderId(WellKnownFolderName.SentItems, Resources.EmailUsername);
email.Save(folderId);
email.From = Resources.EmailUsername;
email.Send();