How to send test email in C#
Introduction - sending email in C#
If you're writing software using C#, you're probably sending emails, either as part of sign up flows, or for sending notifications or maybe you just like sending pictures of Chameleons!
The standard way to send email is via an SMTP server, usually hosted by a specialist email service provider but can also be hosted yourself.
.Net has provided a way of sending email via SMTP in C# since version 1.0.
Unsurprisingly, they've called the class in question
SmtpClient and it's part of the standard library in the
In order to send email using the
SmtpClient you need to know the host and port of the SMTP server and then almost always a username and password with which to authenticate yourself
The following code illustrates how to send an email:
// First of all construct the SMTP client using the host and port var smtpClient = new SmtpClient("smtp.gmail.com", 587); //I have provided the URI and port for GMail, replace with your providers SMTP details // Configure it (these are common example properties) smtpClient.EnableSsl = true; //Required for gmail, may not for your provider, if your provider does not require it then use false. smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.Credentials = new NetworkCredential("YourUserName", "YourPassword"); // Create an email to send var mail = new MailMessage("yourEmail@address.com", "theirEmail@address.com"); // Then we construct the message mail.Subject = "Important Message"; mail.Body = "Hello over there"; //The body contains the string for your email // using "mail.IsBodyHtml = true;" you can put an HTML page in your message body // Then we use the SMTP client to send the message await smtpClient.SendAsync(mail);
Sending Test Email: Set up Imitate Email
If you've not already done so please sign up to Imitate Email.
For Imitate Email, when sending test emails you use the following server details:
Imitate Email uses STARTTLS which ensures that your emails are sent over an encrypted connection. To do that in C# ensure that
smtpClient.EnableSsl = true.
Then, for your username and password you need to decide if you're using your personal mailbox or have set up a project in Imitate Email.
Locate your mailbox credentials
To locate your username go to Settings > My Mailbox where you will find it (it is the same for all mailboxes in your account)
For the password
If you're on the Free or Developer plan or you're setting this up for your personal mailbox copy the password from the same place as the username.
If you're setting this up for a team mailbox go to Settings > Projects and you will find the password next to the symbol for your mailbox. It will look like the following