EASendMail SMTP Component > Using EASendMail in VB.NET to send email
This page has moved. Click Here! to redirect to our new page.
Introduction
EASendMail is a SMTP component which supports all operations of SMTP/ESMTP protocols (RFC 821, RFC 822, RFC 2554). This tutorial covers everything of sending email with EASendMail in VB.NET.
Installation
You should download the EASendMail SMTP Component Installer and install it on your machine at first.
Add Reference of EASendMail to Visual Stuido.NET Project
To use EASendMail SMTP Component in your project, the first step is "Add reference of EASendMail to your project". Please create/open your project with Visual Studio.NET, then choose menu->"Project"->"Add Reference"->".NET"->"Browse...", and choose the EASendMail{version}.dll from your disk, click "Open"->"OK", the reference of EASendMail will be added to your project, and you can start to use EASendMail to send email in your project.
Because EASendMail has separate builds for .Net Framework, please refer to the following table and choose the correct dll.
Separate builds of run-time assembly for .Net Framework 1.1, 2.0, 3.5, 4.0 and .Net Compact Framework 2.0, 3.5.
| File | .NET Framework Version |
| EASendMail.dll |
Built with .NET Framework 1.1
It requires .NET Framework 1.1, 2.0, 3.5 or later version. |
| EASendMail20.dll |
Built with .NET Framework 2.0
It requires .NET Framework 2.0, 3.5 or later version. |
| EASendMail35.dll |
Built with .NET Framework 3.5
It requires .NET Framework 3.5 or later version. |
| EASendMaill40.dll |
Built with .NET Framework 4.0
It requires .NET Framework 4.0 or later version. |
| EASendMailCF20.dll |
Built with .NET Compact Framework 2.0
It requires .NET Compact Framework 2.0, 3.5 or later version. |
| EASendMailCF35.dll |
Built with .NET Compact Framework 3.5
It requires .NET Compact Framework 3.5 or later version. |
A simple email sending project
First of all, let's create a VB.NET console project at first, then add the reference of EASendMail in your project (Please refer to previous section).
Add the following code like this:
'[VB.NET Example - Send Simple Email]
Imports EASendMail 'Add EASendMail namespace
Module Module1
Sub Main()
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
'Set sender email address, please change it to yours
oMail.From = "test@emailarchitect.net"
'Set recipient email address, please change it to yours
oMail.To = "support@emailarchitect.net"
'Set email subject
oMail.Subject = "test email from VB.NET project"
'Set email body
oMail.TextBody = "this is a test email sent from VB.NET project, do not reply"
'Your smtp server address
Dim oServer As New SmtpServer("smtp.emailarchitect.net")
'User and password for ESMTP authentication, if your server doesn't require
'User authentication, please remove the following codes.
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
'If your smtp server requires SSL connection, please add this line
'oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Try
Console.WriteLine("start to send email ...")
oSmtp.SendMail(oServer, oMail)
Console.WriteLine("email was sent successfully!")
Catch ep As Exception
Console.WriteLine("failed to send email with the following error:")
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
If you set everything right, you can get "email was sent successfully". If you get "failed to send email with the following error:", then please have a look at the following section.
Where can I get my SMTP email server address, user and password?
Because each email account provider has different server address, so you should query your SMTP server address from your email account provider. To prevent spreading email from the server, most SMTP servers also require user authentication. User name is your email address or your email address without domain part, it depends on your email provider setting.
When you execute above example code, if you get error about "Networking connection" or "No such host", it is likely that your SMTP server address is not correct. If you get an error like "5xx Relay denied", it is likely that you did not set user authentication. Another common error is "5xx Must issue a STARTTLS command first" or "No supported authentication marshal found!", that is because your SMTP server requires user authentication under SSL connection. You can set the SSL connection to solve this problem.
Finally, if you have already set your account in your email client such as Outlook or Window Mail, you can query your SMTP server address, user in your email client. For example, you can choose menu -> "Tools" - > - "Accounts" - > "Your email account" - > "Properties" - > "Servers" in Outlook express or Windows Mail to get your SMTP server, user. Using EASendMail to send email does not require you have email client installed on your machine or MAPI, however you can query your exist email accounts in your email client.
Email Address Syntax and Multiple Recipients
Mail Address Syntax in EASendMail SMTP Component:
For single email address (From, ReplyTo, ReturnPath), the syntax can be: ["][display name]["]<email address>.
For example: "Tester, T" <test@adminsystem.com>, Tester <test@adminsystem.com>, <test@adminsystem.com> or test@adminsystem.com.
For mulitple email address (To, CC, Bcc), the syntax can be: [single email],[single email]... (,;\r\n) can be used to separate multiple email addresses.
For example: "Tester, T" <test1@adminsystem.com>, Tester2 <test2@adminsystem.com>, <test3@adminsystem.com>, test4@adminsystem.com
To better understand the email address syntax in EASendMail, please refer to the following codes.
'[VB.NET Example - Email syntax]
'From is a MailAddress object in VB.NET/Visual Basic.NET
oMail.From = New MailAddress("Tester", "test@adminsystem.com")
oMail.From = New MailAddress("Tester<test@adminsystem.com>")
oMail.From = New MailAddress("test@adminsystem.com")
'To, Cc and Bcc is a AddressCollection object, in VB.NET/Visual Basic.NET
' Multiple addresses are separated with (,)
' The syntax is like this: "test@adminsystem.com, test1@adminsystem.com"
oMail.To = New AddressCollection("test1@adminsystem.com, test2@adminsystem.com")
oMail.To = New AddressCollection("Test1<test@adminsystem.com>, Test2<test2@adminsystem.com>")
' You can add more recipient by Add method
oMail.To.Add(New MailAddress("tester", "test@adminsystem.com"))
' You can also add carbon copy (CC) or blind carbon copy (BCC) in the email.
oMail.Cc.Add(New MailAddress("CC recipient", "cc@adminsystem.com"))
oMail.Bcc.Add(New MailAddress("Bcc recipient", "bcc@adminsystem.com"))
Send email over SSL Connection
SSL connection encrypts data between the SMTP component and SMTP server to protects user, password and email content in TCP/IP level. Now this technology is commonly used and many SMTP servers are deployed with SSL such as Gmail. There are two ways to deploy SSL on SMTP server: 1. Using STARTTLS command to switch SSL channel on normal SMTP port (25); 2. Deploying SSL on another port (465 or other port, you may query it from your server administrator) directly. EASendMail SMTP component supports both ways.
The following samples demonstrate how to send email over SSL connection with Gmail, Yahoo and Hotmail account.
Send email by Gmail account with SSL connection
'[VB.NET Example - Send Email by Gmail Account with SSL connection]
Imports EASendMail 'Add EASendMail namespace
Module Module1
Sub Main()
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
'Your gmail email address
oMail.From = "gmailid@gmail.com"
'Set recipient email address, please change it to yours
oMail.To = "support@emailarchitect.net"
'Set email subject
oMail.Subject = "test email from gmail account"
'Set email body
oMail.TextBody = "this is a test email sent from VB.NET project with gmail"
'Gmail SMTP server address
Dim oServer As New SmtpServer("smtp.gmail.com")
'gmail user authentication should use your
'gmail email address as the user name.
oServer.User = "gmailid@gmail.com"
oServer.Password = "yourpassword"
'Send email over SSL/TLS connection.
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Try
Console.WriteLine("start to send email over SSL ...")
oSmtp.SendMail(oServer, oMail)
Console.WriteLine("email was sent successfully!")
Catch ep As Exception
Console.WriteLine("failed to send email with the following error:")
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
Send email by Yahoo account with SSL connection
'[VB.NET Example - Send Email by Yahoo Account with SSL connection]
Imports EASendMail 'Add EASendMail namespace
Module Module1
Sub Main()
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
'Your Yahoo email address
oMail.From = "myid@yahoo.com"
'Set recipient email address, please change it to yours
oMail.To = "support@emailarchitect.net"
'Set email subject
oMail.Subject = "test email from yahoo account"
'Set email body
oMail.TextBody = "this is a test email sent from VB.NET project with yahoo"
'Yahoo SMTP server address
Dim oServer As New SmtpServer("smtp.mail.yahoo.com")
'yahoo user authentication should use your
'yahoo email address as the user name.
oServer.User = "myid@yahoo.com"
oServer.Password = "yourpassword"
'Because yahoo deploys SMTP server on 465 port with direct SSL connection.
'So we should change the port to 465.
oServer.Port = 465
'Send email over SSL/TLS connection.
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Try
Console.WriteLine("start to send email over SSL ...")
oSmtp.SendMail(oServer, oMail)
Console.WriteLine("email was sent successfully!")
Catch ep As Exception
Console.WriteLine("failed to send email with the following error:")
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
Send email by MSN/hotmail account with SSL connection
'[VB.NET Example - Send Email by MSN/hotmail Account with SSL connection]
Imports EASendMail 'Add EASendMail namespace
Module Module1
Sub Main()
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
'Your hotmail email address
oMail.From = "liveid@hotmail.com"
'Set recipient email address, please change it to yours
oMail.To = "support@emailarchitect.net"
'Set email subject
oMail.Subject = "test email from hotmail account"
'Set email body
oMail.TextBody = "this is a test email sent from VB.NET project with hotmail"
'Hotmail SMTP server address
Dim oServer As New SmtpServer("smtp.live.com")
'hotmail user authentication should use your
'email address as the user name.
oServer.User = "liveid@hotmail.com"
oServer.Password = "yourpassword"
'Send email over SSL/TLS connection.
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Try
Console.WriteLine("start to send email over SSL ...")
oSmtp.SendMail(oServer, oMail)
Console.WriteLine("email was sent successfully!")
Catch ep As Exception
Console.WriteLine("failed to send email with the following error:")
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
Reply-To, Return-Path and Mail Priority
If you want to set another email address to get the replied email rather than your From address, you can use ReplyTo property.
If you want to set another email address to get the delivery report rather than your From address, you can use ReturnPath property.
If you want to set Higher or Lower priority to your email, you can use Priority prority
Send email directly without SMTP server(MX DNS lookup)
In general, we send email via specified SMTP server. How does the specified SMTP server know what address this email should be sent to? The answer is... it queries MX record of recipient's domain via DNS lookup. It then forwards this email to the SMTP server queried from DNS server. If recipient's server doesn't work fine, sender's SMTP server will send a failure-delivery report to the sender telling it failed to send out the email.
How does EASendMail SMTP component work with "Send email directly"? Firstly, it queries MX record for recipient address from DNS, then sends email to recipient's email server directly. In short, if no SMTP server is specified in the code, EASendMail will send email to recipient directly. Since querying DNS server consumes CPU time and networking resource, the performance of "Send email directly" is lower than sending email with specified SMTP server. Moreover, nowadays more and more SMTP servers block email sent from dynamic IP address, so we don't recommend you to use "Direct Send Email" except you have a static IP address or you encounter problem with your ISP SMTP server.
Every recipient may have different SMTP server, if there are multiple recipients in one message and you want to send email directly, you should send the email to the recipients one by one.
To implement this feature, you just need to put nothing to SMTP server address.
'[VB.NET Example - Send Email Directly without SMTP Server]
Imports EASendMail 'Add EASendMail namespace
Module Module1
Sub Main()
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
'Set sender email address, please change it to yours
oMail.From = "test@emailarchitect.net"
'Set recipient email address, please change it to yours
oMail.To = "support@emailarchitect.net"
'Set email subject
oMail.Subject = "direct email sent from VB.NET project"
'Set email body
oMail.TextBody = "this is a test email sent from VB.NET project directly"
'Set SMTP server address to ""
Dim oServer As New SmtpServer("")
'Do not set user authentication
'Do not set SSL connection
Try
Console.WriteLine("start to send email directly ...")
oSmtp.SendMail(oServer, oMail)
Console.WriteLine("email was sent successfully!")
Catch ep As Exception
Console.WriteLine("failed to send email with the following error:")
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
With above code, if you get error like "5xx IP address rejected", that means your IP address is blocked by the recipient's SMTP server. You have to specify a SMTP server with user authentication to relay your email.
Send email with Html body
If you want to specify the font, color or insert pictures in your email, you should use Html email format instead of Plain text email format. The following sample demonstrates how to use HtmlBody to send a HTML email.
'[VB.NET Example - Send HTML Email]
Imports EASendMail 'Add EASendMail namespace
Module Module1
Sub Main()
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
'Set sender email address, please change it to yours
oMail.From = "test@emailarchitect.net"
'Set recipient email address, please change it to yours
oMail.To = "support@emailarchitect.net"
'Set email subject
oMail.Subject = "test HTML email from VB.NET project"
'Set HTML email body
oMail.HtmlBody = "<font size=5>This is</font> <font color=red><b>a test</b></font>"
'Your smtp server address
Dim oServer As New SmtpServer("smtp.emailarchitect.net")
'User and password for ESMTP authentication, if your server doesn't require
'User authentication, please remove the following codes.
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
'If your smtp server requires SSL connection, please add this line
'oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Try
Console.WriteLine("start to send HTML email ...")
oSmtp.SendMail(oServer, oMail)
Console.WriteLine("email was sent successfully!")
Catch ep As Exception
Console.WriteLine("failed to send email with the following error:")
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
After you received the email by your email client, the body text is like this:
Of course, you don't have to write the HTML source body text in your application manually. You can build a html file with HTML tools and use ImportHtmlBody method to import the html file directly.
You can also refer to the htmlmail.xx samples in EASendMail SMTP Component installer. Those samples demonstrate how to build a HTML email editor and send HTML email with attachment or embedded pictures/images.
Send email with Attachment
To send an email with attachment, we need to use AddAttachment method. This method can attach a file to the email message from local disk or a remote URL.
'[VB.NET Example - Send Email with File Attachment]
Imports EASendMail 'Add EASendMail namespace
Module Module1
Sub Main()
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
'Set sender email address, please change it to yours
oMail.From = "test@emailarchitect.net"
'Set recipient email address, please change it to yours
oMail.To = "support@emailarchitect.net"
'Set email subject
oMail.Subject = "test HTML email with attachment"
'Set HTML email body
oMail.HtmlBody = "<font size=5>This is</font> <font color=red><b>a test</b></font>"
'Your smtp server address
Dim oServer As New SmtpServer("smtp.emailarchitect.net")
'User and password for ESMTP authentication, if your server doesn't require
'User authentication, please remove the following codes.
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
'If your smtp server requires SSL connection, please add this line
'oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Try
'adds attachment from local disk
oMail.AddAttachment( "d:\test.pdf" )
'adds attachment from remote website
oMail.AddAttachment( "http://www.emailarchitect.net/webapp/img/logo.jpg" )
Console.WriteLine("start to send email with attachment ...")
oSmtp.SendMail(oServer, oMail)
Console.WriteLine("email was sent successfully!")
Catch ep As Exception
Console.WriteLine("failed to send email with the following error:")
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
Send email with Embedded Picture/Image
To attach an embedded picture to email, you should add an attachment to email at first. Then you should assign an unique identifier(contentid) to this attachment. Finally, you need to replace the <img src="your file name" /> to <img src="cid:yourcontentid" />.
'[VB.NET Example - Send Email with Embedded Images]
Imports EASendMail 'Add EASendMail namespace
Module Module1
Sub Main()
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
'Set sender email address, please change it to yours
oMail.From = "test@emailarchitect.net"
'Set recipient email address, please change it to yours
oMail.To = "support@emailarchitect.net"
'Set email subject
oMail.Subject = "test HTML email with embedded image"
'Your smtp server address
Dim oServer As New SmtpServer("smtp.emailarchitect.net")
'User and password for ESMTP authentication, if your server doesn't require
'User authentication, please remove the following codes.
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
'If your smtp server requires SSL connection, please add this line
'oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Try
'adds attachment from local disk
Dim oAttachment As Attachment = oMail.AddAttachment("d:\test.gif")
'specifies the attachment as an embedded picture
'contentid can be any string.
Dim contentID As String = "test001@host"
oAttachment.ContentID = contentID
oMail.HtmlBody = "<html><body>this is a <img src=""cid:" _
+ contentID + """> embedded picture.</body></html>"
Console.WriteLine("start to send email with embedded image ...")
oSmtp.SendMail(oServer, oMail)
Console.WriteLine("email was sent successfully!")
Catch ep As Exception
Console.WriteLine("failed to send email with the following error:")
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
To attach embedded images/pictures, SmtpMail.ImportHtmlBody and SmtpMail.ImportHtml methods are strongly recommended. With these methods, you don't have to specify the ContentID manually. The html source/file html body can be imported to email with embedded pictures automatically.
Send email with Digital Signature(S/MIME)
Digital signature prevents email content is faked or changed in transport level. Encrypting email protects email content from exposure to inappropriate recipients. Both digital signature and email encrypting depend on digital certificate.
If you have an email digital signature certificate installed on your machine, you can find it in "Control Panel" -> "Internet Options" -> "Content" -> "Certificates" -> "Personal".
Then you can use your email certificate to sign the email by the following code. If you don't have a certificate for your email address, you MUST get a digital certificate for personal email protection from third-party certificate authorities such as www.verisign.com.
'[VB.NET Example - Send Email with Digital Signature (S/MIME)]
Imports EASendMail 'Add EASendMail namespace
Module Module1
Sub Main()
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
'Set sender email address, please change it to yours
oMail.From = "test@emailarchitect.net"
'Set recipient email address, please change it to yours
oMail.To = "support@emailarchitect.net"
'Set email subject
oMail.Subject = "test email with digital signature"
'Set email body
oMail.TextBody = "this is a test email with digital signature (S/MIME)"
'Your smtp server address
Dim oServer As New SmtpServer("smtp.emailarchitect.net")
'User and password for ESMTP authentication, if your server doesn't require
'User authentication, please remove the following codes.
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
'If your smtp server requires SSL connection, please add this line
'oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Try
'Find certificate by email adddress in My Personal Store.
'Once the certificate is loaded to From, the email content
'will be signed automatically
oMail.From.Certificate.FindSubject(oMail.From.Address, _
Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER, _
"My")
Catch exp As Exception
Console.WriteLine("No sign certificate found for <" + _
oMail.From.Address + ">:" + exp.Message)
End Try
Try
Console.WriteLine("start to send email ...")
oSmtp.SendMail(oServer, oMail)
Console.WriteLine("email was sent successfully!")
Catch ep As Exception
Console.WriteLine("failed to send email with the following error:")
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
Send email with Email Encryption(S/MIME)
After the recipient received your email with digital signature, the recipient can get your digital certificate public key from your digital signature. Then the recipient can encrypt an email with your public key and send it to you. Only you can decrypt this email with your private key. That is how S/MIME can protect your email content. If you don't expose your digital certificate private key to others, none can read your email which is encrypted by your public key.
If you received an email with digital signature, your email client usually stores the public key of the sender in "Control Panel" -> "Internet Options" -> "Content" -> "Certificates" -> "Other People".
Then you can use the following code to encrypt email and send it to your recipient.
'[VB.NET Example - Encrypt email with certificate (S/MIME)]
Imports EASendMail 'Add EASendMail namespace
Module Module1
Sub Main()
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
'Set sender email address, please change it to yours
oMail.From = "test@emailarchitect.net"
'Set recipient email address, please change it to yours
oMail.To = "support@emailarchitect.net"
'Set email subject
oMail.Subject = "test encrypted email"
'Set email body
oMail.TextBody = "this is a test email with email encryption (S/MIME)"
'Your smtp server address
Dim oServer As New SmtpServer("smtp.emailarchitect.net")
'User and password for ESMTP authentication, if your server doesn't require
'User authentication, please remove the following codes.
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
'If your smtp server requires SSL connection, please add this line
'oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Try
'Find certificate by email adddress in My Personal Store.
'Once the certificate is loaded to From, the email content
'will be signed automatically
oMail.From.Certificate.FindSubject(oMail.From.Address, _
Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER, _
"My")
Catch exp As Exception
Console.WriteLine("No sign certificate found for <" + _
oMail.From.Address + ">:" + exp.Message)
End Try
Dim count As Integer = oMail.To.Count
For i As Integer = 0 To count - 1
Dim oAddress As MailAddress = oMail.To(i)
Try
'Find certificate by email adddress in My Other Peoples Store.
'The certificate can be also imported by *.cer file like this:
'oAddress.Certificate.Load("c:\encrypt1.cer")
'Once the certificate is loaded to MailAddress, the email content
' will be encrypted automatically
oAddress.Certificate.FindSubject(oAddress.Address, _
Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER, _
"AddressBook")
Catch ep As Exception
Try
oAddress.Certificate.FindSubject(oAddress.Address, _
Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER, _
"My")
Catch exp As Exception
Console.WriteLine("No encryption certificate found for <" + _
oAddress.Address + ">:" + exp.Message)
End Try
End Try
Next
Try
Console.WriteLine("start to send encrypted email ...")
oSmtp.SendMail(oServer, oMail)
Console.WriteLine("email was sent successfully!")
Catch ep As Exception
Console.WriteLine("failed to send email with the following error:")
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
If you received digital signed and encrypted email by Windows Mail(Outlook Express), it looks like this:
Send email with Event Handler
After SendMail method is invoked, if you want to know the progress of the email sending, you should use Event Handler. The following sample codes demonstrate how to use Event Handler to monitor the progress of email sending.
'[VB.NET Example - Send Email with Event Handler]
Imports EASendMail 'Add EASendMail namespace
Module Module1
Sub OnIdle(ByVal sender As Object, ByRef cancel As Boolean)
' this event is fired when the SmtpClient is wait for response from
' smtp server, if you add Application.DoEvents in windows form application,
' it can prevent your form has no response before SendMail is not returned.
' Application.DoEvents()
End Sub
Sub OnConnected(ByVal sender As Object, ByRef cancel As Boolean)
Console.WriteLine("Connected")
End Sub
Sub OnSendingDataStream(ByVal sender As Object, ByVal sent As Integer, _
ByVal total As Integer, ByRef cancel As Boolean)
Console.WriteLine(String.Format("{0}/{1} sent", sent, total))
End Sub
Sub OnAuthorized(ByVal sender As Object, ByRef cancel As Boolean)
Console.WriteLine("Authorized")
End Sub
Sub OnSecuring(ByVal sender As Object, ByRef cancel As Boolean)
Console.WriteLine("Securing ...")
End Sub
Sub Main()
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
'Set sender email address, please change it to yours
oMail.From = "test@emailarchitect.net"
'Set recipient email address, please change it to yours
oMail.To = "support@emailarchitect.net"
'Set email subject
oMail.Subject = "test email from VB.NET with event handler"
'Set email body
oMail.TextBody = "this is a test email sent from VB.NET with event handler"
'Your smtp server address
Dim oServer As New SmtpServer("smtp.emailarchitect.net")
'User and password for ESMTP authentication, if your server doesn't require
'User authentication, please remove the following codes.
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
'If your smtp server requires SSL connection, please add this line
'oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
'Catching the following events is not necessary,
'just make the application more user friendly.
'If you use the object in asp.net/windows service or non-gui application,
'You need not to catch the following events.
'To learn more detail, please refer to the code in EASendMail EventHandler
AddHandler oSmtp.OnIdle, AddressOf OnIdle
AddHandler oSmtp.OnAuthorized, AddressOf OnAuthorized
AddHandler oSmtp.OnConnected, AddressOf OnConnected
AddHandler oSmtp.OnSecuring, AddressOf OnSecuring
AddHandler oSmtp.OnSendingDataStream, AddressOf OnSendingDataStream
Try
Console.WriteLine("start to send email with event handler ...")
oSmtp.SendMail(oServer, oMail)
Console.WriteLine("email was sent successfully!")
Catch ep As Exception
Console.WriteLine("failed to send email with the following error:")
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
Send email with Asynchronous Mode
In synchronous mode, once SendMail method is called, it returns to application after the method is complete. Therefore, if the runtime (it depends on the networking connection and the email size) is long, your application cannot do anything before this method ends, which results "my application is blocked or halted". In contrast, in asynchronous mode, as BeginSendMail method works in background, this methods return to application immediately no matter the running method is complete or not.
The following sample codes demonstrate how to send email in asynchronous mode.
'[VB.NET Example - Send Email with Asynchronous Mode]
Imports EASendMail 'Add EASendMail namespace
Module Module1
Sub Main()
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
'Set sender email address, please change it to yours
oMail.From = "test@emailarchitect.net"
'Set recipient email address, please change it to yours
oMail.To = "support@emailarchitect.net"
'Set email subject
oMail.Subject = "test asynchronous email from VB.NET"
'Set email body
oMail.TextBody = "this is a test email sent from VB.NET with asynchronous mode"
'Your smtp server address
Dim oServer As New SmtpServer("smtp.emailarchitect.net")
'User and password for ESMTP authentication, if your server doesn't require
'User authentication, please remove the following codes.
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
'If your smtp server requires SSL connection, please add this line
'oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Try
Console.WriteLine("start to send email in asynchronous mode ...")
Dim oResult As SmtpClientAsyncResult = oSmtp.BeginSendMail( _
oServer, oMail, Nothing, Nothing)
'Wati for the email sending...
Do While (Not oResult.IsCompleted)
Console.WriteLine("waiting..., you can do other thing!")
oResult.AsyncWaitHandle.WaitOne(50, False)
Loop
oSmtp.EndSendMail(oResult)
Catch ep As Exception
Console.WriteLine("failed to send email with the following error:")
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
Send email with Multiple Threads(Mass Mail)
Based on asynchronous mode, you can create multiple SmtpClient instances in your application and send email in multiple threads. Here is a simple sample demonstrates how to use asynchronous mode to send email in multiple threads.
'[VB.NET Example - Send Mass Emails with Multiple Threads(Mass Mail)]
Imports EASendMail 'Add EASendMail namespace
Module Module1
Sub Main()
Dim arRcpt() As String = {"test1@adminsystem.com", _
"test2@adminsystem.com", _
"test3@adminsystem.com"}
Dim nRcpt As Integer = arRcpt.Length
Dim arMail(nRcpt - 1) As SmtpMail
Dim arSmtp(nRcpt - 1) As SmtpClient
Dim arResult(nRcpt - 1) As SmtpClientAsyncResult
For i As Integer = 0 To nRcpt - 1
arMail(i) = New SmtpMail("TryIt")
arSmtp(i) = New SmtpClient()
Next
For i As Integer = 0 To nRcpt - 1
Dim oMail As SmtpMail = arMail(i)
'Set sender email address
oMail.From = "sender@emailarchitect.net"
'Set recipient email address
oMail.To = arRcpt(i)
'Set email subject
oMail.Subject = "mass email test from vb.net"
'Set email body
oMail.TextBody = "test from c#, this email is sent to " + arRcpt(i)
'Your smtp server address
Dim oServer As New SmtpServer("smtp.emailarchitect.net")
'User and password for ESMTP authentication, if your server doesn't require
'User authentication, please remove the following codes.
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
'If your smtp server requires SSL connection, please add this line
'oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Dim oSmtp As SmtpClient = arSmtp(i)
'Submit email to BeginSendMail method and return
'to process another email
arResult(i) = oSmtp.BeginSendMail(oServer, oMail, Nothing, Nothing)
Console.WriteLine(String.Format("Start to send email to {0} ...", _
arRcpt(i)))
Next
'all emails were sent by BeginSendMail Method
'now get result by EndSendMail method
Dim nSent As Integer = 0
Do While (nSent < nRcpt)
For i As Integer = 0 To nRcpt - 1
'this email is finished
If (arResult(i) Is Nothing) Then
Continue For
End If
'wait for specified email ...
If (Not arResult(i).AsyncWaitHandle.WaitOne(10, False)) Then
Continue For
End If
Try
'this email is finished, using EndSendMail to get result
arSmtp(i).EndSendMail(arResult(i))
Console.WriteLine(String.Format("Send email to {0} successfully", _
arRcpt(i)))
Catch ep As Exception
Console.WriteLine( _
String.Format("Failed to send email to {0} with error {1}: ", _
arRcpt(i), ep.Message))
End Try
'Set this email result to null, then it won't be processed again
arResult(i) = Nothing
nSent += 1
Next
Loop
End Sub
End Module
Total Sample Projects
After you downloaded the EASendMail SMTP Component Installer and install it on your machine, there are many samples in the installation path.
| asp | Send email from ASP (VBScript, JScript) - ActiveX/COM |
| asp_queue | Send email from ASP to EASendMail Service. (VBScript, JScript) - ActiveX/COM |
| asp_queue_database | Send email from ASP to EASendMail Service, EASendMail service will select recipients from database. (VBScript, JScript) - ActiveX/COM |
| asp_net | Send email from ASP.NET. (C#, VB, JScript.NET) |
| asp_net_batch | Send bulk emails with multiple threads from ASP.NET. (C#, VB) |
| asp_net_queue | Send email from ASP.NET to EASendMail Service. (C#, VB, JScript.NET) |
| asp_net_queue_database | Send email from ASP.NET to EASendMail Service, EASendMail service will select recipients from database. (C#, VB, JScript.NET) |
| simple.vb6 | Send text/plain email from Visual Basic 6.0. This sample also demonstrates digital signature, email encryption. (VB6) - ActiveX/COM |
| simple.vcNative | Send text/plain email from Visual C++. This sample also demonstrates digital signature, email encryption. (Visual C++) - ActiveX/COM |
| simple.vb | Send text/plain email from Visual Basic.NET. This sample also demonstrates digital signature, email encryption. |
| simple.csharp | Send text/plain email from C#. This sample also demonstrates digital signature, email encryption. |
| simple.vc | Send text/plain email from managed c++. This sample also demonstrates digital signature, email encryption. |
| htmlmail.vb6 | Send text/html email from Visual Basic 6.0. This sample also demonstrates embedded pictures, digital signature, email encryption. (VB6) - ActiveX/COM |
| htmlmail.vcNative | Send text/html email from Visual C++. This sample also demonstrates embedded pictures, digital signature, email encryption. (Visual C++) - ActiveX/COM |
| htmlmail.vb | Send text/html email from Visual Basic.NET. This sample also demonstrates embedded pictures, digital signature, email encryption. |
| htmlmail.csharp | Send text/html email from C#. This sample also demonstrates embedded pictures, digital signature, email encryption. |
| mass.vb6 | Send email by FastSender with multiple threadings. This sample also demonstrates email address validating. (VB6) - ActiveX/COM |
| mass.vb | Send email by BeginSendMail with multiple threadings. This sample also demonstrates email address validating. |
| mass.csharp | Send email by BeginSendMail with multiple threadings. This sample also demonstrates email address testing. |
| samples_vs2008\pocketpc.mobile.cs | Send email from PocketPC/Windows Mobile System. |
| samples_vs2008\pocketpc.mobile.vb | Send email from PocketPC/Windows Mobile System. |
See Also
Send Email in C#/CSharp.NET - Toturial
Send Email in Visual Basic 6.0 - Toturial
Send Email in Managed C++ - Toturial
Send Email in Visual C++ - Toturial
Free Email Support
Not enough? Please contact our technical support team.
Support@EmailArchitect.NET
VIP@EmailArchitect.NET(Registered User)
Remarks
We usually reply emails in 24hours. The reason for getting no response is likely
that your smtp server bounced our reply. In this case, please try to use another
email address to contact us. Your Hotmail or Yahoo email account is recommended.
|