Home > Backend Development > C++ > How to Send Emails Using ASP.NET C# and SMTP?

How to Send Emails Using ASP.NET C# and SMTP?

Mary-Kate Olsen
Release: 2025-01-17 15:36:14
Original
113 people have browsed it

How to Send Emails Using ASP.NET C# and SMTP?

Using ASP.NET C# to Send Emails via SMTP

This guide demonstrates how to send emails using ASP.NET C# and the Simple Mail Transfer Protocol (SMTP).

Understanding SMTP

SMTP (Simple Mail Transfer Protocol) is the standard protocol for sending emails. It requires an SMTP server to act as a relay between the sender and recipient. You'll need the server's address (the SMTP address) to configure your email sending functionality.

Implementing Email Sending in ASP.NET C#

To send emails in your ASP.NET C# application, create an ASPX page and its corresponding code-behind file. Use the following code in the code-behind:

<code class="language-csharp">using System.Net.Mail;
using System.Net;

protected void Btn_SendMail_Click(object sender, EventArgs e)
{
    // Email message details
    MailMessage mail = new MailMessage(
        txtFrom.Text, // Sender's email address
        txtTo.Text, // Recipient's email address
        txtSubject.Text, // Email subject
        txtBody.Text); // Email body

    // SMTP client configuration
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com"; // Replace with your SMTP server address
    smtp.Port = 587; // Replace with your SMTP server port
    smtp.EnableSsl = true; // Enable SSL for secure communication
    smtp.Credentials = new NetworkCredential("[email protected]", "yourPassword"); // Replace with your email and password

    // Send the email
    try
    {
        smtp.Send(mail);
        Label1.Text = "Email sent successfully!";
    }
    catch (Exception ex)
    {
        Label1.Text = "Error sending email: " + ex.Message;
    }
}</code>
Copy after login

Important Considerations:

Replace "smtp.gmail.com", 587, and the credentials with your SMTP server's details. Verify that your Internet Service Provider (ISP) supports SMTP and that your email address and password are correct. The Host value should be your SMTP server address (e.g., "smtp-proxy.tm.net.my").

The above is the detailed content of How to Send Emails Using ASP.NET C# and SMTP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template