Visual Basic Code Snippet - Send Email Using SMTP Server

Visual Basic Code Snippet - Send Email Using SMTP Server

Visual Basic Code Snippet - Send Email Using SMTP Server

(VB) Visual Basic code snippet connects to SMTP Email Server and send email message. SendEmail send email using SMTP email server.

Bookmark:

Visual Basic Code Snippet - Send Email Using SMTP Server

This .Net Visual Basic code snippet connects to SMTP Email Server and send email message. To use this function simply provide from email, from name, to email, to name, email subject, email body, body HTML or not, attachments, SMTP server address, login name and login password. Email attachments are passing to function as a string array. To avoid email attachments, simply pass NULL for parameter value. This function uses System.Net.Mail Namespace to process email sending, function returns TRUE if email send out successfully, FALSE otherwise. Modify the exception handling section for your project requirements.

''' <summary>
''' method to send email using SMTP server
''' </summary>
''' <param name="_FromEmail">From email address</param>
''' <param name="_FromName">From name</param>
''' <param name="_ToEmail">To email address</param>
''' <param name="_ToName">To name</param>
''' <param name="_Subject">Email subject</param>
''' <param name="_EmailBody">Email message body</param>
''' <param name="_IsBodyHtml">Is email message body HTML</param>
''' <param name="_Attachments">Email message file attachments</param>
''' <param name="_EmailServer">SMTP email server address</param>
''' <param name="_LoginName">SMTP email server login name</param>
''' <param name="_LoginPassword">SMTP email server login password</param>
''' <returns>TRUE if the email sent successfully, FALSE otherwise</returns>
Public Function SendEmail(ByVal _FromEmail As String, ByVal _FromName As String, ByVal _ToEmail As String, ByVal _ToName As String, ByVal _Subject As String, ByVal _EmailBody As String, ByVal _IsBodyHtml As Boolean, ByVal _Attachments() As String, ByVal _EmailServer As String, ByVal _LoginName As String, ByVal _LoginPassword As String) As Boolean
    Try
        ' setup email header
        Dim _MailMessage As New System.Net.Mail.MailMessage()

        ' Set the message sender
        ' sets the from address for this e-mail message. 
        _MailMessage.From = New System.Net.Mail.MailAddress(_FromEmail, _FromName)
        ' Sets the address collection that contains the recipients of this e-mail message. 
        _MailMessage.To.Add(New System.Net.Mail.MailAddress(_ToEmail, _ToName))

        ' sets the message subject.
        _MailMessage.Subject = _Subject
        ' sets the message body. 
        _MailMessage.Body = _EmailBody
        ' sets a value indicating whether the mail message body is in Html. 
        ' if this is false then ContentType of the Body content is "text/plain". 
        _MailMessage.IsBodyHtml = _IsBodyHtml

        ' add all the file attachments if we have any
        If _Attachments IsNot Nothing AndAlso _Attachments.Length > 0 Then
            For Each _Attachment As String In _Attachments
                _MailMessage.Attachments.Add(New System.Net.Mail.Attachment(_Attachment))
            Next _Attachment
        End If

        ' SmtpClient Class Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
        Dim _SmtpClient As New System.Net.Mail.SmtpClient(_EmailServer)

        'Specifies how email messages are delivered. Here Email is sent through the network to an SMTP server.
        _SmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network

        ' Some SMTP server will require that you first authenticate against the server.
        ' Provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.
        Dim _NetworkCredential As New System.Net.NetworkCredential(_LoginName, _LoginPassword)
        _SmtpClient.UseDefaultCredentials = False
        _SmtpClient.Credentials = _NetworkCredential

        'Let's send it
        _SmtpClient.Send(_MailMessage)

        ' Do cleanup
        _MailMessage.Dispose()
        _SmtpClient = Nothing
    Catch _Exception As Exception
        ' Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString())
        Return False
    End Try

    Return True
End Function


Here is a simple example showing how to use above function (SendEmail) to send plain text email using SMTP email server. Notice over here we passing FALSE for HTML body to allow plain text and NULL value as a attachment.

' Send plain text email with one attachment
If SendEmail("[email protected]", "From name", "[email protected]", "To name", "email subject", "This is a test email" & Constants.vbCrLf & "line2", False, Nothing, "mail.yourdomain.com", "login-name", "login-password") Then
	Console.WriteLine("Email sent successfully")
Else
	Console.WriteLine("Failed to send email")
End If


Here is a simple example showing how to use above function (SendEmail) to send email with HTML contents in the email body using SMTP email server. Notice over here we passing TRUE for HTML body to allow HTML contents and NULL value as a attachment.

' Send plain text email with one attachment
If SendEmail("[email protected]", "From name", "[email protected]", "To name", "email subject", "Here is HTML content body<br /><b>This line is bold</b>", True, Nothing, "mail.yourdomain.com", "login-name", "login-password") Then
	Console.WriteLine("Email sent successfully")
Else
	Console.WriteLine("Failed to send email")
End If


Here is a simple example showing how to use above function (SendEmail) to send plain text email with one attachment file using SMTP email server. Notice over here we passing FALSE for HTML body to allow plain text and one file path as a string array to attachment parameter.

' Send plain text email with one attachment
If SendEmail("[email protected]", "From name", "[email protected]", "To name", "email subject", "This is a test email" & Constants.vbCrLf & "line2", False, New String() { "c:\sampleimage.jpg" }, "mail.yourdomain.com", "login-name", "login-password") Then
	Console.WriteLine("Email sent successfully")
Else
	Console.WriteLine("Failed to send email")
End If


Here is a simple example showing how to use above function (SendEmail) to send plain text email with more than one attachment file using SMTP email server. Notice over here we passing FALSE for HTML body to allow plain text and two file paths as a string array to attachment parameter.

' Send plain text email with one attachment
If SendEmail("[email protected]", "From name", "[email protected]", "To name", "email subject", "This is a test email" & Constants.vbCrLf & "line2", False, New String() { "c:\sampleimage.jpg", "c:\sampledoc.doc" }, "mail.yourdomain.com", "login-name", "login-password") Then
	Console.WriteLine("Email sent successfully")
Else
	Console.WriteLine("Failed to send email")
End If


VB Keywords Used:

  • SmtpClient
  • MailMessage
  • MailAddress
  • Attachment
  • SmtpDeliveryMethod
  • UseDefaultCredentials
  • NetworkCredential
  • Exception

Code Snippet Information:

  • Applies To: .Net, VB, Visual Basic, CLI, Email, SMTP, System.Net.Mail, MailMessage, SMTPClient, Sending emails using .Net, Email attachments, SMTP Authentication, SMTP Delivery Methods
  • Programming Language : Visual Basic (VB)

External Resources:

Leave a comment