Click here to Skip to main content
Click here to Skip to main content

Send SMTP mail using VB.NET

By , 1 Oct 2002
 

Introduction

I needed a way to send a smtp mail message from a command prompt to notify me when one our servers failed over using Double-Take.

This article demonstates sending a smtp mail message from the command prompt

    
Imports System.Web.Mail
    
Sub Main()
        Dim strMSG As String
        Dim strArgs() As String = Command.Split(",")
        Dim blnSMTP As Boolean = False
        Dim blnCC As Boolean = False
        Dim blnAttachments As Boolean = False

        'get the product name, version and description from the assembly
        strMSG = vbCrLf + vbCrLf + _
          System.Diagnostics.FileVersionInfo.GetVersionInfo( _ 
      System.Reflection.Assembly.GetExecutingAssembly.Location).ProductName _
              + " v" + System.Diagnostics.FileVersionInfo.GetVersionInfo( _
      System.Reflection.Assembly.GetExecutingAssembly.Location _
            ).ProductVersion + vbCrLf + _
         System.Diagnostics.FileVersionInfo.GetVersionInfo( _
         System.Reflection.Assembly.GetExecutingAssembly.Location _
              ).Comments + vbCrLf + vbCrLf

        If UBound(strArgs) < 3 Then
            strMSG = strMSG + "Usage: EPSendMail from@email.com, " + _
                   "to@email.com, subject, message, [smtp Server],"  + _
                   "[cc1@email.com;cc2@email.com;...], [attachment1;" + _
                        "attachment2;...]" + vbCrLf
            Console.Write(strMSG)
            Exit Sub
        End If

        strMSG = strMSG + "Sending email message" + vbCrLf + _
            "  From        --> " + Trim(strArgs(0)) + vbCrLf + _
            "  To          --> " + Trim(strArgs(1)) + vbCrLf + _
            "  Subject     --> " + Trim(strArgs(2)) + vbCrLf + _
            "  Message     --> " + Trim(strArgs(3)) + vbCrLf
        If UBound(strArgs) >= 4 Then
            If Len(Trim(strArgs(4))) > 0 Then
                blnSMTP = True
                strMSG = strMSG + "  SMTP Server --> " + Trim(strArgs(4)) + _
                   vbCrLf
            End If
        End If
        If UBound(strArgs) >= 5 Then
            If Len(Trim(strArgs(5))) > 0 Then
                blnCC = True
                strMSG = strMSG + "  CC          --> " + Trim(strArgs(5)) + _
                   vbCrLf
            End If
        End If
        If UBound(strArgs) >= 6 Then
            If Len(Trim(strArgs(6))) > 0 Then
                blnAttachments = True
                strMSG = strMSG + "  Attachments --> " + Trim(strArgs(6)) + _
                   vbCrLf
            End If
        End If
        Console.Write(strMSG)

        'send the email
        Try
            Dim insMail As New MailMessage()
            With insMail
                .From = Trim(strArgs(0))
                .To = Trim(strArgs(1))
                .Subject = Trim(strArgs(2))
                .Body = Trim(strArgs(3))
                If blnCC Then .Cc = Trim(strArgs(5))
                If blnAttachments Then
                    Dim strFile As String
                    Dim strAttach() As String = Split(strArgs(6), ";")
                    For Each strFile In strAttach
                        .Attachments.Add(New MailAttachment(Trim(strFile)))
                    Next
                End If
            End With
            If blnSMTP Then SmtpMail.SmtpServer = Trim(strArgs(4))

            SmtpMail.Send(insMail)

            Console.WriteLine("Successfully sent email message" + vbCrLf)

        Catch err As Exception
            Console.WriteLine("EXCEPTION " + err.Message + vbCrLf)
        End Try

    End Sub

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Chris Dufour
Web Developer
Canada Canada
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralExceptions when running from renaming path on Vista? [modified]memberJohn Boster12 Sep '08 - 16:57 
I found a weird issue that seems to only happen on Vista.
 
