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

by Anshoo Arora ON August 10, 2009 · Posted In All, QTP, VBScript · 34 comments

This article discusses 2 ways of sending e-mail from your Yahoo, Hotmail, Gmail, Live or AOL e-mail accounts using the ‘EmailSender’ 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
SendMail "myEmailID@AOL.com", "myPassword", "recipient@Gmail.com", _
        "", "Subject", "Hello, this is a test mail."
'HTML
SendMail "myEmailID@AOL.com", "myPassword", "recipient@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:

SendMailFromFile "myEmailID@AOL.com", "myPassword", "recipient@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:

SendMail "myEmailID@AOL.com", "myPassword", "recipient1@Gmail.com;recipient2@Yahoo.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.

Code: Class SendMail
Class EmailSender
 
'#region Public Variables

    Public Body  'Message body
    Public From  'Sender's EmailID

 
'#region Private Variables

    Private CDOMessage  'CDO.Message Object
    Private strFrom     'Sender's Email ID: XX@YY.COM
    
 
'#region Public Methods
    
    ' Purpose: Send Email Using CDO
    ' Args:
    '    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
    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

        Me.From = sEmailID
        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 CDOMessage
            .Subject = sSubject
            .From = sEmailID
            .To = sTo
            .CC = sCC
            '.BCC = sBCC  'BCC Property can be added as well
            
            '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 CDOMessage.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
            CDOMessage.Send  'Send Message
            
            If Err.Number <> 0 Then
                intStatus = micFail
                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
 
    ' Purpose: Loads BodyText from a Text File
    ' Args:
    '    sCompleteFilePath: Complete Path to the Text File (Eg: "C:\MyDocs\MyMail.txt")
    Public Property Let LoadBodyMessage( sCompleteFilePath ) 'ReadOnly Property LoadBodyMessage
        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 Property
 
 
'#region Private Gets

    ' Purpose: Readonly property configuration for SMTP Service'
    ' Return: Integer
    Private Property Get CDOSendUsing  'As Integer
        CDOSendUsing = 2    'Use SMTP Over The Network
        'CDOSendUsing = 1    'Use Local SMTP Service Pickup Directory
    End Property
 
    ' Purpose: Maximum time in seconds CDO will try to establish a connection
    ' Return: Integer
    Private Property Get CDOTimeout  'As Integer
        'CDOTimeout = 15    'Seconds
        CDOTimeout = 45    'Seconds
        'CDOTimeout = 75    'Seconds
    End Property
 
    ' Purpose: Type of Authentication to be used
    ' Return: Integer
    Private Property Get CDOAuthenticationType  'As Integer
        'CDOAuthenticationType = 0    'No Authentication
        CDOAuthenticationType = 1    'Basic Authentication
        'CDOAuthenticationType = 2    'NTML Authentication
    End Property
 
    ' Purpose: Server Port
    ' Return: Integer
    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
 
    ' Purpose: Name/IP of SMTP Server
    ' Return: Integer
    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
 
    ' 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
 
 
'#region Initialization and Termination
    
    Private Sub Class_Initialize()
        Set CDOMessage = CreateObject("CDO.Message")
    End Sub
 
    Private Sub Class_Terminate()
        Set CDOMessage = Nothing
    End Sub
 
End Class
Code: Function SendMail
' Purpose: Sends an Email Using CDO to a recipient
' Args:
'    sEmailID: Sender's Mail ID String
'    sPassword: Sender's Password String
'    sTo: Recipient's Mail ID String
'    sSubject: Subject String
'    sBody: Body Message String
Public Sub SendMail(EmailID, Password, Recipient, CC, Subject, Body)
    Dim oEmailSender : Set oEmailSender = New EmailSender
 
    With oEmailSender
        .Send EmailID, Password, Recipient, CC, Subject, Body
    End with 
End Sub
Code: Function SendMailFromFile
' Purpose: Sends an Email Using CDO to a recipient
' Args:
'    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
Public Sub SendMailFromFile(EmailID, Password, Recipient, CC, Subject, sCompleteFilePath)
    Dim oEmailSender : Set oEmailSender = New EmailSender
 
    With oEmailSender
        .LoadBodyMessage = sCompleteFilePath
        .Send EmailID, Password, Recipient, CC, Subject, ""
    End with 
End Sub

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

Subscribe to Relevant Codes (by Anshoo Arora)

Hello! We're always posting interesting articles on Relevant Codes. Why not subscribe so you don't miss out?

Leave a Comment

{ 34 comments… read them below or add one }

David B January 4, 2011 at 6:21 pm

Thanks for writing this. Seems to work nicely.

Reply

Anonymous October 18, 2010 at 7:45 am

Hi dis is mahesh

Reply

mahesh October 18, 2010 at 7:32 am

Hi dis is mahesh nice 2 meeting u

Reply

Ravi August 22, 2010 at 9:35 am

How to attach Excel File as attachment in this code

Reply

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

Ravi August 22, 2010 at 9:34 am

Kiran,

You should use EmailfromFile Function instead of E-Mail

Reply

Ravi August 22, 2010 at 9:19 am

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

Reply

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

Anshoo Arora August 3, 2010 at 9:44 am

Kiran,

What is the exact code that you used..?

Reply

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

Anshoo Arora July 30, 2010 at 8:49 am

Kiran,

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

Reply

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Polprav October 11, 2009 at 8:32 pm

Hello from Russia)

Reply

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

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

Anonymous October 18, 2010 at 7:33 am

Hi nice 2 meeting u

Reply

Previous post:

Next post: