# VBForums CodeBank > CodeBank - Visual Basic 6 and earlier >  Simple VB emailer

## moeur

Here is a class you can use to send email from VB.  I wrote it years ago, but have seen a few requests for info on emailing.
Here is an example of how to use the class

*Edit:*  Before using the class you'll have to add a refernce to MSWINSCK.OCX
Goto Project\References Browse to system32\MSWINSOCK.OCX

VB Code:
Option Explicit
 Private WithEvents SMTP As clsSMTP
 Private Sub Command1_Click()
 With SMTP
 'who is the email from?
 .Sender = "YoMama"
 'who is it going to?
 .Recipient = "whomever@whereever.net"
 'your SMTP server
 .SMTPhost = "smtp.myserver.com"
 'optional subject line
 .Subject = "SMTP test"
 'make connection to the server
 .OpenMail
 'did connection succeed?
 If Not .Connected Then Exit Sub
 'you can send as many lines as you want here
 .Send "Bill,"
 .Send "This is a test of your wonderful SMTP client!"
 'make sure you close or nothing will get sent
 .CloseMail
End With
 End Sub
 Private Sub Form_Load()
    Set SMTP = New clsSMTP
End Sub
  Private Sub SMTP_Error(Code As Integer, Message As String)
    Debug.Print "SMTP Error "; Code, Message
End Sub
 Private Sub SMTP_ServerResponse(Reply As Integer, Message As String)
    Debug.Print Reply, Message
End Sub
Pretty simple, Now here is the class

VB Code:
Option Explicit
 Private mvarConnected As Boolean
Private mvarRecipient As String
Private mvarSender As String
Private mvarSMTPhost As String
Private mvarSubject As String
 Private WithEvents Winsock As MSWinsockLib.Winsock
 Const OK = 250
Const Connection = 220
Const ReadyforData = 354
Const UserUnknown = 550
 Dim Reply As Integer
Dim Message As String
Dim MyName As String
Dim ErrMSg As String
 Event Error(Code As Integer, Message As String)
Event ServerResponse(Reply As Integer, Message As String)
 Private Function WaitFor(R As Integer) As Boolean
Dim A
    A = Timer + 3
    While Not Reply = R And A > Timer
    DoEvents
    Wend
    If A < Timer Then
        WaitFor = True
    Else
        WaitFor = False
    End If
    Reply = 0
End Function
 Public Property Let Subject(ByVal vData As String)
    mvarSubject = vData
End Property
 Public Property Get Subject() As String
    Subject = mvarSubject
End Property
 Public Property Let SMTPhost(ByVal vData As String)
    mvarSMTPhost = vData
End Property
 Public Property Get SMTPhost() As String
    SMTPhost = mvarSMTPhost
End Property
 Public Sub Send(Message As String)
 Winsock.SendData Message & vbCrLf
End Sub
 Public Property Let Sender(ByVal vData As String)
    mvarSender = vData
End Property
 Public Property Get Sender() As String
    Sender = mvarSender
End Property
 Public Property Let Recipient(ByVal vData As String)
    mvarRecipient = vData
End Property
 Public Property Get Recipient() As String
    Recipient = mvarRecipient
End Property
 Public Property Get Connected() As Boolean
    Connected = mvarConnected
End Property
 Public Sub OpenMail()
    Reply = 0
    'connect to SMTP server
    Winsock.Connect mvarSMTPhost, 25
    If WaitFor(Connection) Then
        GiveError
        Exit Sub
    End If
    'send hello and wait for OK
    Winsock.SendData "helo " & mvarSMTPhost & vbCrLf
    If WaitFor(OK) Then
        GiveError
        Winsock.Close
        Exit Sub
    End If
    'send sender's name
    MyName = WhoAmI
     If InStr(mvarSender, "@") = 0 Then
        Winsock.SendData "Mail From:<" & mvarSender & "@" & MyName & ">" & vbCrLf
    Else
        Winsock.SendData "Mail From:<" & mvarSender & ">" & vbCrLf
    End If
    If WaitFor(OK) Then
        GiveError
        Winsock.Close
        Exit Sub
    End If
    'send recipient
    Winsock.SendData "RCPT TO:<" & mvarRecipient & ">" & vbCrLf
    If WaitFor(OK) Then
        GiveError
        Winsock.Close
        Exit Sub
    End If
    'make ready for data
    Winsock.SendData "Data" & vbCrLf
    If WaitFor(ReadyforData) Then
        GiveError
        Winsock.Close
        Exit Sub
    End If
    'Send Date:
    Winsock.SendData "Date: " & Format(Date, " dd mmm yy ") & Time & vbCrLf
    'To:
    Winsock.SendData "TO:<" & mvarRecipient & ">" & vbCrLf
    'From:
    Winsock.SendData "From: <" & mvarSender & "@" & MyName & ">" & vbCrLf
    'Subject:
    If Not mvarSubject = "" Then Winsock.SendData "Subject:" & mvarSubject & vbCrLf
    mvarConnected = True
