Send an e-mail in VB .NET
Sending an e-mail is quite simple. This example saves an .eml file if sending fails
Dim msg As New Mail.MailMessage msg.From = New Mail.MailAddress(StrSender) msg.To.Add(New Mail.MailAddress(StrRecipient)) msg.CC.Add(New Mail.MailAddress(StrCarbonCopy)) msg.Subject = "Message subject" msg.Body = "Hello, " & vbCrLf & _ "This is message body" msg.IsBodyHtml = False 'Set this to True if body is HTML msg.Attachments.Add(New Mail.Attachment("c:\temp\file.att")) Dim smtp As New Mail.SmtpClient("127.0.0.1") 'Replace with the IP address of SMTP server. 'If the server is on non default port. Use Mail.SmtpClient(server,port) 'If the server requires an username and a password smtp.Credentials = New System.Net.NetworkCredential(MailServerUserName, MailServerPassword) Try 'Try to send the message smtp.Send(msg) Catch exc As Exception 'Failed to send message. Create an .eml and store it for later send attempt smtp.DeliveryMethod = Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory smtp.PickupDirectoryLocation = "c:\temp\eml" smtp.Send(msg) Finally 'Dispose of the objects smtp.Dispose() smtp = Nothing End Try msg.Dispose() msg = Nothing
The example above detect if the message fails, but what if the sending was canceled by user?
Modify the above code:
Dim msg As New Mail.MailMessage msg.From = New Mail.MailAddress(StrSender) msg.To.Add(New Mail.MailAddress(StrRecipient)) msg.CC.Add(New Mail.MailAddress(StrCarbonCopy)) msg.Subject = "Message subject" msg.Body = "Hello, " & vbCrLf & _ "This is message body" msg.IsBodyHtml = False 'Set this to True if body is HTML msg.Attachments.Add(New Mail.Attachment("c:\temp\file.att")) Dim smtp As New Mail.SmtpClient("127.0.0.1") 'Replace with the IP address of SMTP server. 'If the server is on non default port. Use Mail.SmtpClient(server,port) 'If the server requires an username and a password smtp.Credentials = New System.Net.NetworkCredential(MailServerUserName, MailServerPassword) AddHandler smtp.SendCompleted, AddressOf SendCompletedCallback Try 'Try to send the message smtp.Send(msg) Catch exc As Exception 'Failed to send message. Create an .eml and store it for later send attempt smtp.DeliveryMethod = Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory smtp.PickupDirectoryLocation = "c:\temp\eml" smtp.Send(msg) Finally 'Dispose of the objects smtp.Dispose() smtp = Nothing End Try msg.Dispose() msg = Nothing
And add the specified method
Private Shared mailSent As Boolean = False Private Shared Sub SendCompletedCallback(ByVal sender As Object, ByVal e As ComponentModel.AsyncCompletedEventArgs) ' Get the unique identifier for this asynchronous operation. Dim token As String = CStr(e.UserState) If e.Cancelled Then Console.WriteLine("[{0}] Send canceled.", token) End If If e.Error IsNot Nothing Then Console.WriteLine("[{0}] {1}", token, e.Error.ToString()) Else Console.WriteLine("Message sent.") End If mailSent = True End Sub