Search code examples
c#.netemailemail-validationsystem.net.mail

How do I add another email address in my C#?


I would like to add an extra email address for messages to be sent/forwarded to when the email form submit button is clicked, whats the easiest way to do this?

public partial class Contact : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
    string name = txtName.Text;
    string emailaddress = txtEmail.Text;
    string body = txtComment.Text;


    MailAddress From = new MailAddress(emailaddress);
    MailAddress To = new MailAddress("[email protected]");
    MailMessage email = new MailMessage(From, To);
    email.Subject = "Comment from Website from " + name;
    email.Body = body;

    SmtpClient smtp = new SmtpClient("smtp.1111.com");
    smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "1111111111");
    smtp.Send(email);
    email.Dispose();

    ClientScript.RegisterClientScriptBlock(this.GetType(), "Email Confirm", "alert('Email Sent!');", true);

    txtComment.Text = "";
    txtEmail.Text = "";
    txtName.Text = "";


}
protected void txtEmail_TextChanged(object sender, EventArgs e)
{

}
}

We'll say that my extra email address is smtp.2222.com [email protected] with an authentication of 22222. Thanks for looking folks.


Solution

  • Instead of using the To.Add method, you can pass a comma separated list of email address to MailMessage constructor which is a much better solution especially if you have more than a few email addresses to send the email to...

    var from = "[email protected]";
    var to = "[email protected],[email protected],[email protected]";
    var subject = "My Subject";
    var body = "Message Body";
    var message = new MailMessage(from, to, subject, body);
    

    will work just as well...