Send Html Email
Sends an HTML email to one or more recipients using the specified SMTP server.
- If multiple recipients are specified, separate them with commas in the parameter.
- If User and Password are provided, SMTP authentication will be used.
- SSL is disabled by default, even when authentication is used. Modify if required.
- If no credentials are provided, default system credentials will be used.
VB
Public Function SendHtmlEmail(Subject As String,
MailBody As String,
EmailAddress As String,
Sender As String,
SmtpServer As String,
ServerPort As Integer,
Optional User As String = "",
Optional Password As String = "") As Boolean
' Basic validations
If String.IsNullOrWhiteSpace(EmailAddress) Then Return False
If String.IsNullOrWhiteSpace(Sender) Then Return False
If String.IsNullOrWhiteSpace(SmtpServer) Then Return False
If ServerPort <= 0 OrElse ServerPort > 65535 Then Return False
Dim RecipientList As List(Of String) = Split(EmailAddress, ",").ToList()
Try
Using msg As New MailMessage()
' From/To
msg.From = New MailAddress(Sender)
For Each Recipient As String In RecipientList
If Not String.IsNullOrWhiteSpace(Recipient) Then
msg.To.Add(Recipient.Trim())
End If
Next
' Subject & HTML body
msg.Subject = If(Subject, String.Empty)
msg.SubjectEncoding = Encoding.UTF8
msg.Body = If(MailBody, String.Empty)
msg.BodyEncoding = Encoding.UTF8
msg.IsBodyHtml = True
' Configure SMTP client
Using client As New SmtpClient(SmtpServer, ServerPort)
client.DeliveryMethod = SmtpDeliveryMethod.Network
' If credentials are provided, use them
If Not String.IsNullOrWhiteSpace(User) AndAlso Not String.IsNullOrWhiteSpace(Password) Then
client.Credentials = New Net.NetworkCredential(User, Password)
client.UseDefaultCredentials = False
'client.EnableSsl = True ' Assume SSL when authentication is used
client.EnableSsl = False
Else
' No authentication
client.UseDefaultCredentials = True
client.EnableSsl = False
End If
' Send message
client.Send(msg)
End Using
End Using
Return True
Catch ex As Exception
Throw New ApplicationException($"Error sending email to {EmailAddress}: {ex.Message}", ex)
End Try
End Function