【ASP.NET】公司內部寄信不能到外部問題(Exchange WebServices API 寄信)

首先先感謝某個重要的人囉,讓我了解有Exchange WebServices API這東西 : )

問題

想要從程式寄信(SMTP)至外部信箱都會出現錯誤(內部寄信可以成功),一只Reply不成功,用了老半天才知道系統權限問題,系統管理者也不可能給我權限。思考著同個SMTP Server為什麼我Outlook卻可以寄到外部信箱,而SMTP方法卻不行,接著找關鍵字,才知道公司的Outlook是用Exchange Server來處理,到Nuget找到了Exchange WebServices API,發現功能滿強大的,其實就是把我們平常Outlook操作變程式化,這裡我只有用到寄信的方法,其它方法這裡不做多介紹。

Exchange WebServices寄信方法

先到Nuget找到相關套件。

裝了套件之後就是來寫寄信程式囉,不難,我寫成一個Class,可自行更改需要的參數。

using System.Net;
using Microsoft.Exchange.WebServices.Data;

    public class SendmailByOutLook
    {
        /// <summary>
        /// Exchange寄信
        /// </summary>
        /// <param name="MailUser">Windows帳號</param>
        /// <param name="MailPasswords">Windows密碼</param>
        /// <param name="MailRecipient">收件人</param>
        /// <param name="MailSubject">信件標題</param>
        /// <param name="MailMain">信件內容</param>
        /// <param name="MailFrom">寄件人自定義名稱(需要有該帳號權限)</param>
        public void SendMail(string MailUser, string MailPasswords, string MailRecipient, 
        string MailSubject, string MailMain, string MailFrom)
        {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
            //Exchange Server 網域(AD)帳號密碼
            service.Credentials = new NetworkCredential(MailUser, MailPasswords);
            service.AutodiscoverUrl(MailFrom);

            EmailMessage emailMessage = new EmailMessage(service);
            
            //下行可以刪除,會以你登入網域帳號(AD)對應到寄件人
            emailMessage.From = MailFrom; 
            //目前參數寫單一收件者,可自行更改成List等方式一次寄多人
            emailMessage.ToRecipients.Add(MailRecipient); 
            emailMessage.Subject = MailSubject;
            emailMessage.Body = new MessageBody(MailMain);

            //Send
            emailMessage.SendAndSaveCopy();
        }
    }

當然引用方法很簡單,自行試試看囉。

SendmailByOutLook sbo = new SendmailByOutLook();

sbo.SendMail(MailUser, MailPasswords,MailRecipient, MailSubject, MailMain, MailFrom);

參考網址

Working with the EWS Managed API 2.0

Exchange Server Developer