插入数据库记录时在ASP.NET中发送电子邮件

时间:2013-06-05 15:09:13

标签: asp.net email-integration

我有一个ASP.NET FormView,它允许将记录插入SQL Server表。如果在&#34; Insert&#34;之后成功将记录添加到表中,如何从应用程序发送电子邮件?单击按钮<InsertItemTemplate>

我希望能够指定电子邮件的目的地,主题,正文等。

我使用的是.NET 4.0和C#。

.aspx页面:

<asp:FormView ID="formViewNewOrder" runat="server" DataKeyNames="Order_ID" DataSourceID="dsource1">
    <InsertItemTemplate>
    <b>Order Number:</b> <asp:TextBox ID="txtInsertOrderNo" runat="server" Text='<%# Bind("Order_Number") %>' />
    <br />
    <br />
    <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Insert" onclick="InsertButton_Click" />
            &nbsp; &nbsp; &nbsp; &nbsp; 
    <asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"    Text="Cancel" OnClick="InsertCancelButton_Click" />
    </InsertItemTemplate>
</asp:FormView>

代码隐藏:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
//Namespaces to be added?

protected void InsertButton_Click(object sender, EventArgs e)
{

    //Email code here ?

}

1 个答案:

答案 0 :(得分:1)

using System.Net.Mail;
using System.Net;

private void SendMail( string targetMail, 
                       string shownTargetName, 
                       string[] attachmentNames) {
  var fromAddress = new MailAddress("support@e-volution-software.de", "MailSendingProgram");
  var toAddress = new MailAddress(targetMail, shownTargetName);
  const string fromPassword = "12345isAbadPassword";
  subject = "Your Subject";
  body = 
        @"
          Here you can put in any text that will appear in the body
          multilined and even in <html>
        ";
  var smtp = new SmtpClient {
    Host = "smtp.1und1.de",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
  };

  using (var message = new MailMessage(fromAddress, toAddress) {
                             Subject = subject,
                             Body = body }
        ) {
    foreach(string filePath in attachmentNames[]) {
      Attachment attachMail = new Attachment(filePath);
      message.Attachments.Add(attachMail);
    }

    try {
      smtp.Send(message);
      MessageBox.Show("E-Mail sent!");
    } catch {
      MessageBox.Show("Sending failed, check your internet connection!");
    }
  }
}