This code show how to send email multiple attachments from vb.net by using System.Net.Mail

1. This is how you use it

Dim fileAttch = New ArrayList
fileAttch.Add("C:\test.csv")
fileAttch.Add("C:\test2.csv")
fileAttch.Add("C:\test3.csv")

sendEmail.send(your_emailHost, "no-reply@company.com", your_EmailTo, your_EmailSubject, your_EmailBody, your_EmailccTo, fileAttch)


2. Create a class called sendEmail.vb

Imports System.IO
Imports System.Net.Mail
Imports Microsoft.VisualBasic
Imports System

Public Class sendEmail

    Public Shared Sub send(ByVal smtpHost As String, ByVal fromEmail As String, ByVal toEmail As String, ByVal subject As String, ByVal body As String, ByVal cc As String, Optional ByVal AttachmentFiles As ArrayList = Nothing)
        Dim mail As New MailMessage()

        '-----------------------------------
        'Set Email Address
        '-----------------------------------
        mail.From = New MailAddress(fromEmail)

        If toEmail = "" Then
            Throw New Exception("Error: No email address to send")
        End If
        If toEmail.Contains(";") Then
            Dim emailList As String()
            emailList = toEmail.Split(";")
            For Each email As String In emailList
                mail.To.Add(email)
            Next
        Else
            mail.To.Add(toEmail)
        End If
        If cc <> "" Then
            If cc.Contains(";") Then
                Dim ccList As String()
                ccList = cc.Split(";")
                For Each ccTo As String In ccList
                    mail.CC.Add(ccTo)
                Next
            Else
                mail.CC.Add(cc)
            End If
        End If

        '-----------------------------------
        'Set Email Address Content
        '-----------------------------------
        mail.Subject = subject
        mail.IsBodyHtml = True
        mail.Body = body

        Dim i As Integer
        Dim Attachment As System.Net.Mail.Attachment

        For i = 0 To AttachmentFiles.Count - 1
            If FileExists(AttachmentFiles(i)) Then
                Attachment = New Net.Mail.Attachment(AttachmentFiles(i))
                mail.Attachments.Add(Attachment)
            End If
        Next

        '-----------------------------------
        'Set Email Address Host
        '-----------------------------------
        Dim smtp As New SmtpClient(smtpHost)
        Try
            smtp.Send(mail)
        Catch ex As Exception
            '-------------------------------------------------
            MsgBox("Error " & ex.Message)
            '-------------------------------------------------
        End Try

    End Sub

    Private Shared Function FileExists(ByVal FileFullPath As String) As Boolean
        If Trim(FileFullPath) = "" Then Return False

        Dim f As New IO.FileInfo(FileFullPath)
        Return f.Exists

    End Function

End Class

  • Share/Bookmark