Sending email messages using C# is easy. But you must have access to an SMTP server in order to do it. If you don’t have your own SMTP server, it’s possible to use your Gmail or Outlook.com account. This post will show you how to create an SmtpMailer
class which can be used to send email messages with Gmail or Outlook.com.
What are the SMTP settings?
Before you create the SmtpMailer
class you need to know what the SMTP server settings are for connecting to Outlook.com and Gmail. I have listed them below.
SMPT Server Settings for Gmail?
- Host: smtp.gmail.com
- Port: 587
- Require SSL: True
- Username: your full gmail.com email address
- Password: your gmail.com password
SMPT Server Settings for Outlook.com?
- Host: smtp.live.com
- Port: 587
- Require SSL: True
- Username: your full outlook.com email address
- Password: your outlook.com password
SmtpSettings class
Create a class called SmtpSettings
. This class will be used to pass the SMTP server settings to the SmtpMailer
class.
public class SmtpSettings
{
public string Host { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
SmtpMailer Class
Create a class called SmtpMailer
. This class will be used to send the email messages using the .NET framework SmtpClient
class.
public class SmtpMailer
{
public bool Send(SmtpSettings settings, string from, string to, string subject, string body)
{
// TODO: Validate arguments
try
{
using (var mail = new MailMessage())
{
mail.From = new MailAddress(from);
mail.To.Add(to);
mail.Subject = subject;
mail.Body = body;
mail.ReplyToList.Add(new MailAddress(from));
var smtp = new SmtpClient(settings.Host, settings.Port);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(settings.Username, settings.Password);
smtp.Timeout = 60000; // 60 seconds
smtp.EnableSsl = true; // Outlook.com and Gmail require SSL
smtp.Send(mail);
// email was accepted by the SMTP server
return true;
}
}
catch (Exception ex)
{
// TODO: Log the exception message
return false;
}
}
}
A working example
The code below shows you an eample of how to use the SmtpMailer
class to send an email message using Outlook.com
var settings = new SmtpSettings()
{
Host = "smtp.live.com", // or "smtp.gmail.com"
Port = 587,
Username = "yourfullemail",
Password = "yourpassword"
};
var smtpMailer = new SmtpMailer();
smtpMailer.Send(settings, "[email protected]", "[email protected]", "Testing From Hotmail", "Testing");
And that’s all there is to it. As you can see, sending email messages is easy with C#. There’s also a lot more you can do with the SmtpClient
class. You can send email messages with attachments, send HTML email messages or send to multiple email addresses at a time. Check out the SmtpClient documentation to see what else you can do.