Quick Reference on how to send an email using .NET

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    Quick Reference on how to send an email using .NET

    Introduction
    Many .NET applications will require an email be sent out for various reasons. This article will give a quick examples on how to send an email using VB.NET. The examples given can easily be translated into C#.NET.

    Storing Email Credentials
    If you are developing a web application the best place to store your email credentials is in your web.config file's <appSettings> . This will allow you to secure your email credentials using encryption and also provide a single location for all of your code to access the credentials.

    [code=xml]
    <configuratio n>
    <appSettings>
    <add key="EmailUserN ame" value="userName "/>
    <add key="EmailPassw ord" value="password "/>
    </appSettings>
    </configuration>
    [/code]


    If you are using .NET Framework version 1.1
    You will have to import System.Web.Mail
    This Framework will not easily allow you to supply email credentials that allow you to connect to your mail server. I will not cover how to do this in this article.

    [code=vbnet]
    Dim mailMsg As Mail.MailMessag e
    Dim body As new String = "This will be the body of my email message"

    mailMsg= New MailMessage
    mailMsg.To= "to@blabla. com"
    mailMsg.From= "from@blabla.co m"
    mailMsg.Subject = "The subject of the email"
    mailMsg.BodyFor mat = MailFormat.Html
    mailMsg.Body = body

    SmtpMail.SmtpSe rver="localhost "

    Try
    SmtpMail.Send(m ailMsg)
    Catch ex As Exception

    End Try

    [/code]


    If you are not using the using .NET Framework version 1.1
    You will have to import System.Net.Mail .MailMessage and if you need to provide email credentials in order to connect to your mail server System.Net.Netw orkCredentials

    Please note that the following code snippet shows how to retrieve your user credentials from the web.config file. If you are not storing your credentials in this file you can simply add strings for the user name and password instead of using ConfigureationM anager.AppSetti ngs(...) to supply your credentials.

    Also if you do not have to supply user credentials in order to connect to your mail provider you can ignore anything that has to do with credentials in this example

    [code=vbnet]
    Try
    Dim emailTitle As String ="My Email Title"

    Dim emailMessage As Net.Mail.MailMe ssage

    Dim body As String = "This will appear in the body of my email"

    emailMessage = New Net.Mail.MailMe ssage("from@ema ilAddress.com", "to@emailAddres s.com", emailTitle, body)

    Dim mailClient As New Net.Mail.SmtpCl ient("urlOfEmai lService.com", 25)
    '25 is the port on which the mail server is listening. If your mail server
    'runs on the default port this number does not need to be provided


    'If you do not need to provide credentials to connect to the mail server you can ignore the next 3 lines
    Dim myCredentials As New System.Net.Netw orkCredential(S ystem.Configura tion.Configurat ionManager.AppS ettings("EmailU serName"), System.Configur ation.Configura tionManager.App Settings("Email Password"))
    mailClient.UseD efaultCredentia ls = False
    mailClient.Cred entials = myCredentials

    mailClient.Send (emailMessage)

    Catch ex As Exception

    End Try

    [/code]

    I hope this has helped you!

    -Frinny
    Last edited by Frinavale; Nov 24 '11, 09:17 PM.
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    As a side note:
    Be aware that sending emails through .NETs built in mailer, for whatever reason, does not send message immediatly. (I have had to wait up to 3hours for an email to myself to arrive)
    If the wait time is not an issue it's great, if you want immediate results, you will have to look elsewhere.

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #3
      Originally posted by Plater
      As a side note:
      Be aware that sending emails through .NETs built in mailer, for whatever reason, does not send message immediatly. (I have had to wait up to 3hours for an email to myself to arrive)
      If the wait time is not an issue it's great, if you want immediate results, you will have to look elsewhere.
      Wow, I've never experienced that before.
      I guess it depends on your provider.

      Comment

      • Plater
        Recognized Expert Expert
        • Apr 2007
        • 7872

        #4
        Well, I wrote my own mailer using sockets and every email went instantaniously . I did head-to-heads with the .NET implementation and my own and mine won out every time.

        Comment

        • Frinavale
          Recognized Expert Expert
          • Oct 2006
          • 9749

          #5
          Just thought that I would post a code snippet here that sends email using GMail.

          I used Gmail's reference to find information about ports etc. here: Configuring Gmail for Other Mail Clients


          First you need to include a reference to System.Net.Mail and System.NET at the top of your VB.NET or C# code file.

          Like this:
          (VB.NET)
          Code:
          Imports System.Net.Mail
          Imports System.Net
          (C#)
          Code:
          using System.Net.Mail;
          using System.Net;

          Then you can send the email using the following:
          (VB.NET)
          Code:
          Try
            Dim emailMessage As New MailMessage("fromAccount@gmail.com", "toAccount@gmail.com", "test email", "testing email")
            Dim mailClient As New SmtpClient("smtp.gmail.com", 587)
            mailClient.EnableSsl = True
            mailClient.UseDefaultCredentials = False
            mailClient.DeliveryMethod = SmtpDeliveryMethod.Network
            Dim myCredentials As New System.Net.NetworkCredential("theGmailAccount@gmail.com", "theGmailAccountPassword")
            mailClient.Credentials = myCredentials
            mailClient.Send(emailMessage)
            MessageBox.Show("Sent")
          Catch ex As Exception
            MessageBox.Show(ex.Message)
          End Try
          (C#)
          Code:
          try {
            MailMessage emailMessage = new MailMessage("fromAccount@gmail.com", "toAccount@gmail.com", "test email", "testing email");
            SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
            mailClient.EnableSsl = true;
            mailClient.UseDefaultCredentials = false;
            mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            System.Net.NetworkCredential myCredentials = new System.Net.NetworkCredential("theGmailAccount@gmail.com", "theGmailAccountPassword");
            mailClient.Credentials = myCredentials;
            mailClient.Send(emailMessage);
            MessageBox.Show("Sent");
          } catch (Exception ex) {
            MessageBox.Show(ex.Message);
          }
          -Frinny
          Last edited by Frinavale; Dec 12 '11, 05:45 PM.

          Comment

          Working...