How to send email in C# windows forms application

Hello everybody,

sometime people ask me how to send email from C# windows forms application or even ask is it possible at all to accomplish in C#?

I can reassure you that yes, it's possible. 

For this purpose you can use following code sample:

private void btnSendMessage_Click(object sender, EventArgs e)
{
            var from = new MailAddress(txtFrom.Text, "From Name");
            var toEmail = new MailAddress(txtTo.Text, "To Name");
            string passwordFromEmailOfSender = txtPassword.Text;
            string subject = "Subject";
            string body = txtMessage.Text;

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(from.Address, passwordFromEmailOfSender)
            };
            using (var message = new MailMessage(from, toEmail)
            {
                Subject = subject,
                Body = body
            })
            {
                smtp.Send(message);
            }

}

If you are to busy to copy/paste code by yourself with guessing how to locate buttons on the form, you can Download source code and compile it with Visual Studio 2015. Actually Archive contains exe file as well.

If you'll execute program and fill some data you can see something like this:

If your mailbox is from yahoo, you will see something similar to this:

Also you can use presented code for making mass sending of some needed information for your business.

No Comments

Add a Comment