Relevant Codes

A Test Development Resource for HP QuickTest Professional.

CDO: Send Email from Yahoo, Hotmail, Live, AOL or GMail

by Anshoo Arora on August 10, 2009

This article discusses 2 ways of sending e-mail from your Yahoo, Hotmail, Gmail, Live or AOL e-mail accounts using the ‘clsSendMail’ class:

  1. Calling the Method with the Body Message
  2. Retrieve body-messages from text files

This can be quite handy during regression cycles – you can use this code to send yourself an e-mail whenever a step in the test process fails. You can even keep a count of the number of times this procedure executes in your script and even stop your test if too many steps fail.

Calling the Method with the Body Message
The code snippets below shows the syntax to send an HTML and plain text e-mails:

'TEXT

'Call Email( Sender's_ID, Sender's_Password, Send_To, CC_To, Subject, Message )
Email "XYZ@AOL.com", "myPassword", "ABC@Gmail.com", _
        "", "Subject", "Hello, this is a test mail."
'HTML

'Call Email( Sender's_ID, Sender's_Password, Send_To, CC_To, Subject, Message )
Email "XYZ@AOL.com", "myPassword", "ABC@Gmail.com", "", _
        "Subject", "<h1>Hello</h1><p>Test Mail</p>"

Retrieve body-messages from text files
You can create a text file with the body message, and use the file path in the method to send the e-mail. Below is an example of an HTML body inserted into a text file:

'Call Email( Sender's_ID, Sender's_Password, Send_To, CC_To, Subject, Message )
Email "XYZ@AOL.com", "myPassword", "ABC@Gmail.com", "", _
        "Subject", "C:\MyTestMail.txt"
Sample Text File

Sample Text File

Similarly, mails can be sent to multiple recipients using “;” between Recipient’s emails. Example:

Email "Me@MeEmail.Com", "mePassword", "You@YouEmail.Com;Them@TheirEmail.Com", _
    "CC@YouCC.Com;CC@MeCC.Com", "Test Subject", "Test Message"

You can find the download links to this class towards the end of this post.


How its done:

