ExchangeService与AutodiscoverUrl从错误的电子邮件地址发送

时间:2016-01-08 14:39:26

标签: c# outlook active-directory exchangewebservices

我正在使用此代码在winforms应用程序中通过Outlook发送电子邮件。

_exchangeService = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
_exchangeService.AutodiscoverUrl(_sender);
// ...
var email = new EmailMessage(_exchangeService)
{
    Subject = mailMessage.Subject, 
    Body = mailMessage.Body
};
email.ToRecipients.AddRange(mailMessage.To.Select(x => x.Address));
email.SendAndSaveCopy();

我在_exchangeService.AutodiscoverUrl(_sender);上设置了一个断点,我可以看到发件人 customerservice@mycompany.com 。但是,电子邮件正在“从”登录到winforms应用程序的实际用户发送。例如 person@mycompany.com

我们已尝试将Active Directory设置为“发送为”和“代表发送”,以允许此用户发送为customerservice@mycompany.com,但它没有帮助。我们还审核了此电子邮件的Exchange Server日志记录,并且显然是“发件人”发送给person@mycompany.com。

在此处的代码示例https://msdn.microsoft.com/en-us/library/dd634273中,他们使用NetworkCredential。我需要这样做吗?

为什么发件人(电子邮件发送 FROM )错误?

1 个答案:

答案 0 :(得分:2)

_exchangeService = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
_exchangeService.AutodiscoverUrl(_sender);
using email = new EmailMessage(_exchangeService)
{
    From = new MailAddress("customerservice@mycompany.com"),
    Subject = subject,
    Body = body
})
{
    //System.Net.Mail.Attachment attachment;
    //attachment = new System.Net.Mail.Attachment("your attachment file");
    //mail.Attachments.Add(attachment);
    message.To.Add(address);//Jess@Jess.com for example
    _exchangeService.Send(message);
};

如果你想要一个好的SendEmail方法,那么我也为你创建了一个静态方法

public static void SendEmail(string subject, string body)
{
    using (var client = new SmtpClient(utilities.EmailHost, 25))
    using (var message = new MailMessage()
    {
        From = new MailAddress(utilities.FromEmail),
        Subject = subject,
        Body = body
    })
    {
        System.Net.Mail.Attachment attachment;
        attachment = new System.Net.Mail.Attachment("your attachment file");
        mail.Attachments.Add(attachment);
        message.To.Add(address);//Jess@Jess.com for example
        client.Send(message);
    };
}