How to send emails in VBA

Send email in Visual basic. VBA scripting has built in mailing functionality. Use SMTPClient to send mail and attachments.

Visual Basic is a powerful scripting language from Microsoft that has many uses. Sending email with VBA is easy using the Net.Mail.SmtpClient package. In this post we will demonstrate how to setup VBA with SMTP mailserver credentials and then send emails from code or tests.

Configure an SMTP server access

To send email in visual basic you need access to a MailServer (or API such as MailSlurp). In this example we will use a MailServer hosted by MailSlurp to configure our VBA client. If you already have a MailServer you can skip to the next step.

Dim webClient As New Net.WebClient
Dim jsonClient As New Net.WebClient
Dim apiKey As String = Environment.GetEnvironmentVariable("API_KEY")
Assert.IsNotEmpty(apiKey)
Assert.IsNotNull(apiKey)
webClient.Headers.Add("x-api-key", apiKey)
Dim imapSmtpAccessJson = webClient.DownloadString("https://api.mailslurp.com/inboxes/imap-smtp-access")
jsonClient.Headers.Add("Content-Type", "application/json")
Dim username = jsonClient.UploadString("https://api.mailslurp.com/user/json/pluck?property=smtpUsername", imapSmtpAccessJson)
jsonClient.Headers.Add("Content-Type", "application/json")
Dim password = jsonClient.UploadString("https://api.mailslurp.com/user/json/pluck?property=smtpPassword", imapSmtpAccessJson)
jsonClient.Headers.Add("Content-Type", "application/json")
Dim port = jsonClient.UploadString("https://api.mailslurp.com/user/json/pluck?property=smtpServerPort", imapSmtpAccessJson)
jsonClient.Headers.Add("Content-Type", "application/json")
Dim host = jsonClient.UploadString("https://api.mailslurp.com/user/json/pluck?property=smtpServerHost", imapSmtpAccessJson)

Create an SMTP client

Next, take the password, username, host, and port and configure the SMTP client:

Dim Smtp_Server As New Net.Mail.SmtpClient
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential(username, password)
Smtp_Server.EnableSsl = False
Smtp_Server.Port = Integer.Parse(port)
Smtp_Server.Host = host

Now send an email

Once configured we can use the Net.Mail.SmtpClient instance to send an email:

Dim email As New Net.Mail.MailMessage()
email = New Net.Mail.MailMessage()
email.From = New Net.Mail.MailAddress(fromAddress)
email.To.Add(toAddress)
email.Subject = "Send email with VB"
email.IsBodyHtml = False
email.Body = "Hello this is me"
Smtp_Server.Send(email)