'Public Class clsSendMail
Class clsSendMail
 
    Private oMessage    'CDO.Message Object
    Private strFrom     'Sender's Email ID: XX@YY.COM
    Public Body         'Body Text from Text File

    '—————————————————————————————————————————————  
    ' Name: Sub Email (Public)
    ' 
    ' Purpose: Send Email Using CDO
    ' 
    ' Parameters:
    '    sEmailID: Sender's Mail ID String
    '    sPassword: Sender's Password String
    '    sTo: Recipient's Mail ID String (Primary)
    '    sCC: Recipient's Mail ID String (CC)
    '    sSubject: Subject String
    '    sBody: Body Message String
    ' 
    ' Return: -
    '————————————————————————————————————————————— 
    Public Sub Send( sEMailID, sPassword, sTo, sCC, sSubject, sBody )
    '————————————————————————————————————————————— 
        Dim oRegExp     'RegEx Object
        Dim sDetails    'Report Details
        Dim intStatus   'Report Status
        Dim sStepName   'Report Step
        
        'Sender ID has Class scope
        Me.From = sEmailID
        'Message Body
        If sBody <> "" Then Me.Body = sBody
 
        intStatus = micPass
        sStepName = " Sent"
 
        Set oRegExp = New RegExp
        oRegExp.Global = True
        oRegExp.Pattern = "<\w>|<\w\w>|<\w\d>"
        Set oMatches = oRegExp.Execute( Me.Body )
 
        'Build Message
        With oMessage
            .Subject = sSubject
            .From = sEmailID
            .To = sTo
            .CC = sCC
            'BCC Property can be added as well:
            '.BCC = sBCC
            'If HTML Tags found, use .HTMLBody
            If oMatches.Count > 0 Then
                .HTMLBody = Me.Body
            Else
                .TextBody = Me.Body
            End If
        End With
 
        Set oMatches = Nothing
        Set oRegExp = Nothing
 
        With oMessage.Configuration.Fields
            'Sender's Mail ID
            .Item("http://schemas.microsoft.com/cdo/configuration/" &_
            "sendusername") = sEmailID
            'Sender's Password
            .Item("http://schemas.microsoft.com/cdo/configuration/" &_
            "sendpassword") = sPassword
            'Name/IP of SMTP Server
            .Item("http://schemas.microsoft.com/cdo/configuration/" &_
            "smtpserver") = cdoSMTPServer
            'Server Port
            .Item("http://schemas.microsoft.com/cdo/configuration/" &_
            "smtpserverport") = cdoOutgoingMailSMTP
            'Send Using: (1) Local SMTP Pickup Service (2) Use SMTP Over Network
            .Item("http://schemas.microsoft.com/cdo/configuration/" &_
            "sendusing") = cdoSendUsing
            'Authentication Used: (1) None (2) Basic (3) NTLM
            .Item("http://schemas.microsoft.com/cdo/configuration/" &_
            "smtpauthenticate") = cdoAuthenticationType
            'SMTP Server Requires SSL/STARTTLS: Boolean
            .Item("http://schemas.microsoft.com/cdo/configuration/" &_
            "smtpusessl") = cdoUseSSL
            'Maximum Time in Seconds CDO will try to Establish Connection
            .Item("http://schemas.microsoft.com/cdo/configuration/" &_
            "smtpconnectiontimeout") = cdoTimeout
            'Update Configuration Entries
            .Update
        End With
 
        'Report Details
        sDetails = "SMTP Server: " & cdoSMTPServer & vbLf
        sDetails = sDetails & "Sender: " & sEMailID & vbLf
        sDetails = sDetails & "Recipient: " & sTo & vbLf
        sDetails = sDetails & "Server Port: " & cdoOutgoingMailSMTP & vbLf
        sDetails = sDetails & "SSL Used: " & cdoUseSSL & vbLf
        sDetails = sDetails & "Authentication Type: " & cdoAuthenticationType & vbLf
        sDetails = sDetails & "SMTP Service Type: " & cdoSendUsing & vbLf & vbLf
        sDetails = sDetails & "Subject: " & sSubject & vbLf & vbLf
        sDetails = sDetails & "Body: " & sBody
 
        On Error Resume Next
            'Send Message
            oMessage.Send
            If Err.Number <> 0 Then
                intStatus = micWarning
                sStepName = " Not Sent"
                sDetails = sDetails & vbLf & "Error Description: " & Err.Description
            End If
        On Error Goto 0
 
        'If you're not using QTP, please disable the statement below:
        Reporter.ReportEvent intStatus, "EMail" & sStepName, sDetails
    End Sub
 
    '—————————————————————————————————————————————  
    ' Name: Sub LoadBodyMessage (Public)
    ' 
    ' Purpose: Loads BodyText from a Text File
    ' 
    ' Parameters:
    '    sCompleteFilePath: Complete Path to the Text File (Eg: "C:\MyDocs\MyMail.txt")
    ' 
    ' Return: -
    '—————————————————————————————————————————————  
    Public Sub LoadBodyMessage( sCompleteFilePath )
    '————————————————————————————————————————————— 
        CONST ForReading = 1 
        Dim oFSO, oFile
 
        Set oFSO = CreateObject( "Scripting.FileSystemObject" )
        Set oFile = oFSO.OpenTextFile( sCompleteFilePath, ForReading )
        Me.Body = oFile.ReadAll
        oFile.Close: Set oFile = Nothing
 
        Set oFSO = Nothing
    End Sub
 
    '—————————————————————————————————————————————  
    ' Name: Class_Initialize (Private)
    ' 
    ' Purpose: Binds to the CDO Object
    ' 
    ' Parameters: -
    ' 
    ' Return: -
    '—————————————————————————————————————————————  
    Private Sub Class_Initialize
    '—————————————————————————————————————————————  
        Set oMessage = CreateObject( "CDO.Message" )
    End Sub
 
    '—————————————————————————————————————————————  
    ' Name: Class_Initialize (Private)
    ' 
    ' Purpose: Release the CDO Object
    ' 
    ' Parameters: -
    ' 
    ' Return: -
    '—————————————————————————————————————————————     
    Private Sub Class_Terminate
    '————————————————————————————————————————————— 
        Set oMessage = Nothing
    End Sub
 
    '—————————————————————————————————————
    ' Name: Property cdoSendUsing (Private)
    ' 
    ' Purpose: Readonly property configuration for SMTP Service
    '—————————————————————————————————————
    Private Property Get cdoSendUsing  'As Integer
    '—————————————————————————————————————    
        cdoSendUsing = 2    'Use SMTP Over The Network
        'cdoSendUsing = 1    'Use Local SMTP Service Pickup Directory
    End Property
 
    '—————————————————————————————————————
    ' Name: Property cdoTimeout (Private)
    ' 
    ' Purpose: Maximum time in seconds CDO will try to establish a connection
    '—————————————————————————————————————
    Private Property Get cdoTimeout  'As Integer
    '—————————————————————————————————————    
        'cdoTimeout = 15    'Seconds
        cdoTimeout = 45    'Seconds
        'cdoTimeout = 75    'Seconds
    End Property
 
    '—————————————————————————————————————
    ' Name: Property cdoAuthenticationType (Private)
    ' 
    ' Purpose: Type of Authentication to be used
    '—————————————————————————————————————    
    Private Property Get cdoAuthenticationType  'As Integer
    '—————————————————————————————————————    
        'cdoAuthenticationType = 0    'No Authentication
        cdoAuthenticationType = 1    'Basic Authentication
        'cdoAuthenticationType = 2    'NTML Authentication
    End Property
 
    '—————————————————————————————————————
    ' Name: Property cdoOutgoingMailSMTP (Private)
    ' 
    ' Purpose: Server Port
    '—————————————————————————————————————    
    Private Property Get cdoOutgoingMailSMTP  'As Integer
    '—————————————————————————————————————    
        If InStr(1, Lcase(Me.From), "@gmail") <> 0 Then
            cdoOutgoingMailSMTP = 465
        ElseIf InStr(1, LCase(Me.From), "@aol") <> 0 Then
            cdoOutgoingMailSMTP = 587
        Else
            cdoOutgoingMailSMTP = 25
        End If
    End Property
 
    '—————————————————————————————————————
    ' Name: Property cdoSMTPServer (Private)
    ' 
    ' Purpose: Name/IP of SMTP Server
    '—————————————————————————————————————    
    Private Property Get cdoSMTPServer  'As String
    '—————————————————————————————————————    
        If InStr(1, LCase(Me.From), "@yahoo") <> 0 Then
            cdoSMTPServer = "smtp.mail.yahoo.com"
        ElseIf InStr(1, LCase(Me.From), "@gmail") <> 0 Then
            cdoSMTPServer = "smtp.gmail.com"
        ElseIf InStr(1, LCase(Me.From), "@hotmail") <> 0 Or _
               InStr(1, LCase(Me.From), "@live") <> 0 Then
            cdoSMTPServer = "smtp.live.com"
        ElseIf InStr(1, LCase(Me.From), "@aol") <> 0 Then
            cdoSMTPServer = "smtp.aol.com"
        End If    
    End Property
 
    '—————————————————————————————————————
    ' Name: Property cdoUseSSL (Private)
    ' 
    ' Purpose: Setting for SMTP Server's use of SSL (Boolean)
    '—————————————————————————————————————        
    Private Property Get cdoUseSSL  'As Boolean
    '—————————————————————————————————————    
        cdoUseSSL = True
        If InStr(1, LCase(Me.From), "@aol") <> 0 Then
            cdoUseSSL = False
        End If
    End Property
 
    '—————————————————————————————————————
    ' Name: Property From (Public)
    ' 
    ' Purpose: Sender's Email ID
    '—————————————————————————————————————
    Public Property Let From( ByVal Val )
           strFrom = Val
    End Property
    Public Property Get From 'As String
           From = strFrom
    End Property
 
