Send email in ASP.NET when database record is inserted

我是研究僧i 提交于 2019-12-02 16:58:40

问题


I have a ASP.NET FormView which allows for inserting of a record into a SQL Server table. How can I have an email be sent from the application once the record is successfully added to the table after the "Insert" button is clicked in an <InsertItemTemplate>?

I would like to be able to specify the to, from, subject, body, etc. of the email.

I'm using .NET 4.0 and C#.

.aspx page:

<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>

Code-behind:

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:


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!");
    }
  }
}


来源:https://stackoverflow.com/questions/16943469/send-email-in-asp-net-when-database-record-is-inserted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!