If I compile the project and put the exe in c:\epsendmail for example I can run it fine.
However as soon as I rename the directory (i.e. c:\epssendmail2) it will be unable to send email and the error message is "The transport failed to connect to the server."
 
Now if I move epsendmail.exe out of c:\epsendmail2 and then move it back it'll fix it. I can also copy it out of c:\epsendmail2 and copy it back (overwriting the current epsendmail.exe inside c:\epsendmail2) and it'll work.
 
If you want to try it yourself here's a quick way to do it (through DOS):
 
First, put epsendmail.exe in c:\epsendmail
 
Now open DOS and do:
 
c:\epsendmail\epsendmail.exe someone@example.com, me@mysite.com, test, test, smtp.emailserver.com
 
And it'll send successfully. Now do:
 
REN c:\epsendmail epsendmail2
c:\epsendmail2\epsendmail.exe someone@example.com, me@mysite.com, test, test, smtp.emailserver.com
 
And it'll fail to send. You can try running it as many times as you want but it always fails.
 
Now if you do:
 
move c:\epsendmail2\epsendmail.exe c:\
move c:\epsendmail.exe c:\epsendmail2\
c:\epsendmail2\epsendmail.exe someone@example.com, me@mysite.com, test, test, smtp.emailserver.com
 
It'll work again. But now if you rename c:\epsendmail2 to c:\epsendmail or whatever it'll break again until you move the executable out and back into the renamed directory.
 
This all happens with copies too, copy c:\epsendmail to c:\epsendmail2 and the version in c:\epsendmail2 will fail.
 
Anyone else have this issue on Vista?
 
I'm wondering if it's firewall or .net/vista security related? After renaming the directory I tried adding the new directory and executable to the windows firewall exception list and it still failed. I also tried disabling the firewall and it failed. The only thing I haven't tried is rebooting after disabling or adding the exception. Could it be some security feature where renaming the dir stops it from having access to networking features? I noticed it gets the error instantly no matter what SMTP server I use. However if I try using an IP address instead of a domain name it just hangs. So it's like it's not even resolving IPs after renaming the directory??
 
I believe this is just on Vista as I tested it on XP sP3 without issue, however on my XP system I have the firewall turned off. I'll do some testing later on XP with the firewall on and see if it happens.
 
Thanks.
 
modified on Friday, September 12, 2008 11:17 PM

GeneralImports System.Web.Mail not found [modified]memberSeveley14 Jun '08 - 6:21 
I tryed to add the line
 
Imports System.Web.Mail
 
but my visual studio underline it as Namespace or type 'Mail' for the Imports 'System.Web.Mail' cannot be found.
 
actualy when i type System. the autocomplete dont show the Web at all.
i'm missing some component of VB .Net ? where can i get it ?
 
any idea ?
 
Seveley
 
=== edit ===
 
I installed VS studio 2008 ( had 2002 before ) and now I have System.Net.Mail Smile | :) for all that have the same problem as me
 
modified on Sunday, June 15, 2008 9:54 PM

GeneralRe: Imports System.Web.Mail not found [modified]memberdcalvinisti8 Apr '12 - 13:04 
Try changing your imports to Imports System.Net.Mail... it should work.
Generalproblem smtservermemberraquidd2218 Mar '08 - 15:55 
i dont know why the email no arrive
 
EPSendMail v1.0.2999.36948
Console application to send smtp mail
 
Sending email message
From --> test@test.com
To --> raquidd@yahoo.com
Subject --> test
Message --> test
SMTP Server --> 127.0.0.1

 
the only think is the test@test.com
if i use window xp and i not count how i can do
 
thanks for the time
GeneralRe: problem smtservermemberraquidd2218 Mar '08 - 16:30 
i have the email in the Mailroot Queue
 
i found a article about
 
Ensure that your machine is able to resolve MX
records for the destination domain in the DNS"
 
