Send e-mail via SMTP using C#

In this tutorial we will see how to send an e-mail via SmtpClient class in C#.


First let's add these directives:

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

Code:

string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;

string emailFrom = "youremail@gmail.com";
string password = "yourpassword";

private void SendButton_Click(object sender, EventArgs e)
{
    try
    {
        using (MailMessage mail = new MailMessage())
        {
            mail.From = new MailAddress(emailFrom);
            mail.To.Add(TotextBox.Text);
            mail.Subject = SubjecttextBox.Text;
            mail.Body = BodytextBox.Text;
            mail.IsBodyHtml = true;

            using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
            {
                smtp.Credentials = new NetworkCredential(emailFrom, password);
                smtp.EnableSsl = enableSSL;
                smtp.Send(mail);
            }
        }

        MessageBox.Show("Email sent successfully");

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }
}

Server Parameters

Server Name   SMTP Address   Port   SSL
Yahoo!      smtp.mail.yahoo.com   587   Yes
GMail   smtp.gmail.com   587   Yes
Hotmail   smtp.live.com   587   Yes


Send e-mail via SMTP using C# Send e-mail via SMTP using C# Reviewed by Bloggeur DZ on 03:57 Rating: 5

Aucun commentaire:

Fourni par Blogger.