Sending Email - .Net Framework

The following code demonstrates how to send email. You can convert code between C# and VB.NET at this website.

See also the MailServer Class.

Using a Mail Server

MailMessage message = new MailMessage(sender, recipient, subject, msg);
SmtpClient mySmtpClient = new SmtpClient(mailServer);
mySmtpClient.UseDefaultCredentials = true;
mySmtpClient.Send(message);

Via the local SMTP service hosted within IIS

SmtpClient smtp = new SmtpClient("127.0.0.1");
smtp.UseDefaultCredentials = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.Port = 25;
MailMessage msg = new MailMessage("somebody@emailhost.com",
	"somebody@emailhost.com", "My Email Subject", 
	"This is a test of my SMTP service.");

try
{
    smtp.Send(msg);
	MessageBox.Show("Message sent!");
}

The following code shows a slightly different way to do it, this time in Visual Basic.

Imports System.Net
Imports System.Net.Mail

...

Public Sub SendEmail(ByVal recipient As String, ByVal sender As String, ByVal subject As _
String, ByVal messageBody As String, ByVal smtpServer As String)

    Dim smtpClient As New SmtpClient
    smtpClient.Host = smtpServer
    smtpClient.Port = 25
    smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials

    Dim mailMessage As New MailMessage(sender, recipient, subject, messageBody)
    mailMessage.IsBodyHtml = True
    smtpClient.Send(mailMessage)

End Sub

Via Configuration

The following settings in the web.config file will be used (if present) when a call to SmtpClient c = new SmtpClient() is made.

<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" >
      <network
        host="10.0.0.2"
        port="25"
        defaultCredentials="true"
      />
    </smtp>
  </mailSettings>
</system.net>

Sample setup for using Amazon SES is shown below. The userName and password are the Access Key and Secret Key, respectively, provided by Amazon.

<system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" 
            from="sender@email.com"
            >
        <network host="email-smtp.us-east-1.amazonaws.com" 
                 port="587" 
                 userName="AKIA*****" 
                 password="*****" 
                 enableSsl="true" 
                 />
      </smtp>
    </mailSettings>
  </system.net>