i trying to follow the article but i dont understand the part with
i configure with me isp
 
is possible i send emai Through me isp without ask he
 
thanks for the time
GeneralGreat ArticlesmemberVuyiswamb21 Oct '07 - 20:07 
hi
This is a very good article. one vote for it. i have Question. am using vb2003, .NET 1.1, so i want to use mail namespace, but it seems it doesnt work there, everytime i import the namespace.
 
what namespace or how can i send an E-mail in this Framework, because all i get is Web Examples, i want to send from a Windows Application.
 
Vuyiswa Maseko,
 
Sorrow is Better than Laughter, it may Sudden your Face, but It sharpens your Understanding
 
VB.NET/SQL7/2000/2005
http://vuyiswamb.007ihost.com
http://Ecadre.007ihost.com
vuyiswam@tshwane.gov.za
 

QuestionDo we really need an SMTP Server here ?memberJustme4u27 Sep '07 - 5:04 
Do we really need to have an SMTP Server ? because if we digg into the real anonymous mail programs they don't need the SMTP Server to send the mails. instead they just send it with your IP Address. Is it possible with this program ?
 
I tried so but it not sending the mails without SMTP Server Suspicious | :suss:
Generalsending mailsmemberdivyathannippara18 Mar '07 - 18:38 
i have done codings for sending mail in vb.net ...it not showing errors..but i didnt get mail in inbox?
what is the pblm ? can u help me?
GeneralCDO.Message ErrormemberAndyHug19 Jun '06 - 22:03 

Hi , I used your application but every time I try to run it it gives me the same error
message : Could not access 'CDO.Message' object ...

QuestionSMTP Server Authentication : How To?memberMehdiAnis7 Mar '06 - 3:23 
I use ArgoSoft eMail server from my computer as my SMTP/POP server. SMTP server has authentication turned ON. I have to include Username/Password in order to send eMail through my SMTP server. In the given example nothing about authentication has been mentioned.
 
How can I pass parameters for UserName and Password for SMTP Authentication?
 
Thank you.
 
Regards,
Mehdi Anis
Confused | :confused:
AnswerRe: SMTP Server Authentication : How To?memberChris Dufour7 Mar '06 - 4:03 
Add the following properties to your mail message...
 
