Error Sending automation mail after registration using lotus script - lotus-notes

Question:
1. My question why after registration of an user still not listed in domino directory?
Case:
I am using xPages form call lotus script agent.
All my script is using lotus script to register an user.
After Complete register an email, need to send automation notification mail to user as welcome mail.
when i complete registration, i want to send mail, it give me an error message:
1.unable to deliver message 'ChunWH#devsvr1.pcs.com.my'
2.User 'ChunWH#devsvr1.pcs.com.my' not listed in Domino Directory
Register user Agent
Option Public
Option Declare
Sub Initialize
On Error GoTo ErrorHandler
Dim s As New NotesSession, db As NotesDatabase, a As NotesAgent
Dim doc As NotesDocument
Set db = s.Currentdatabase
Set a = s.Currentagent
Set doc = s.Documentcontext ' uidoc
Dim maildoc As NotesDocument, body As NotesMIMEEntity
Dim stream As NotesStream
Dim groups
groups = Null
groups = group(groups,"Everyone")
Dim certid As String ' full path of cert id
Dim certpasswd As String
Dim OU As String
Dim lastname As String
Dim firstname As String
Dim middleinit As String
Dim usrIdpath As String
Dim mailsvr As String
Dim mailfile As String
Dim userpasswd As String
Dim internetpathLength As String
Dim internetpath As String
Dim remapuserID As String
Dim depvw As NotesView, depdoc As NotesDocument
Set depvw = db.Getview("Department sort by dept")
Set depdoc = depvw.Getdocumentbykey(doc.Dept(0), True)
If Not depdoc Is Nothing Then
certid = depdoc.IdPath(0)
certpasswd = depdoc.IdPassword(0)
OU = ""
lastname= doc.Name(0)
firstname = ""
middleinit = ""
usrIdpath = depdoc.DptIdStor(0) +doc.SelectMail(0)+ ".id"
' remove "." replace with empty and remove the empty space
remapuserID = remapChr(doc.SelectMail(0)) ' this is remapuserID
mailsvr = depdoc.MailSvr(0) ' mail svr
' Mail file name also cannot have . in between for example, mail/test1.apple, reason window not understand it
mailfile = depdoc.MailLocation(0)+ remapuserID ' Mail\Person
userpasswd= depdoc.UserPassword(0)
internetpath = doc.SelectMail(0)+depdoc.InternetPath(0) ' mail address
internetpathLength = Len(depdoc.InternetPath(0)) ' not used
End If
Dim reg As New NotesRegistration
Dim dt As Variant
dt = DateNumber(Year(Today)+1, Month(Today), Day(Today))
reg.RegistrationServer = mailsvr
reg.CreateMailDb = True '
reg.CertifierIDFile = certid
reg.Expiration = dt
reg.IDType = ID_HIERARCHICAL
reg.MinPasswordLength = 1
reg.IsNorthAmerican = True
reg.OrgUnit = OU
reg.RegistrationLog = "log.nsf"
reg.UpdateAddressBook = True
reg.Storeidinaddressbook = false
reg.MailInternetAddress = internetpath
reg.Shortname=doc.SelectMail(0)
reg.Mailowneraccess =2
reg.Mailcreateftindex=True
reg.Mailaclmanager ="LocalDomainAdmins"
reg.Grouplist=groups
Call reg.RegisterNewUser(lastname, _
usridpath, _
mailsvr, _
firstname, _
middleInit, _
certpasswd, _
"", _
"", _
mailfile, _
"", _
userpasswd, _
NOTES_DESKTOP_CLIENT)
Dim acl As NotesACL
Dim aclEntry As NotesACLEntry
Dim dbUser As NotesDatabase
Set dbUser = New NotesDatabase(mailsvr,mailfile) ' mail/person.nsf
Set acl = dbUser.aCL
Set aclEntry = acl.Getentry( "LocalDomainAdmins" )
If Not (aclEntry Is Nothing) Then
aclEntry.UserType = ACLTYPE_PERSON_GROUP
Call acl.Save()
End if
' call name nsf and open for edit for forcing user must change password first time
Dim ndb As NotesDatabase
Dim viwUser As NotesView
Dim docUser As NotesDocument
Set ndb = New NotesDatabase( mailsvr, "names.nsf" )
Set viwUser = ndb.GetView("People by Email")
Set docUser = viwUser.GetDocumentByKey(doc.SelectMail(0),True)
Call docUser.ReplaceItemValue( "HTTPPasswordForceChange" , "1" )
Print "Force user change password is updated"
Call docUser.Save( True, True, True )
Print "Please wait ...... Registration in progress"
Call doc.Replaceitemvalue("S_Process", "Pending")
Call doc.Save(True, False)
Dim agt As NotesAgent
Set agt=db.getagent("(Welcome Mail)")
Call agt.Runonserver()
EndOfRoutine:
Exit Sub 'or exit function
ErrorHandler:
Print Err & ", " & Error & " in line " & Erl
Resume EndOfRoutine
End Sub
Function remapChr (oldString)
' to replace all special character with a empty space after that trim to remove all special character in system
Dim oldChr, newChr, newString As String
oldChr = {! "" # $ % & ' ( ) * + , - . / : ; = > ? # [ \ ] ^ _}
newChr = " {"
oldChr = Split(oldChr, " ")
newChr = Split(newChr, " ")
newString = Trim(Replace(LCase(oldString), oldChr, newChr))
remapChr = newString
End Function
Function group(groupArr, newReason$)
If IsArray(groupArr) Then
If groupArr(0) = "" Then
groupArr(0) = newReason
Else
Dim counter%
counter = UBound(groupArr) + 1
ReDim Preserve groupArr(counter)
groupArr(counter) = newReason
End If
group = groupArr
Else
Dim tempgroupArr() As String
ReDim tempgroupArr(0)
tempgroupArr(0) = newReason
group = tempgroupArr
End If
End Function
Sending mail Agent
Sub Initialize
On Error GoTo ErrorHandler
Print "Welcome Mail Agent started..."
' This agent is a sub agent for register user, which let register agent call
Dim s As New NotesSession, db As NotesDatabase, a As NotesAgent
Dim doc As NotesDocument
Set db = s.Currentdatabase
Set a = s.Currentagent
Set doc = s.Documentcontext ' uidoc
Dim maildoc As NotesDocument, body As NotesMIMEEntity
Dim stream As NotesStream
Dim receiver$
Dim tmpallve As NotesViewEntry
Dim viwUser As NotesView
Dim viwVe As NotesViewEntry
Dim viwVc As NotesViewEntryCollection
Dim docUser As NotesDocument
Set viwUser = db.GetView("(Request sort by S_Process)")
'Set docUser = viwUser.GetDocumentByKey("Pending",True)
Set viwVc = viwUser.Allentries
If viwVc.Count = 0 Then
Print "No item found in this list"
Exit Sub
End If
Set viwVe = viwVc.Getfirstentry()
Do While Not viwVe Is Nothing ' loop to all entry
Set docUser = viwVe.Document
receiver$ = docUser.SelectMail(0) + "#devsvr1.pcs.com.my"
' send mail
Set maildoc = db.Createdocument()
Call maildoc.Replaceitemvalue("Form", "Memo")
Call maildoc.Replaceitemvalue("Subject", "Welcome")
Call maildoc.Replaceitemvalue("SendTo", receiver)
Set body = maildoc.Createmimeentity
s.Convertmime = False
Set stream = s.Createstream()
stream.Writetext(|<html><body>|)
stream.Writetext(|<p>Your application for registration ....</p>|)
stream.Writetext(|<p>Welcome. Pleaase....</p>|)
stream.Writetext(|<p><em>(No signature requried on this computer generated document)</em></p>|)
stream.Writetext(|<p>*** This is a system generated email. | + _
|Please do not reply to this email. ***</p>|)
Call stream.Writetext(|</body></html>|)
Call body.Setcontentfromtext(stream, "text/html;charset=UTF-8", 1725)
Call maildoc.Send(False)
s.Convertmime = True
Call docUser.Replaceitemvalue("S_Process", "Processed")
Call docUser.Save(True, False)
Set tmpallve = viwVc.Getnextentry(viwVe)
Set viwVe = tmpallve
Loop
Print "Welcome Mail Agent finished..."
EndOfRoutine:
Exit Sub 'or exit function
ErrorHandler:
Print Err & ", " & Error & " in line " & Erl
Resume EndOfRoutine
End Sub
new update of image on 25/09/2017
(after set config router_debug=3 set config DebugRouterLookup=3 )
i try send manually will be fine...but using code directly send after registration will be fail. Not only that, i also try on sleep(2) , wait 2 second just send mail..it seem like my thought of not directly create mail account mail also not valid..not sure which part is wrong?

I suspect that your issue is one of time and caching. The Domino server maintains a Name Lookup Cache that only gets refreshed, well, occasionally (I have never figured out how occasionally that is but 5-10 minutes generally does the trick). This affects both the email functions and the web login functions. What I have done with my registration systems is have the agent that does the ID creation leave a document in it database that is in the status "Pending welcome email". Then another agent finds those docs and if they are more then 15 minutes old it attempts the email. if the email goes through then the status is changed to "Complete".
Note, you can reset the cache with the console command show nlcache reset and that almost always results in the user being able to get mail and login from a browser. But I have not been able to get that to work from a scheduled agent run on the server or a web agent.

Can you take a look at the Person Document? See if that address is properly registered on the document.
You may also try to enable router_debug=3 and DebugRouterLookUp=3 and we may see where did it try to lookup the address.

Related

How can I decide whether to save or not save an email via IBM Notes?

UPDATE 28/03/2022:
I've found a solution, that works for me fine. The code below is now working. The email is only saved/not saved when it is sent immediatly.
My (old) problem was:
I want to use the following code to send an email via IBM Notes. Everything works fine, but I can't figure out how to NOT save the email in the folder "sent".
I've tried already to put the line
.PostedDate = Now()
at the "objBackendDocument"-object, and tried to clear the value, because I've read in some posts, that this maybe a criteria for IBM Notes to save an email in the folder "sent". But it didn't work.
If I'm using an alternative mailfile it doesn't save my emails at all. If I use my standard mailfile, it saves every email ignoring "blnSaveEMail".
I would like to not save the email, because I want to send automated emails with attachements, which are already on the users pc (saving storage and avoiding copies of copies).
Another idea could be to strip the attachements from the recent sent email, but this is at the moment to difficult for me. Because I'm still trying to understand how the API of IBM Notes works. :)
'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
'+
'+ EMail_by_Notes
'+
'+ API: Lotus Notes COM/OLE
'+ Parameter "varRecipients": Requires a VARIANT or an array (VARIANT) of verified email-adresses
'+ Parameter "strSubject": Requires a STRING as the title of the email
'+ Paramater "strMessage": Requires as STRING as the content of the email
'+ Parameter "varCopy" optional: VARIANT or an array (VARIANT) of verified email-adresses
'+ Parameter "varBlindCopy" optional: VARIANT or an array (VARIANT) of verified email-adresses
'+ Parameter "varAttachements" optional: VARIANT or an array (VARIANT) of filepath(s)
'+ Parameter "blnSendImmediately" optional: BOOLEAN
'+ Parameter "blnSaveEMail" optional: BOOLEAN
'+ Parameter "strAlternative_Mailfile" optional: STRING, contains the filename of the alternative mailfile
'+
'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Public Function EMail_by_Notes( _
varRecipients As Variant, _
strSubject As String, _
strMessage As String, _
Optional varCopy As Variant = "", _
Optional varBlindCopy As Variant = "", _
Optional varAttachements As Variant, _
Optional blnSendImmediately As Boolean = True, _
Optional blnSaveEMail As Boolean = False, _
Optional strAlternative_Mailfile As String = "" _
) As Boolean
Dim objNotesSession As Object
Dim objNotesWorkspace As Object
Dim objNotesDatabase As Object
Dim objBackendDocument As Object
Dim objFrontendDocument As Object
Dim objRecipients As Object
Dim objCopy As Object
Dim objBlindCopy As Object
Dim objSubject As Object
Dim objMessage As Object
Dim objEmbedded As Object
Dim objAttachement As Object
Dim objProfileDoc As Object
Dim strMailServer As String
Dim strMailFile As String
Dim strFilepath As String
Dim strSignature As String
Dim lngIndex As Long
'Starts Notes Session
Set objNotesSession = CreateObject("Notes.NotesSession")
'Locate the mailserver
strMailServer = objNotesSession.GetEnvironmentString("MailServer", True)
'Check for an alternative mailfile (in case you have a second account)
If VBA.Len(strAlternative_Mailfile) = 0 Then
'Uses the standard account
strMailFile = objNotesSession.GetEnvironmentString("MailFile", True)
Else
'Uses an alternative mailfile, if the filename is wrong, it uses the standard account
'Unfortunately there is no error message
strMailFile = "mail/" & strAlternative_Mailfile
End If
'Connect to the database
Set objNotesDatabase = objNotesSession.GETDATABASE(strMailServer, strMailFile)
'If your constructed path (variable strMailFile) is wrong or the database cannot be accessed
'then this line will make sure to fallback to the mailfile configured in your location document in Notes Client.
If Not objNotesDatabase.IsOpen Then objNotesDatabase.OPENMAIL
If blnSendImmediately = True Then
Set objProfileDoc = objNotesDatabase.GetProfileDocument("CalendarProfile")
End If
'Create a Notes document in the backend
Set objBackendDocument = objNotesDatabase.CREATEDOCUMENT
With objBackendDocument
'Fill in the contents
Set objRecipients = .APPENDITEMVALUE("SendTo", varRecipients)
Set objCopy = .APPENDITEMVALUE("CopyTo", varCopy)
Set objBlindCopy = .APPENDITEMVALUE("BlindCopyTo", varBlindCopy)
Set objSubject = .APPENDITEMVALUE("Subject", strSubject)
If blnSendImmediately = True Then
Set objMessage = .CreateRichTextItem("body")
'Adds the user's RTF-signature from Lotus Notes
With objMessage
.appendText strMessage & VBA.vbCrLf & VBA.vbCrLf
.appendrtitem objProfileDoc.GetfirstItem("Signature_Rich")
End With
End If
'Attach the file(s)
If VBA.IsMissing(varAttachements) = False Then
If VBA.IsArray(varAttachements) = True Then
For lngIndex = LBound(varAttachements) To UBound(varAttachements)
strFilepath = varAttachements(lngIndex)
If strFilepath <> "" And VBA.Dir(strFilepath) <> "" Then
Set objAttachement = .CreateRichTextItem("Attachment" & lngIndex)
Set objEmbedded = _
objAttachement.EMBEDOBJECT(1454, "", strFilepath, "Attachment" & lngIndex)
End If
Next
ElseIf VBA.Len(varAttachements) > 0 And VBA.Dir(varAttachements) <> "" Then
Set objAttachement = .CreateRichTextItem("Attachment1")
Set objEmbedded = _
objAttachement.EMBEDOBJECT(1454, "", varAttachements, "Attachment1")
End If
End If
'Save or do not save the email in the folder "sent" before sending the email immediately
If blnSendImmediately = True Then .SAVEMESSAGEONSEND = blnSaveEMail
End With
'Check, whether the email shall be sent immediately or not
If blnSendImmediately = False Then
'Load Notes Workspace
Set objNotesWorkspace = CreateObject("Notes.NotesUIWorkspace")
'Get the backend document in the foreground
'Also in case, the email shall be edited before sending it
Set objFrontendDocument = objNotesWorkspace.EDITDOCUMENT(True, objBackendDocument)
With objFrontendDocument
'Fill in the emails message
'Important if you use a signature in IBM Notes
.GoToField "Body"
.InsertText strMessage
End With
Else
With objBackendDocument
.Send False
End With
End If
EMail_by_Notes = True
End Function
This is what you are doing :
building doc1
working on doc1.uidocument
sending doc1.uidocument.document (=doc2)
SaveMessageOnSend applies on doc1, not on uidoc nor doc2.
Moreover, it does NOT make sense to open in the ui, and send in the back.
You should do all in the background (look up for user signature in its profile).
If you want to interact with the user, open in the foreground, and let him work and choose to save or not the mail (this is a global Notes client preference, that may be changed with field MailSaveOptions)
Try setting SaveOptions to "0" instead of to zero.
Dimly in the far back reaches of my mind, something is telling me that it should be a text value.
Also, I think you should be doing this before you open the UIDocument for editing, but that's an even more dim memory.