End Sub
 Private Function WhoAmI() As String
Dim X As Integer, Y As Integer
    X = InStr(Message, "Hello")
    Y = InStr(Message, "[")
    If X = 0 Or Y = 0 Then
        WhoAmI = Winsock.LocalIP
    Else
        X = X + 6
        Y = Y - 1 - X
        WhoAmI = Mid$(Message, X, Y)
    End If
End Function
 Public Sub CloseMail()
    Winsock.SendData "." & vbCrLf
    If WaitFor(OK) Then
        GiveError
        Exit Sub
    End If
    Winsock.SendData "QUIT"
    Winsock.Close
End Sub
 Private Sub GiveError()
 Dim Message As String
 Select Case Reply
 Case Is = 10061
  Message = "Can't Connect to " & mvarSMTPhost
 Case Is = 11001
  Message = mvarSMTPhost & " is not a valid name or address."
 Case Is = 550
  Message = "User " & mvarRecipient & " not known to server."
 Case Is = 0
  Message = "Timeout waiting for server response"
 Case Is = 500
  Message = "Server does not recognize a command sent."
 Case Is = 553
  Message = "Invalid recipient name"
 Case Is = 1
  Message = "You must set Host, Recipient and Sender before connecting"
 Case Else
  Message = "Mail tool error."
 End Select
  RaiseEvent Error(Reply, Message)
End Sub
 Private Sub Class_Initialize()
    Set Winsock = New MSWinsockLib.Winsock
End Sub
 Private Sub Winsock_DataArrival(ByVal bytesTotal As Long)
Dim X As String
    Winsock.GetData X
    Reply = Val(X)
    X = Trim$(Mid(X, 4))
    RaiseEvent ServerResponse(Reply, X)
    Message = X
End Sub
 Private Sub Winsock_Error(ByVal Number As Integer, Description As String, _
ByVal Scode As Long, ByVal Source As String, _
ByVal HelpFile As String, ByVal HelpContext As Long, _
CancelDisplay As Boolean)
    Reply = Number
End Sub

----------


## |2eM!x

nice job moeur

----------


## visualAd

Very nice. Another useful thing to add onto this class is to allow one to make an MIME encoded email enabling you to attach additional files to the message.

----------


## manavo11

Or maybe to authenticate the username and password that some SMTP servers require  :Smilie:

----------


## dglienna

Why am I getting an error here? I have the clsSMTP class named right, with a winsock control named Winsock on a form, with a button named Commannd1, so what is missing?


VB Code:
Private Sub Class_Initialize()
    Set Winsock = New MSWinsockLib.Winsock
End Sub




> Invalid use of NEW keyword


Thanks.

[Simple Send Email project]

----------


## moeur

Before using the class you'll have to add a refernce to MSWINSCK.OCX
Goto Project\References Browse to system32\MSWINSOCK.OCX

----------


## dglienna

I had it loaded as a component.  Thanks.
Now, though I'm getting a SMTP timeout error.
I'll try it again tomorrow.

Thanks.

----------


## Hack