insMail.Fields.Add(@"http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); // Basic authentication
insMail.Fields.Add(@"http://schemas.microsoft.com/cdo/configuration/sendusername", <"SmtpUsername">);
insMail.Fields.Add(@"http://schemas.microsoft.com/cdo/configuration/sendpassword", <"SmtpPassword">);

 
Chris

AnswerRe: SMTP Server Authentication : How To?memberMehdiAnis7 Mar '06 - 9:44 
Chris,
Thanks for the prompt reply. I am using Visual Studio 2005. It can not recognize ".Fields" property for "insMail" object. So, I could not use it. I solved my problem, but in a totally different way.
 
In this web site I found another thread where code is given in C# with authentication. Can't remember the thread name/id, but it uses EnhancedMailMessage class. Anyway, I just took the
 
EnhancedMailMessage.cs
 
file from that thread in a new C# DLL project and compiled to a .DLL file. Then, in my VB .NET project I added the .DLL file as REFERENCE and Imported that in my VB code file. Now I can just use the EnhancedMailMessage object directly.
 
Bye now.
AnswerRe: SMTP Server Authentication : How To?memberChris Dufour9 Mar '06 - 3:59 
Hi,
 
Another option for you is to explore the new System.Net.Mail namespace available to the .NET Framework 2.0.
 
To send a mail message with credentials...
 
private void SendMailMessage()
{
try
{
// create the email message
MailMessage mailMessage = new MailMessage(
"test@test.com",
"cdufour@epcanada.com",
"Test email message",
"Test sending an email with an attachment and using credentials...");
 
// create and add the attachment(s)
Attachment attachment = new Attachment("test.xls", MediaTypeNames.Application.Octet);
mailMessage.Attachments.Add(attachment);
 
// create SMTP Client and add credentials if the SMTP server requires them.
SmtpClient smtpClient = new SmtpClient("Your SMTP Server");
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential("user", "password", "domain");
 
//Send the message.
smtpClient.Send(mailMessage);
}
catch (Exception ex)
{
MessageBox.Show(string.Format("{0} \n\n {1}", ex.Message, ex.InnerException.Message));
}
}

 


 
Chris

GeneralProb with CDA.MessagememberBuxo7 Sep '05 - 23:38 
Hi,
running this App, this Err occs:
"Fehler bei Zugriff auf Klasse CDA.Message"
"Error on accessing class CDA.Message".
 
Anybody n idia why this occs?
 
carpe noctem!
GeneralRe: Prob with CDA.MessagesussZ789512313 Sep '05 - 7:50 
your virus scanner is blocking the access to the ColabraDataObject. Library for SMTP support.
Generalhelpmemberpradeesh83sharma5 Sep '05 - 3:49 
This application is not working.Im facing the problem when i press any key the console application window is closing.. Plz let me know why it happens like this..
 

 
thanks
P
GeneralRe: helpmembergthekid26 Jul '07 - 11:57 
same here. did you figure it out yet?

GeneralHTML formatmemberKhraeef15 Jul '05 - 5:22 
Hi,
How can I send email as html format and the Body of the email is already exist as html file without put this file as attachment.
GeneralRe: HTML formatmemberAdamNThompson3 Mar '08 - 17:19 
I wrote class something like this using System.Net.Mail. In mine the message object you send has .IsHtml property.
 
http://www.codeproject.com/KB/aspnet/AdHawkMailer.aspx[^]
 
-Adam N. Thompson

GeneralRe: HTML formatmemberChris_Inman15 Jun '11 - 13:04 
.NET Framework 4 Other Versions
Represents an e-mail message that can be sent using the SmtpClient class.
 
Inheritance Hierarchy
System.Object
System.Net.Mail.MailMessage
Namespace: System.Net.Mail
Assembly: System (in System.dll)
 
.IsBodyHtml Gets or sets a value indicating whether the mail message body is in Html.
 
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.aspx
GeneralSMTP Blocked By McAfee Virus Scan 8sussPaul Gunston21 Mar '05 - 6:01 
Just a word of warning, I have been using SMTP for my applications to generate email notifications. Suddenly all by app's stopped being able to send mail.
 
This was about the same time we changed some of our mail servers so I assumed that this was what was killing this part of my app's and thought nothing further of it as I was tied up doing other stuff.
 
Checking another issue I noticed that McAfee Virus Scan 8 was blocking port 25 which is used by SMTP. Re-enabling port 25 has returned my email notifications.
 
The port 25 block is default behaviour when installing version 8.
QuestionProblem with Import?sussAnonymous30 Sep '04 - 12:19 
If VB doesn't recognise System.Web.Mail as a valid Import, go to Project -> Add Reference and add System.Web.dll.
 
Hope this helps Smile | :)
AnswerRe: Problem with Import?sussAnonymous14 Jul '05 - 2:49 
hi,I have an error message saying that I could not access the CDO.object while I tried to send SMTP mail using vb.net..Can someone help me,please???
Thank you very much....
GeneralUBoundmemberabuhun23 Feb '04 - 17:27 
Can someone explain in more detail the job of Ubound? In this code "if UBound(strArgs) < 3", what doesn 3 stand for? Bytes?
 
Also, are the refrences like "System.Web" a library? Is there something similar for receiving mail?
 
thanks a lot.
GeneralRe: UBoundsussAnonymous17 Dec '04 - 0:47 
Ubound is a basic vb command that tells you the size of an array.
In this example, strArgs is an array (its name is wrong. it should have been something like arrArgs)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 2 Oct 2002
Article Copyright 2002 by Chris Dufour
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid