VB.NET Email Attachment

The System.Net classes offer a range of functionalities for communication with other applications, including HTTP, TCP, UDP, and Socket protocols. In the context of sending emails, Microsoft .NET languages rely on the System.Net.Mail namespace. In previous chapters, we learned how to send emails containing only text content. However, in this section, our focus is on sending emails with attachments, which adds an extra layer of complexity.

System.Net.Mail namespace

When sending an email with an attachment, we need to utilize the classes and methods provided by the System.Net.Mail namespace to handle the attachment-related functionality. This includes selecting and attaching the desired file or files to the email message.

Dim attachment As System.Net.Mail.Attachment attachment = New System.Net.Mail.Attachment("your attachment file") mail.Attachments.Add(attachment)

By employing the appropriate methods and properties, such as the Attachment class, we can associate one or more files with the email. This allows for the transmission of not only text content but also additional files or documents. The attachments could be in various formats, such as images, documents, or compressed files.

To send an email with attachments, it is crucial to follow the correct syntax and use the appropriate classes and methods provided by the System.Net.Mail namespace. By understanding the concepts and utilizing the available tools, developers can effectively incorporate attachment functionality into their email sending applications, enabling the seamless transmission of both text content and additional files.

The following VB.NET source code shows how to send an email with an attachment from a Gmail address . The Gmail SMTP server name is smtp.gmail.com and the port using send mail is 587 .

NetworkCredential for password based authentication

SmtpServer.Port = 587 SmtpServer.Credentials = New System.Net.NetworkCredential("username", "password") SmtpServer.EnableSsl = True
Full Source VB.NET
Imports System.Net.Mail Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim mail As New MailMessage() Dim SmtpServer As New SmtpClient("smtp.gmail.com") mail.From = New MailAddress("your_email_address@gmail.com") mail.[To].Add("to_address") mail.Subject = "Test Mail - 1" mail.Body = "mail with attachment" Dim attachment As System.Net.Mail.Attachment attachment = New System.Net.Mail.Attachment("your attachment file") mail.Attachments.Add(attachment) SmtpServer.Port = 587 SmtpServer.Credentials = New System.Net.NetworkCredential("username", "password") SmtpServer.EnableSsl = True SmtpServer.Send(mail) MessageBox.Show("mail Send") End Sub End Class