NotesRegistration Lotusscript function for create ft index

My main purpose is to create a user into names.nsf on website, which only "admin" account can do the registration for user.
The admin account have right to call web agent below is attached photo of setting
I have problem on
1. createftindex = mail ftindex not functioning
2. grouping = possible to add two group? for example [Everyone] group and [software] group
Does my coding part for below this is wrong?
reg.Mailcreateftindex=True
reg.Grouplist="Everyone"
Option Public
Option Declare
Sub Initialize
' this agent use on [register] button locate on [request form] xpages
Dim s As New NotesSession, db As NotesDatabase, a As NotesAgent
Dim doc As NotesDocument
Set db = s.Currentdatabase
Set a = s.Currentagent
Set doc = s.Documentcontext ' uidoc
Dim certid As String ' full path of cert id
Dim certpasswd As String
Dim OU As String
Dim lastname As String
Dim firstname As String
Dim middleinit As String
Dim usrIdpath As String
Dim mailsvr As String
Dim mailfile As String
Dim userpasswd As String
Dim internetpath As String
Dim userID As String
Dim depvw As NotesView, depdoc As NotesDocument
Set depvw = db.Getview("Department sort by dept")
Set depdoc = depvw.Getdocumentbykey(doc.Dept(0), True)
If Not depdoc Is Nothing Then
certid = depdoc.IdPath(0) ' full path of cert id
certpasswd = depdoc.IdPassword(0) ' Cert id password(password)
OU = "" 'depdoc.Dept(0) ' Application (department to register)
lastname= doc.Name(0) ' current document selected mail (person)
firstname = "" ' [din't used]
middleinit = "" ' [din't used]
usrIdpath = depdoc.DptIdStor(0) +doc.SelectMail(0)+ ".id" ' user path
' id cannot have . in between for example, test1.Apple
' remove "." replace with empty and remove the empty space
userID = remapChr(doc.SelectMail(0))
mailsvr = depdoc.MailSvr(0) ' mail svr
' Mail file name also cannot have . in between for example, mail/test1.apple, reason window not understand it
mailfile = depdoc.MailLocation(0)+userID ' Mail\Person
userpasswd= depdoc.UserPassword(0) ' User password
internetpath = doc.SelectMail(0)+depdoc.InternetPath(0) ' mail address
End If
Dim reg As New NotesRegistration
Dim dt As Variant
dt = DateNumber(Year(Today)+1, Month(Today), Day(Today))
reg.RegistrationServer = mailsvr '"CN=ServerOne/O=dev"
reg.CreateMailDb = True '
reg.CertifierIDFile = certid '"C:\IBM\Domino\data\office.id"
reg.Expiration = dt
reg.IDType = ID_HIERARCHICAL
reg.MinPasswordLength = 1 ' password strength
reg.IsNorthAmerican = True
reg.OrgUnit = OU ' "" empty ..will just follow certid registration
reg.RegistrationLog = "log.nsf"
reg.UpdateAddressBook = True
reg.StoreIDInAddressBook = True
reg.MailInternetAddress = internetpath '"desmond#devsv1.pcs.com.my"
reg.Shortname=userID ' 'Set shortname []
reg.Mailowneraccess =2 ' '[editor access]
reg.Mailcreateftindex=True ' '[Indexing]
reg.Mailaclmanager ="LocalDomainAdmins" ' 'Add LocalDomainAdmins into mail acl
reg.Grouplist="Everyone" ' 'Everyone
Call reg.RegisterNewUser(lastname, _ ' last name
usridpath, _ '"C:\IBM\Domino\data\ +name+.id" ' file to be created
mailsvr, _ '"CN=ServerOne/O=dev" ' mail server
firstname, _ ' ' first name
middleInit, _ ' ' middle initial
certpasswd, _ '"office" ' certifier password
"", _ ' location field
"", _ ' comment field
mailfile, _ '"mail\person.nsf" ' mail file
"", _ ' Forwarding domain
userpasswd, _ '"password", _ ' user password
NOTES_DESKTOP_CLIENT) ' user type
' call name nsf and open for edit for forcing user must change password first time
Dim ndb As NotesDatabase
Dim viwUser As NotesView
Dim docUser As NotesDocument
Set ndb = New NotesDatabase( mailsvr, "names.nsf" )
Set viwUser = ndb.GetView("People by Email")
Set docUser = viwUser.GetDocumentByKey(userID,True)
Call docUser.ReplaceItemValue( "HTTPPasswordForceChange" , "1" )
Call docUser.Save( True, True, True )
Print "Please wait ...... Registration in progress"
End Sub
Function remapChr (oldString)
' to replace all special character with a empty space after that trim to remove all special character in system
Dim oldChr, newChr, newString As String
oldChr = {! "" # $ % & ' ( ) * + , - . / : ; = > ? # [ \ ] ^ _}
newChr = " {"
oldChr = Split(oldChr, " ")
newChr = Split(newChr, " ")
newString = Trim(Replace(LCase(oldString), oldChr, newChr))
remapChr = newString
End Function

NotesReplicationEntry - Lotus Notes

I am trying to set Selective Replication using LotusScript but I cannot get it to save. The log shows no errors and the script completes without error. The replica gets created but not with my Selective Replication set.
%REM
Agent createRenewalDB
Created Dec 14, 2016 by
Description: Comments for Agent
%END REM
Option Public
Use "xxx Routines"
Sub Initialize
Dim db As NotesDatabase
Dim doc As NotesDocument
Dim s As New NotesSession
Dim flag As Boolean
Dim renDb As NotesDatabase
Dim renFP As String
Dim renHubDb As NotesDatabase
Dim sQuote As String
Dim nowt As String
Dim pos As Long
Dim client As String
Dim frm As String
Dim L As Long
Dim P1 As String
Dim P2 As String
Dim item As NotesItem
Dim renYN As String
Dim agent As NotesAgent
Set agent = s.CurrentAgent
Print("createRenewalDB starting")
Set db = s.Currentdatabase
Set doc = db.GetDocumentByID(agent.ParameterDocID)
'Print("got doc")
client = doc.getItemValue("Client")(0)
nowt = ""
sQuote = """"
pos = 1
Dim tmp1 As String
'Print("set vars")
tmp1 = doc.getItemValue("SearchFormula")(0)
'Print("got search formula")
frm = StrLeft(StrRight(tmp1,"ix_client;"),")")
'### strip out quotation marks
Do Until pos = 0
L = Len(frm)
pos& = InStr(1,frm,sQuote)
If pos <> 0 Then
P1 = Left(frm,pos - 1) ' Part 1 of the text string
P2 = Right(frm,L- pos )
frm = P1 & nowt & P2
End If
Loop
'Print("stripped out the rubbish")
'#### Setup a new Renewals document if none exixts and Renewals has been selected
Set item = doc.getfirstitem("EnabledApps")
renYN = item.text
If InStr(renYN, "32") > 0 Then
'##### Get the Renewals Quotes Db
Set renHubDb = Get_Specific_Db_Object("Renewal Quotes", "xxx-01")
If renHubDb Is Nothing Then
MsgBox("Fail: Could not get the Renewals Quotes database on Hub, exiting renewals created.")
Exit Sub
End If
renFP = doc.getItemvalue("Renewals")(0)
'Msgbox("Renewals to be set up " + renFP)
Set renDb = s.GetDatabase("",renFP,False)
If renDb Is Nothing Then '#### No replica, so create one
Print("Creating a replica for " + client)
Set renDb = renHubDb.CreateReplica("xxx-01",renFP)
renDb.Title = client
Dim rep As NotesReplication
Dim re As NotesReplicationEntry
Dim server As String
server = "xxx-xxx-01"
Set rep = renDb.ReplicationInfo '## Get the replication info
Set re = rep.GetEntry("-",server,True) '## get the replication entry - true creates it
re.Formula = "SELECT #Contains(client;" &"""" & frm & """" & ")" '## add the selective replication
Print("selective replication formula " + re.Formula)
'## save both
Call re.Save
Call rep.Save()
Print(re.Formula) '## formula is still set correctly at this point
End If
If renDb Is Nothing Then
MsgBox("Could not create a replicate for " + client)
Exit Sub
End If
Else
MsgBox("No Renewals " + renYN)
End If
Print("###########################################Finished creating the replica - agent")
End Sub
Any thoughts?
Lotus Notes 9.0.1
Lotus Domino 9.0.1
Code is in an agent that has Full Admin Access Set on the Security Tab.
Thanks
Graeme

Getting "The linked document (UNID... cannot be found in the view (UNID ...)" Error Message

I'm getting the error message below:
Upon clicking the doclink which was being attached in the e-mail which was generated by me through clicking the send to managers button. I also tried using NotesURL instead of doclink:
Call rtitem.appendtext(emaildoc.Notesurl)
but the generated URL is different from the doclink. Below is the generated from the doclink itself.
Generated NotesURL: notes://LNCDC#PHGDC/__48257E3E00234910.nsf/0/237B2549EEA393A948257E530042BA4A?OpenDocument
Doclink: Notes://LNCDC/48257E3E00234910/28BD6697AB48F55348257E2D0006CF60/C9B0266FDC0D929E48257E530041D6F9
Can you please help? Below is my agent code.
%REM
Agent Send Email to Managers
%END REM
Option Public
Option Declare
Dim s As NotesSession
Dim db As NotesDatabase
Dim emaildoc As NotesDocument
Dim paydoc As NotesDocument
Dim rtitem As NotesRichTextItem
Dim i As Integer
Dim view As NotesView
Sub Initialize
Set s = New NotesSession
Set db = s.CurrentDatabase
Set view = db.GetView("Pending Claims")
Dim addresses As NotesName
Dim arrpem As Variant
ReDim arrpem(0)
Set paydoc = view.GetFirstDocument
'// Store all PEM names in an array
While Not(paydoc Is Nothing)
ReDim Preserve arrpem(UBound(arrpem) + 1)
arrpem(UBound(arrpem)) = paydoc.PeopleManager(0)
Set paydoc = view.GetNextDocument(paydoc)
Wend
'// Remove all duplicate PEM names and empty entries in the array
arrpem = FullTrim(ArrayUnique (arrpem))
'// Loop the PEM names array
ForAll pem In arrpem
Set emaildoc = New NotesDocument(db)
Set addresses = New NotesName(pem)
If addresses.abbreviated <> "" Then
emaildoc.SendTo = addresses.abbreviated
emaildoc.Subject = "Leave Balances of your Direct Reports"
emaildoc.Form = "Memo"
Set rtitem = New NotesRichTextItem(emaildoc, "Body")
Call rtitem.AppendText("Dear " & addresses.common & ",")
Call rtitem.AddNewLine(2)
'// Remove paydoc value which was used in the PEM names array
Set paydoc = Nothing
'// Get all documents that has matching PEM name in the view
Dim dc As NotesDocumentCollection
Set dc = view.GetAllDocumentsByKey(addresses.Abbreviated, True)
Set paydoc = dc.GetFirstDocument
'// Append doc link of employee
While Not(paydoc Is Nothing)
Call rtitem.AppendText("Doc link of :" & paydoc.FMName(0) & " " & paydoc.LastName(0))
Call rtitem.appenddoclink(emaildoc, "Link to Leave Balance of " & paydoc.FMName(0) & " " & paydoc.LastName(0))
Call rtitem.AddNewLine(1)
Set paydoc = dc.GetNextDocument(paydoc)
Wend
'// Send email per PEM
Call emaildoc.Send(False)
End If
End ForAll
MsgBox "Emails successfully sent."
End Sub
The doclink is pointing back to the document you've created in memory for your email. When sent, that document no longer exists in the original database.
Change your code to be:
Call rtitem.appendtext(paydoc.Notesurl)

Remainder Mail agent

I have form with 3 fields adress,status,ReportingDate.
Adress field contains the ID where the mil has to be sent.
Now I have created an agent where it should mail to the data present in adress field when status is incomplete and reporting date is exactly 7 days before todays date.
My Code:
Option Public
Option Declare
Sub Initialize
Dim sess As New NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Dim timestamp As New NotesDateTime("Today")
Dim Noresponsedate As NotesDateTime
Dim vw As NotesView
Dim diff As Integer
Dim SendTo As Variant
Call timestamp.SetNow()
Set db = sess.CurrentDatabase
Set vw = db.GetView( "data" )
Set doc = vw.GetFirstDocument()
While Not doc Is Nothing
If doc.Status(0) = "Incomplete" Then
Call checktimedifference(doc)
End if
Set doc = vw.GetNextDocument(doc)
wend
End Sub
Sub checktimedifference(doc As NotesDocument)
Dim due As NotesDateTime
Dim present As NotesDateTime
Dim timecheck As variant
Set due = New NotesDateTime ( "" )
Set present = New NotesDateTime ( "Today" )
timecheck = doc.ReportingDate(0)
due.LSLocalTime = timecheck
If due.TimeDifference (present) = -604800 Then
Call sendmailtouser(doc)
End If
End Sub
Sub sendmailtouser(doc As NotesDocument)
Dim db As NotesDatabase
Dim rtiitem As NotesRichTextItem
Dim maildoc As NotesDocument
dim recepient As variant
Set maildoc = New NotesDocument( db )
Set rtiitem = New NotesRichTextItem( maildoc, "Body" )
recepient = doc.adress(0)
maildoc.from = db.Title
maildoc.form = "memo"
maildoc.subject = "A Minor Injury Report:" & doc.Seq_No(0) & " needs your response"
maildoc.SendTo = recepient
Call rtiitem.AppendText( "Please respond to this Minor Injury Report" )
Call rtiitem.AddNewline( 2 )
Call rtiitem.AppendText( "Your response for the Minor Injury Report: " & doc.Seq_No(0) & " is required" )
Call rtiitem.AddNewline( 2 )
Call rtiitem.AppendText( "Please click on the following link to access the document.")
Call rtiitem.AppendDocLink( doc, db.Title )
Call maildoc.Send(False)
End Sub
When I am running the agent on client I am getting the following error:
Please help me to solve the error and send mail to the recepients.
Not using any error handling is very bad practice. But your error will most probably happen in the sendmailtouser- sub, where you dim a local notesdatabase- object named db without actually initializing it.
The line
set maildoc = New NotesDocument( db )
will fail.
Either declare db globally and set it in your initialize or dim ses in that sub again and set db again (worst case as you have to do it for every document)

Resources