ASP.NET使用COM組件調用OUTLOOK2016發送郵件

一個簡單的例子,主要點在於outlook的設置.

程式很簡單,在debug時能正常發送郵件,但是在發佈到IIS後卻不能正常發送郵件。

那麼就需要設置Component Services...

注意使用comexp.msc -32 命令打開

具體可參考http://www.cnblogs.com/allenfly/p/6647164.html

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <asp:Button runat="server" ID="MailTest" OnClick="MailTest_Click" Text="Mail"/>
    <asp:Label runat="server" ID="ShowMessage" />
</asp:Content>
protected void MailTest_Click(object sender, EventArgs e)
        {
            try
            {
                this.ShowMessage.Text = String.Empty;
                Outlook.Application olApp = new Outlook.Application();
                Outlook.MailItem mailItem = (Outlook.MailItem)olApp.CreateItem(Outlook.OlItemType.olMailItem);
                mailItem.To = "****@***.COM";
                mailItem.Subject = "郵件標題";
                mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
                string content = "just a test";
                mailItem.HTMLBody = content;

                string smtpAddress = ConfigurationManager.AppSettings["MailSTMP"].ToString();
                mailItem.SendUsingAccount = GetAccountForEmailAddress(olApp, smtpAddress);
                ((Outlook._MailItem)mailItem).Send();
                mailItem = null;
                olApp = null;
                this.ShowMessage.Text = "ok";
            }
            catch (Exception ex)
            {
                this.ShowMessage.Text = ex.ToString();
            }
        }

        private static Outlook.Account GetAccountForEmailAddress(Outlook.Application application, string smtpAddress)
        {
            // Loop over the Accounts collection of the current Outlook session.
            Outlook.Accounts accounts = application.Session.Accounts;
            foreach (Outlook.Account account in accounts)
            {
                // When the email address matches, return the account.
                if (account.SmtpAddress == smtpAddress)
                {
                    return account;
                }
            }
            // If you get here, no matching account was found.
            throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!",
                smtpAddress));
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章