一个简单的例子,主要点在于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)); }