Link to home
Create AccountLog in
Avatar of M A S
M A SFlag for United States of America

asked on

Loop through query and send email everyday at 12AM

I used this code to loop through a query and send email but I get this error.
Is there anyone can assist me?
User generated image

Private Sub Form_Timer()
Dim MyDb As DAO.Database
Dim rsEmail As DAO.Recordset
Dim sToName As String
Dim sSubject As String
Dim sMessageBody As String
 
Set MyDb = CurrentDb()
Set rsEmail = MyDb.OpenRecordset("passport_expiry_15days", dbOpenSnapshot)
 
With rsEmail
        .MoveFirst
        Do Until rsEmail.EOF
            If IsNull(.Fields(12)) = False Then
            Set email = CreateObject("CDO.Message")
email.Subject = "Passport Expiry Notification 15 days"
email.From = "HR System <hrms@domain.com>"
email.To = .Fields(12)
email.TextBody = "Your passport will expire on " & .Fields(4)
email.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "admin"
email.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "admin"
email.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = "hrms@domain.com"
email.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.domain.com"
email.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
email.Configuration.Fields.Update
email.Send
Set email = Nothing
 MsgBox (.Fields(12))
            End If
            .MoveNext
        Loop
End With
Set MyDb = Nothing
Set rsEmail = Nothing
End Sub

Open in new window

Avatar of mbizup
mbizup
Flag of Kazakhstan image

Try determining whether this is failing on a particular setting or on any/all, by moving the Update (or temporarily commenting out some of the items), so that you are beginning with one setting and progressively adding more.
If you comment the statement, does the code work?
Avatar of M A S

ASKER

-->If you comment the statement, does the code work?
No
@mbizup
I tested line by line with no luck
ASKER CERTIFIED SOLUTION
Avatar of Mlanda T
Mlanda T
Flag of South Africa image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of M A S

ASKER

Yes this did the trick. Thank you MlandaT.