I am trying to write a code that sends Emails using VB.NET.
The SMTP Server is smtp.office365.com.
I found plenty of resources on how to do this using the Gmail SMTP server. It works fine. But the requirement is to send the Email from the company's Email that runs over a office365.
The project is a Windows Forms Application. I am using Visual Studio 2010.
What did I try?
I have tried this code:
Dim Mail As New MailMessage
Dim SMTP As New SmtpClient("smtp.office365.com")
Mail.Subject = "Test Subject"
Mail.From = New MailAddress("The from Email")
SMTP.Credentials = New System.Net.NetworkCredential("The from Email", "The from Email Password")
Mail.To.Add("The to Email")
Mail.Body = "Hello"
SMTP.EnableSsl = True
SMTP.Port = "587"
ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf customCertValidation)
Try
SMTP.Send(Mail)
MsgBox("done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
In the same form, I have a function defined as follows:
Private Shared Function customCertValidation(ByVal sender As Object, _
ByVal cert As X509Certificate, _
ByVal chain As X509Chain, _
ByVal errors As SslPolicyErrors) As Boolean
Return True
End Function
By running the above code, I get this message (after around a minute): System.Net.Mail. Smtp Exception: The operation has timed out. at System.Net.Mail.SmtpClient.Send(MailMessage message)
- Also, Here, they mentioned a similar issue. I tried to use their code which is the following:
Imports System.Net.Mail
Public Class Form1
Private Sub SendEmail()
Dim MS365Email As New MailMessage
MS365Email.To.Add("RECIPIENTEMAIL")
MS365Email.From = New MailAddress("SENDEREMAIL")
MS365Email.Subject = "SUBJECT"
MS365Email.IsBodyHtml = True
MS365Email.Body = "BODYTEXT"
Dim MS365client As New SmtpClient("smtp.office365.com", 587)
MS365Email.Priority = MailPriority.Normal
MS365client.EnableSsl = True
MS365client.UseDefaultCredentials = False
Dim xms365 As New Net.NetworkCredential("USERNAME", "PASSWORD")
MS365client.Credentials = xms365
MS365client.DeliveryMethod = SmtpDeliveryMethod.Network
MS365client.SendAsync(MS365Email, Nothing)
End Sub
End Class
It does not throw any error or exception. But no Email is received.
- What I am Expecting? Either pointing-out the issue(s) that fix any of these codes, or sharing another code that can achieve the requirement.
Thank you in advance