Email

C#

C# uses SMTP (Simple Mail Transfer Protocol) for sending email. It specifically employs the System.Net.Mail namespace.

Instantiate the SmtpClient class and assign the host and port (25 typically serves as the default port) to perform email tasks. Class properties (e.g., Credentials, Host, DeliveryFormat, EnableSsl, Port, and TargetName) specify critical information in tasks. Class methods perform critical functions in email (e.g., Send(Sender, Recipients, Subject, MessageBody) or Dispose()).

The example below demonstrates sending an email from a Gmail address using a Gmail SMTP server name (smtp.gmail.com) and port 555 along with NetworkCredential for authentication:

using System;
using System.Windows.Forms;
using System.Net.Mail;
namespace App
{
	public partial class FormOne : Form
	{
		public FormOne()
		{
			InitializeComponent();
		}
		private void buttonOne_Click(object sender, EventArgs e)
		{
			try
			{
				MailMessage mail = new MailMessage();
				SmtpClient SmtpServer = new
SmtpClient("smtp.gmail.com");

				mail.From = new MailAddress("joanqpublic@gmail.com");
				mail.To.Add("to_address");
				mail.Subject = "Mail test";
				mail.Body = "This tests SMTP mail from GMAIL";

				SmtpServer.Port = 555;
				SmtpServer.Credentials = new
System.Net.NetworkCredential("username", "password");
				SmtpServer.EnableSsl = true;

				SmtpServer.Send(mail);
				MessageBox.Show("Send");
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}
	}
}

The code below demonstrates how to send an email with an attachment:

using System;
using System.Windows.Forms;
using System.Net.Mail;
namespace App
{
	public partial class FormOne : Form
	{
		public FormOne()
		{
			InitializeComponent();
		}
		private void buttonOne_Click(object sender, EventArgs e)
		{
			try
			{
				MailMessage mail = new MailMessage();
				SmtpClient SmtpServer = new
SmtpClient("smtp.gmail.com");
				mail.From = new MailAddress("joanqpublic@gmail.com");
				mail.To.Add("to_address");
				mail.Subject = "Mail Test";
				mail.Body = "mail includes attachment";

				System.Net.Mail.Attachment attachment;
				attachment = new System.Net.Mail.Attachment("the
attached file");
				mail.Attachments.Add(attachment);

				SmtpServer.Port = 555;
				SmtpServer.Credentials = new
System.Net.NetworkCredential("username", "password");
				SmtpServer.EnableSsl = true;

				SmtpServer.Send(mail);
				MessageBox.Show("Send");
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.ToString());
			}
		}
	}
}