End Class
 
'—————————————————————————————————————————————  
' Name: Sub Email (Public)
' 
' Purpose: Sends an Email Using CDO to a recipient
' 
' Parameters:
'    sEmailID: Sender's Mail ID String
'    sPassword: Sender's Password String
'    sTo: Recipient's Mail ID String
'    sSubject: Subject String
'    sBody: Body Message String
' 
' Return: -
'————————————————————————————————————————————— 
Public Function Email( EmailID, Password, Recipient, CC, Subject, Body )
'————————————————————————————————————————————— 
    Set Email = New clsSendMail
    With Email
        .Send EmailID, Password, Recipient, CC, Subject, Body
    End with 
End Function
 
'—————————————————————————————————————————————  
' Name: Sub EmailFromFile (Public)
' 
' Purpose: Sends an Email Using CDO to a recipient
' 
' Parameters:
'    sEmailID: Sender's Mail ID String
'    sPassword: Sender's Password String
'    sTo: Recipient's Mail ID String
'    sSubject: Subject String
'    sCompleteFilePath: Text File containing the Body Message
' 
' Return: -
'————————————————————————————————————————————— 
Public Function EmailFromFile( EmailID, Password, Recipient, CC, Subject, sCompleteFilePath )
'————————————————————————————————————————————— 
    Set EmailFromFile = New clsSendMail
    With EmailFromFile
        .LoadBodyMessage sCompleteFilePath
        .Send EmailID, Password, Recipient, CC, Subject, ""
    End with 