One quick question:  In the WaitFor function, you have A declared as a Variant (because you didn't explicitly declare it as anything else)

Was that intentional?  Is a Variant required here?

----------


## moeur

A could be single if you wanted.

----------


## CliffPhilip

Just what the doctor ordered and can be used as is.  However, I found I am having problem with the return address.  If I use "YoMamma" or something else made up, it blows up in my face.  However, it I use my "real" address, it works perfectly.

BUT:

It adds "@127.0.0.1" after the address.  if the person tries to respond to it, they get an error message "553 Invalid address syntax".  Any way of getting rid of that last portion?

----------


## dglienna

That is your ISP trying to prevent spam. I have the same thing, even when I'm not using their smtp server.

----------


## moeur

> It adds "@127.0.0.1" after the address. if the person tries to respond to it, they get an error message "553 Invalid address syntax". Any way of getting rid of that last portion?


I changed the code in the OpenMail routine a little bit on 7/29.
VB Code:
'send sender's name
    MyName = WhoAmI
     If InStr(mvarSender, "@") = 0 Then
        Winsock.SendData "Mail From:<" & mvarSender & "@" & MyName & ">" & vbCrLf
    Else
        Winsock.SendData "Mail From:<" & mvarSender & ">" & vbCrLf
    End If
See if your code reflects this change.

----------


## CliffPhilip

> See if your code reflects this change.


Unfortunately it does.  I only pulled the code down a couple of days ago and it is using this latter section.

I can "live" with it, just prefer to have it cleaner.

----------


## moeur

I assume this is the .Sender address you're talking about.
put some Debug.prints in there somewhere to see what's going on.
what is mvarsender equal to and which line does it send?

----------


## dee-u

How could I use Yahoo in your class?

----------


## moeur

> How could I use Yahoo in your class?


if Yahoo requires username and password authentification, then it won't work unless we add something to handle that.  I could do that, but I'd need a server to test it on and mine doesn't require such things.

----------


## zubairkhan

Why i am getting error "Name conflicts with existing module, project or object library" when adding mswinsck.ocx file from prefrences.

----------


## moeur

Don't load the Winsock control into the toolbox.

----------


## CliffPhilip

> Don't load the Winsock control into the toolbox.


I don't see where I have the Winsock control in the toolbox.  I went to components and references and don't see the Winsock.  Other than that, where would I check?

----------


## moeur

This error happens if you try to load MSWINSCK.OCX twice either in references or components.

----------


## CliffPhilip

> This error happens if you try to load MSWINSCK.OCX twice either in references or components


Here is what I have loaded.  Please take a look at them.  I don't see where I have MSWINSCK.OCX loaded twice

*References*
VB for applications
VB runtime objects & procedures
VBobjects and procedures
MS DAO 3.6 object library
MS ActiveX Data Objectrs 2.5 library
MS Data binding collection

*Components*
MS ADO Data Control 6.0 (OLEDB)
MS Calendar Control 9.0
MS Comm Controll 6.0
MS Common dialog control 6.0 (SP3)
MS Data Grid Control 6.0 (OLEDB)
MS Flex grid control 6.0
MS Masked edit control 6.0
MS Multimedia control 6.0
MS Rich textbox control 6.0 (SP4)
MS Windows common controls 5.0 (SP2)
MS Windows common controls-2 (SP4)

*Designers*
Data Environment
Data Report
DHTML Page
Webclass

*Insertable Objects*
MS Calendar Control 9.0

I really appreciate the help
 :Alien Frog:

----------


## impClaw

Uhh, i get a strange errror

Userdefined type not defined

and vb selects: Set Winsock = New mswinsocklib.Winsock

----------


## moeur

I would start a new project, add the reference, and cut and past the code.

----------


## impClaw

well, i have to do it in this project, is that possible?

I could send the project...

Also what shall the winsock class be named?
EDIT: clsSMPT probable, im such a noob

EDIT: ok, i use vb 5.0, that might be a problem.... since i have to add the winsock as a object not a referance....

----------


## moeur

It's been a long time since I used VB5.  Try this prpject to see if it works.  Then you can incorporate it into your project.

----------


## impClaw

Everything works! exept... i get this error: 
[SMTP Error  0               Timeout waiting for server response]

And sometimes i get the [Wrong protecol or connection state for the requested transaction or request] error...

also, what shall the [ .SMTPhost ] be?

----------


## moeur

smtp host has to be a vaild smtp server.  People usually use their own ISP.  Often the ISP will require a valis return address too.

If you don't have an ISP you could try .SMTPhost = mail.flash.net

----------


## impClaw

still getting the same error

it breaks at the line
mvarWinsock.SendData "helo " & mvarSMTPhost & vbCrLf

----------


## moeur

You need an SMTP server that is going to cooperate.  Can't help you with that I just use my ISP.

----------


## impClaw

I searched for free SMTP stuff but found nothing

do you know how do use your ISP, since ive no idea what isp is and how to use my isp:s adress, if it has any..

----------


## Hack

ISP = Internet Service Provider.

You posted a question on this subject, which was the correct thing to do.  However, questions do not belong in the CodeBank, so, I moved your question to where is should be, and where it will receive the most attention, and that is the ClassicVB section.     :Smilie:

----------


## impClaw

Hmm, i fixed a SMTP server (smtp.gmail.com), still getting the same old error.

here is the info i got about the SMTP: 

smtp.gmail.com (use authentication)
Use Authentication: Yes
Use STARTTLS: Yes (some clients call this SSL)
Port: 465 or 587

----------


## LeonX

great program .... , but why it cannot be run twice

----------


## moeur

I have no problem running it twice, what error are you getting?

----------


## LeonX

the program not responding.

try to do this (in vb ide): 
1. run the program once (F5)
2. send a message
3. close the log form
4. close the mail form
5. run the program again (F5)
6. send another message
7. it's not responding

and i don't know why this happen?

----------


## moeur

What is the log form?
If you have altered the code I'll have to see it.

----------


## LeonX

no , i did not altered it at all.

i will explain to you again , i open your project with vb6 , then i run it by pressing F5 , frmmail show up (mail form) , then i click the "Send" command after all configuration needed all sets , then frmLog show up (log form) , after that i click the "Close" command, back to the mail form then i close the form and back to the IDE, and 1 cycle is completed.

then i do the same things again , but not responding after i click the "Send" command.

hope you understand what i mean this time.

----------


## moeur

what project are you opening that has a frmLog? One of mine?

----------


## LeonX

sorry , look like i on wrong forum , sorry moeur.
after i check the code again , i think it is not yours.

----------


## impClaw

moeur, could you show how to make SMTP acces if you need login and Password, since i cannot find any SMTP without password request, and my ISP dont provide that...

----------


## moeur

No, this is a much more complex topic.

----------


## Iron Skull

I wonder if this works i need it:


VB Code:
Do until send = 20
With SMTP
 .Sender = send
 .Recipient = "whomever@" & send & ".com"
 .SMTPhost = "smtp.myserver.com"
 .Subject = "SMTP test"
 .OpenMail
 If Not .Connected Then Exit Sub
 .Send "Bill,"
 .CloseMail
End With
send = send + 1
doevents
loop

will this send 20 emails to one person?

----------


## manavo11

> I wonder if this works i need it:
> 
> 
> VB Code:
> Do until send = 20
With SMTP
 .Sender = send
 .Recipient = "whomever@" & send & ".com"
 .SMTPhost = "smtp.myserver.com"
 .Subject = "SMTP test"
 .OpenMail
 If Not .Connected Then Exit Sub
 .Send "Bill,"
 .CloseMail
End With
send = send + 1
doevents
loop
> 
> will this send 20 emails to one person?


Why would you want to send the same email to the same person 20 times?

----------


## Iron Skull

Someone asked me to make a program that sends one email more often at once i dont know why

----------


## Iron Skull

were can i find the Dll?

----------


## manavo11

What dll?  :Ehh:

----------


## Iron Skull

i meen OCX i already found it  :Smilie:

----------


## CVMichael

Hi moeur, how can I send the e-mail in html format ?

I tried something like:


```
     .Send "<html><body>"
     .Send "Testing...<br>"
     .Send "</body></html>"
```

But that just sends as is, it does not convert to html on the receiving side...

----------


## moeur

> how can I send the e-mail in html format ?


I don't think this is part of the _Simple Mail Transfer Protocol_ but is instead something in the mail message that the client (like outlook) sees and knows the rest of the message is html.

I don't know what that is.  If I could see the entire message sent to outlook including all the header info the I could see it.

I check around...

----------


## moeur

try adding somthing like 
Content-Type: html/text
I played around a little but didn't get it quite right
add a line to the classes OpenMail method after the part where it sends the subject
VB Code:
Winsock.SendData "Content-Type: html/text" & vbCrLf
I'll play some more if I get time later.

----------


## moeur

I posted the final solution to this earlier, but for some reason my post was deleted.

Add this line to the OpenMail subroutine somewhere
VB Code:
Winsock.SendData "Content-Type: html/text; charset=ISO-8859-1" & vbCrLf

----------


## jouster

I tried this code , but i keep getting an error in the CloseMail sub.
Gives me an error about wrong connection status? Anyone seen this?

----------


## moeur

show me how you are using it.

----------


## mellts

Hi ,

i try sending using normal address it works(eg. 123@aaa.com) however if I use something like 123@192.168.2.99 I will receive an error . can you teach me how to send an email using IP address.

Thanks

----------


## ajaythacker

Hi,
I am not able to send mails to multiple recipients. If i send it to single recipeint then it works fine, but it fails everytime i try sending it to more then one recipient.

i need help pls.

----------


## kotinadh

> It's been a long time since I used VB5.  Try this prpject to see if it works.  Then you can incorporate it into your project.


Hi There,

I am new to this forum, I tried ur' code but unable to sending mails. I am getting the error like "runtime error 40020" and the position is  "If Not .Connected Then Exit Sub"

Best regards,
Kotinadh

----------

