6085 comments
2357 subscribers
6223 on Twitter
Subscribe! Feed reader E-mail

Even more awesome LotusScript mail merge for Lotus Notes + Microsoft Excel

UPDATE: May 20, 2011 – David Turner has shared his excellent improvements. Check them out!

UPDATE: May 28, 2010 – fixed errors caused by default Option Declare. Thanks to Lisa Harnett for the feedback!
UPDATE: Oct 19, 2010 – fixed Quit(). Thanks to Vance for the feedback! Also, clarified tokens.

Based on the feedback on my Lotus Notes mail merge from a Microsoft Excel spreadsheet (2009), I’ve refined my merge script to make it more awesome. How is it more awesome?

  • Prompts you for drafting or sending
  • Saves sent messages
  • Allows you to customize the subject
  • Uses [ ] instead of < and > for built-in tokens ([to], [cc], [subject]) for less HTML confusion in blog posts and replies
  • Displays number of sent messages and errors
  • Closes the Microsoft Excel spreadsheet afterwards

The search-and-replace tokens are defined in the first row of your Microsoft Excel spreadsheet. The script searches for them in the message body, replaces them with the appropriate values from the current row, and either saves the message as the draft or sends the message. There are a few built-in tokens for this script ([to], [cc], [subject]) – these are case-sensitive, so enter them exactly like that. All the other tokens are up to you, so you could use FOO and BAR as search-and-replace tokens if you want.

Tokens are replaced only in the message body. If you want a variable subject line, use a formula to calculate the subject in a column with the [subject] header.

As always, test your mail merges with a small list before using it for your entire list. Create an agent and call it something like “Mail merge”. Edit the agent and set the type to LotusScript. In the (Declarations) section, add

%Include "lsconst.lss"

In the “Initialize” section, put in:

Sub Initialize
	'Mail merge script by Sacha Chua (sacha@sachachua.com)

	Dim ws As NotesUIWorkspace
	Set ws = New NotesUIWorkspace
	Dim sendTypes(1) As String
	Dim sendValue As String
	Dim errorCount As Integer
	errorCount = 0
	sendTypes(0) = "Draft messages without sending"
	sendTypes(1) = "Send messages"
	sendValue = ws.Prompt(PROMPT_OKCANCELLIST, "Sending options", "What would you like to do?", "", sendTypes)
	If (sendValue = "") Then
		Exit Sub
	End If

	Dim fileName As String
	Dim strXLFilename As String
	'Prompt for the filename - should be a Microsoft Excel file with columns, where the first row of each column
	'is a token that will be used when replacing text in the body of the message
	'Special tokens: [to], [cc], [subject] set the appropriate fields
	'Make sure the first column does not have any blank cells
	fileName$ = ws.Prompt(12, "Select file", "3")
	If fileName$ = "" Then
		Exit Sub   'Cancel was pressed
	End If
	strXLFilename = fileName$
	Dim s As New NotesSession
	Dim uidoc As NotesUIDocument
	Dim partno As String
	Dim db As NotesDatabase
	Dim view As NotesView
	Dim doc As NotesDocument
	Dim collection As NotesDocumentCollection
	Dim memo As NotesDocument
	Dim body As NotesRichTextItem
	Dim newBody As NotesRichTextItem
	Dim range As NotesRichTextRange
	Dim count As Integer

	Set db = s.CurrentDatabase
	Set collection = db.UnprocessedDocuments
	Set memo = collection.getFirstDocument()

	Dim varXLFile As variant
	'Get data from the spreadsheet
	Set varXLFile = CreateObject("Excel.Application")
	varXLFile.Visible = False
	Dim varXLWorkbook As variant
	Set varXLWorkbook = Nothing
	varXLFile.Workbooks.Open strXLFilename
	Set varXLWorkbook = varXLFile.ActiveWorkbook
	Dim varXLSheet As variant
	Set varXLSheet = varXLWorkbook.ActiveSheet

	Dim lngRow As Integer
	Dim columnNo As Integer
	Dim token As String
	Dim value As string
	lngRow = 2
	Dim maildoc As NotesDocument
	While (Not (varXLSheet.Cells(lngRow, 1).Value = ""))
		'Fill in the template
		Dim subject As string
		subject = memo.Subject(0)
		Set body = memo.GetFirstItem("Body")

		'Compose message
		
		Set maildoc = New NotesDocument(db)
		Set maildoc= db.CreateDocument()
		maildoc.Form = "Memo"
		maildoc.Subject = subject
		Set newBody = maildoc.CreateRichTextItem("Body")
		Call newBody.appendRTItem(body)
		Set range = newBody.CreateRange			

		'Count the number of fields
		'Look up tokens from the column headings and replace them
		columnNo = 1
		While Not(varXLSheet.Cells(1, columnNo).Value = "")
			token = varXLSheet.Cells(1, columnNo).Value
			value = varXLSheet.Cells(lngRow, columnNo).Value
			count = range.FindAndReplace(token, value, 16)
			If (token = "[to]") Then
				maildoc.SendTo = value
			End If
			If (token = "[cc]") Then
				maildoc.CopyTo = value
			End If
			If (token = "[subject]") Then
				maildoc.Subject = value
			End If
			columnNo = columnNo + 1
		Wend
		On Error GoTo save
		If (sendValue = sendTypes(0)) Then
			Call maildoc.Save(True, False)
		Else
			maildoc.SaveMessageOnSend = True
			maildoc.PostedDate = Now()
			Call maildoc.Send(False)
			Call maildoc.Save(True, True)
		End If
		GoTo nextrow