End Function

You can use this code as a .VBS file, but, please remember to remove/comment the Reporter.ReportEvent statement on Line 113.

Download for QTP
Download for executing as .VBS

If you have any questions, please ask them in the comments section. If your query is confidential, please use the Contact Form to send me an e-mail instead.

{ 30 comments… read them below or add one }

1 Anonymous August 11, 2009 at 9:07 pm

Hi
Anshoo this is good Work
Your code is well documented

It would be nice if you could explain me the concept of keyword “me” like me.Form

Reply

2 Anshoo Arora August 11, 2009 at 9:13 pm

The keyword ‘Me’ makes it easier for the reader to infer that we’re working with an instance of a class, or with a variable that is currently executing and is part of the class. Moreover, it can be used to differentiate between a variable of a class vs a variable that has been passed by a class method.

You can also see this article for more information: http://msdn.microsoft.com/en-us/library/7e58sbke%28VS.71%29.aspx

Reply

3 Polprav October 11, 2009 at 8:32 pm

Hello from Russia)

Reply

4 Mahesh Upadhyay November 16, 2009 at 8:41 am

Hello Anshoo,

For me it shows ,mail can not be sent, i am using this code on virtual box for QTP, it shows me warning at last i.e. email not sent in object column and in description it shows
SMTP Server: smtp.gmail.com
Sender: upadhyay40@gmail.com
Recipient: maheshupadhyay.testing@gmail.com
Server Port: 465
SSL Used: True
Authentication Type: 1
SMTP Service Type: 2

Subject: hi

Body: i am mahesh
Error Description: The transport failed to connect to the server.

Reply

5 Anshoo Arora November 16, 2009 at 6:53 pm

Hi again Mahesh,

I tried executing it on my home computer and the class works perfectly.. As for the error that you have received, you may be able to find the resolution in one of the below 2 threads:

http://forums.asp.net/t/993918.aspx
http://www.systemwebmail.com/faq/4.3.9.aspx

I hope this helps. If you have any further questions, please post here and we’ll try to solve them. Thanks :)

Reply

6 Mahesh Upadhyay November 16, 2009 at 9:11 am

Hi Anshoo,

Can you pleas elet me explain what i need to do for remove error

Thanks

Reply

7 Anshoo Arora November 16, 2009 at 10:16 am

Hi Mahesh,

I will test this code tonight to make sure nothing has changed. The last time I used it with both GMail and Yahoo, everything worked fine. Also, could you please share with me the code you used with the password field as null? Thanks :)

Reply

8 Mahesh Upadhyay November 17, 2009 at 1:08 am

Hi Anshoo,

I used the same code that u given, i call function like

Email “upadhyay40@gmail.com”, “123456″, “dhavalmotghare@gmail.com”,”dhavalmotghare@gmail.com”, “hi”, “i am mahesh”

and create two functions 1st for

Public Function Email( EmailID, Password, Recipient, CC, Subject, Body )
'—————————————————————————————————————————————
    Set Email = New clsSendMail

    With Email
       .Send EmailID, Password, Recipient, CC, Subject, Body
    End with
End Function

and second function contains whole class like

Class clsSendMail

    Private oMessage    'CDO.Message Object
    Private strFrom     'Sender's Email ID: XX@YY.COM
    Public Body         'Body Text from Text File

   ** MESSAGE TRUNCATED DUE TO SIZE **

    '�������������������������������������
    ' Name: Property From (Public)
    '
    ' Purpose: Sender's Email ID
    '�������������������������������������
    Public Property Let From( ByVal Val )
           strFrom = Val
    End Property
    Public Property Get From 'As String
           From = strFrom
    End Property

End Class

Is this a write process that i follow

Please let me know, hoping for your cooperation

Reply

9 Anshoo Arora November 17, 2009 at 9:57 am

The process you are following is correct. I think its one of the settings/access on your system that needs to be turned on for you to be able to send that e-mail. I have tested this code on several PCs at work after I read your reply just to make sure it works correctly.. and it does. I think you might have to contact one of your admins to be sure what is causing this behavior.

Reply

10 Mahesh Upadhyay November 17, 2009 at 3:45 am

Please let me know if i need little bit more settings to be set on virtual machine for sending mail

Thanks

