Gabriel de Morais
Gabriel de Morais

Reputation: 1

Send emails through VB using Outlook as outgoing server

I'm having a problem sending emails via Outlook using VB. I've already tested it with other emails, such as Gmail, and the code is working. In the Outlook email I'm using for testing, I've already configured the two-step option in the security section and also generated the application password. I tried with the normal email password and the application password, but nothing. I tested it with other Microsoft email servers, but nothing. Could someone analyze my code and check if I'm forgetting to pass something? I'm using Visual Studio 2013 using Net Framework 4.5. I also attached a screenshot of the error.

Note: In the code below, I removed my email and password for security reasons, but in the original, there is a real email and password.

enter image description here

Imports System.Net
Imports System.Net.Mail

Public Class frmEmail

    Private Sub btnEnviar_Click(sender As Object, e As EventArgs) Handles btnEnviar.Click
        Try
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

            Dim strSmtpServer As String = "smtp.office365.com"
            Dim strSmtpPort As Integer = 587
            Dim strEmail As String = "[email protected]"
            Dim strSenha As String = "senhaaplicativo"

            Dim strRemetente As String = "[email protected]"
            Dim strDestinatario As String = "[email protected]"
            Dim strAssunto As String = "Assunto do e-mail"
            Dim strMensagem As String = "Corpo do e-mail"

            Dim smtp As New SmtpClient(strSmtpServer)
            smtp.Port = strSmtpPort
            smtp.Credentials = New NetworkCredential(strEmail, strSenha)
            smtp.EnableSsl = True

            Dim mail As New MailMessage()
            mail.From = New MailAddress(strRemetente)
            mail.To.Add(strDestinatario)
            mail.Subject = strAssunto
            mail.Body = strMensagem

            smtp.Send(mail)
            MsgBox("E-mail enviado com sucesso!", MsgBoxStyle.Information)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
End Class

I hope to be able to send emails using Outlook as the outgoing server through VB.

Upvotes: -3

Views: 37

Answers (1)

Gennadiy Litvinyuk
Gennadiy Litvinyuk

Reputation: 1597

Since 2023 you can not use neither Basic Authentication, nor SMTP AUTH for Microsoft Exchange Services anymore. Source: Deprecation of Basic authentication in Exchange Online

You have to choose between 2 following alternatives:

Implement OAuth authentication for SMTP as described in this Article: Authenticate an IMAP, POP or SMTP connection using OAuth

or

Use Microsoft Graph API instead, and more precisely Outlook mail API

Upvotes: 0

Related Questions