save:
		MessageBox("Error processing " + maildoc.sendTo)
		errorCount = errorCount + 1
		Resume Next
nextrow:
		lngRow = lngRow + 1
	Wend
	If (sendValue = sendTypes(0)) Then
		MsgBox "Drafted " & (lngRow - errorCount - 2) & " message(s). Errors: " & errorCount
	Else
		MsgBox "Sent " & (lngRow - errorCount - 2) & " message(s). Errors: " & errorCount
	End If
	Call varXLFile.Quit()
End Sub
Short URL: http://sachachua.com/blog/p/7189
  • Varun Malik

    This is great – thank you!

  • http://www.openntf.org/Projects/pmt.nsf/projectlookup/MailMerge%20Excel%20to%20Notes David

    Hi All,

    FYI I’ve just released v1.2 of the Mail Merge script on OpenNTF which includes the ability to embed dynamic attachments. Let me know what you think, and feel free to leave any other feature requests!

    - Dave :)

  • CoolDude

    This is one of the coolest things I have seen ! Has made my job much simpler. !!
    Can’t thank you enough !

  • Kent

    thanks ! Worked great for us … nice script

  • Tine

    Great script!
    I have only one question: if I choose “return receipt” in draft the agent doesn’t include this in later e-mails.
    Can this be fixed somehow (we always send mails with return receipt)?

  • http://sachachua.com Sacha Chua

    I’m not sure how, but you might be able to modify the script to do so. Good luck! =)

  • http://www.openntf.org/Projects/pmt.nsf/projectlookup/MailMerge%20Excel%20to%20Notes David

    Thanks for the suggestion. This should be straightforward. Curiously, this issue also occurs with OpenNTF project release 1.3, so I’ve created a feature request. Look out for this enhancement in the next release.

  • http://www.openntf.org/Projects/pmt.nsf/projectlookup/MailMerge%20Excel%20to%20Notes David

    Tine, I have implemented your request in the latest release 1.3.1.

    All Delivery Options I could find — including: Return Receipt, Reply To, Reply Date, High Importance — will now be copied from the email template to the generated emails.

    Let me know if you encounter any problems with this new function!

    - David :)

  • peter

    Hi,

    I also get this error message when I use the send option:
    Type Mismatch in method CheckOperand: Unknown found, Unknown Expected

    I have a list with 20 names and it does send 1 to 3 messages before popping the error and then it does not close the excel file.

    When using the ‘draft’ options it says that it has created X drafts with no errors. The drafts appear correct with the ‘to’ field correctly inserted and when I press send in the created draft is sends the message with no errors.

    …any suggestions?

  • http://www.openntf.org/Projects/pmt.nsf/projectlookup/MailMerge%20Excel%20to%20Notes David

    Hi Peter, there is probably something funny about the data on row 2 or 3 of your spreadsheet.
    I would recommend you try the latest v1.3.1 of this script on OpenNTF.org. It includes improved error handling — identifying row, line numbers and fields being processed when the error occurred — which will help diagnose the problem!

    • http://sachachua.com Sacha Chua

      Thanks for helping, David! :)

  • Katrien

    Thanks for this script, it works very good.

    I have one more question. We would like to add a button or something like that with a link. If you click on it, it will take you to an online form. In this link we have added some fields. We want one of these fields to be filled in already with the email address when someone clicks on the link. For this we want to use the token [to] (e.g. http://www.test.com/test/field123=to). If we just use the link in the email body it works, because when the mail is sent, the email address will be filled in immediately (ex. [to]). But we don’t want to put the link in the email body (it doesn’t look nice, people can see their email address in the link), we want to hide it behind a button or something like that (a hotspot). Do you have any idea how we can fix this? Because when I use the link as a hotspot it fills in [to] instead of the email address.

  • http://www.openntf.org/Projects/pmt.nsf/projectlookup/MailMerge%20Excel%20to%20Notes David

    Hi Katrien,

    Thanks for the query. I’ve been looking into ways of getting a Notes Hotspot or Button or Embedded Image into the generated emails.

    My research (and trial and error) suggests that for all versions at least up to Notes 8.5.3, is NOT possible to achieve this in ordinary LotusScript (no native functions for these elements exist, and AppendRTItem behaviour is restrictive). Therefore, barring hacking into Notes using DLL extensions, the solution will probably involve re-writing this agent to use Notes DXL manipulation.
    I’ll add this as a feature request on the OpenNTF project and think about this as a major v1.5 enhancement.

  • Pingback: Send email, where body equals same row column b as address in column a - dBforums

  • Martin

    Sacha, it’s awesome, thank you! I’ve been looking for a solution for long time and all which I found were too complicated for me :) This one is pretty straight forward even for basic LN user as me :)

    Anyway, I have a question / problem:
    I’ve created a stationary, which I am using when drafting the mails. In the stationary I’ve set the “reply-to” address to the specific one. However when merging the mails the reply to address is not kept on the created mail drafts..

    PS: I am using LN v 8.5.2

    Any thoughts?

  • http://sachachua.com Sacha Chua

    Martin: Good luck! I don’t have access to Lotus Notes any more (the perks of working on my own! =) ), but maybe you can give David’s script a try (see the link at the beginning of the post). Alternatively, you could add a little bit of code to set the ReplyTo yourself. Hope that helps!

  • Martin

    Sacha: did try that and failed (I didn’t manage to install it – as I said I am Lama at LN and don’t have the Domino Designer..). I’ll keep looking around for solutions, thanks!

  • Andrew

    Sacha, David, I across your blog and then the download at http://www.openntf.org
    The mailmerge function works great. Thanks for the post and then following it up. Also the documentation was very useful.

  • Salim Kadiri

    How do I attach files while sending the Mail using your Mail merge option..
    Also please can u tell the format on the execl file in which I have to create a list of Id to whom I have send the mails..

    regards
    Salim

  • Paul

    Hi,
    Thanks for the great script. I would like to use symphony instead of Excel. What would it take to convert the script to work with symphony??

  • http://sachachua.com Sacha Chua

    Probably figuring out how to talk to Symphony, or parsing a CSV. =) I don’t have Lotus Notes any more, but maybe other people can help!

  • Paul

    I found this in developerWorks

    http://www.ibm.com/developerworks/lotus/library/symphony-toolkit/

    I not into Lotus scripting. Can you help me in figuring out what needs to be replaced with the Symphony toolkit in your script??

  • http://www.openntf.org/Projects/pmt.nsf/projectlookup/MailMerge%20Excel%20to%20Notes David

    Hi Paul,

    There is an open feature request for CSV/OpenOffice/Symphony support on the OpenNTF MailMerge project (click my name above or the link at top of Sacha’s page).

    While you’re not into Lotus scripting, I am afraid you’ll have to get into it (or find a developer who is) to make this work for you as I don’t run Symphony myself.

    However, to help you make a start, have a look under that feature request for some implementation notes I’ve just added. Hope that helps.

    Good luck and enjoy! :)

  • Salim Kadiri

    Dear Sacha..

    Thanks once again for the Mail merge script but still me query for doing the mail merge with attaching files in not resolved.

    I have a number of senders and a different file need to be attached to the respective mails. How to do …

    Mr Paul.. while using the mail symphone the subject becomes the attachment..

  • Paul

    Thanks Dave, I’ll see if I can do a work around and get this working.

  • http://www.openntf.org/Projects/pmt.nsf/projectlookup/MailMerge%20Excel%20to%20Notes David

    Salim, Attachment support was added in v1.2. Please review the OpenNTF project documentation and download the User Guide for the answers to this and your other questions.

  • Salim Kadiri

    Dear David

    Thanks for ur support, but requesting you to kindly update the link in your revert as I m not able to get the same from your update….

    Dear Sacha, Paul & David,
    THANK U All once again, I have managed to run the macro sucessfully but the only error is the attachment of file to its respective sender. Hope you all understand my query…

  • Berni

    Great script
    What code would be required to automatically select one particular stationery?

  • AJ

    Dear Sacha,

    Great Script. Thanks a ton.

    It is specially good for those who do not have the Domino Designer installed.

    Regards,
    AJ

  • http://sachachua.com Sacha Chua

    Glad it was helpful!

  • Nick

    Is there a way to include images as part of the merge?  For example, within the Excel file you’d have [NAME] is John and a corresponding image file named John.jpg.  Is there a way to have the script pull the relevant information from the Excel file and then have it pull the image file that matches the [NAME] in the Excel file?

    Many thanks!

On This Day...

Get the highlights as a PDF!

Stories from my Twenties: Highlights from a Decade of Blogging