Reply

11 Anshoo Arora November 17, 2009 at 10:04 am

I got an email this morning, and I think that email describes a similar problem, but without any errors. The only issue there is that the email is not received. I’m not sure what’s causing this since its working correctly for me. Hmm. I am going to do a little bit of research and update this thread.

Reply

12 Anshoo Arora November 18, 2009 at 12:00 am

Mahesh, are Mail Forwarding/POP settings under your Gmail account correct? Please see this topic at Google for details.

Reply

13 Mahesh Upadhyay November 18, 2009 at 12:35 am

Hi Anshoo,

I make it my Forwording/POP setting, but still it is not forwording my mail, please take in consider hoping for your cooperation

Thanks
Mahesh

Reply

14 Mahesh Upadhyay November 18, 2009 at 12:54 am

Hi Anshoo,

I think it worked on virtual machine, so might be it caused a problem, please correct me if i am wrong, but i got whole net connections as well as lan connection.

Thanks
Mahesh

Reply

15 Anshoo Arora November 18, 2009 at 1:54 pm

Hi Mahesh,

I’m not quite sure what caused this problem, but it should work on any machine with internet + the Gmail’s POP/Forwarding options set correctly. I had an email regarding a similar issue just at about the same time you posted, and their problem was resolved once all the settings for POP were enabled.

:)

Reply

16 Mahesh Upadhyay November 20, 2009 at 1:32 am

Hi Anshoo,

Still i am unsuccessfull, please take in consider and help me out.

Thanks.
Mahesh

Reply

17 Anshoo Arora November 20, 2009 at 11:58 am

Mahesh, have you tried executing this script on your home PC? If it works there, and doesn’t work at your office, then you might need to speak with your network admins to find the cause of this behavior. Can you access Gmail from your office, or is it blocked?

Reply

18 Mahesh Upadhyay November 21, 2009 at 2:09 am

Hi Anshoo,

I havent tried it at home, but at my office Gmail is allowed, but even i dont know what hapeen that this code is not working.

Thanks
Mahesh

Reply

19 Anshoo Arora November 21, 2009 at 2:28 pm

I have a feeling that you do not have CDONTS installed on your system. Can you try to install this and see if it starts working. I have Outlook on all the systems I use, with which CDONTS comes as default..

Reply

20 Mahesh Upadhyay November 23, 2009 at 12:05 am

Hi Anshoo,

I download CDONTS but it wont installed because it shows warning API can not be installed with microsoft outlook.

Please let me know if anything that i can do, thanks

Mahesh

Reply

21 Anshoo Arora November 24, 2009 at 7:46 pm

Hi Mahesh,

Please check your e-mail.

As for installing CDONTS, you should have been able to install it. I’m not sure why this error occurred. I am still doing some research on this, but because I have very little time these days, its been a little slow.

Don’t lose hope though. We’ll resolve it soon.

Reply

22 Mahesh Upadhyay November 25, 2009 at 12:29 am

Hi anshoo,

Thanks for your kind cooperation, i hope we’ll resolve it.

Thanks
Mahesh

Reply

23 kiran July 30, 2010 at 5:33 am

I used the above code and ran it and i received a mail but the subject in the mail is displayed as

C:\Test Mail.txt

instead of the actual content in the text file

Reply

24 Anshoo Arora July 30, 2010 at 8:49 am

Kiran,

Can you please share the exact line of code that you used?

Reply

25 Kiran August 2, 2010 at 3:20 am

Hi Anshoo,

Instead of writing the message body i wrote the subject.

When i ran the code which is on the post i received the mail but the Description or the Message Body (content of themail) displayed as C:\Test Mail.txt. This is the path of the text file. The text file contains the message body.

Reply

26 Anshoo Arora August 3, 2010 at 9:44 am

Kiran,

What is the exact code that you used..?

Reply

27 Ravi August 22, 2010 at 9:19 am

I’m also receving the same problem as Kiran is facing

Reply

28 Ravi August 22, 2010 at 9:34 am

Kiran,

You should use EmailfromFile Function instead of E-Mail

Reply

29 Ravi August 22, 2010 at 9:35 am

How to attach Excel File as attachment in this code

Reply

30 Anshoo Arora August 22, 2010 at 4:47 pm

Ravi,

You will have to modify the code a bit to include attachments. I created the code purely for e-mailing purposes, but creating an additional field for attachment is going to be fairly easy. Please see here.

Reply

Leave a Comment

Previous post:

Next post: