VBA-Insert body of email above signature using Lotus Notes - vba

What I am trying to achieve is very simple, insert the body of an email above the signature in lotus notes. The code I have in vba, when run, opens a new email window in lotus notes pastes in the Subject, SendTo and Body fields. Everything works perfectly, but when the body is inserted it puts the text below my signature. I've done a ton of digging to try and find a solution, but haven't found anything that has worked just right. A few posts I've found suggest removing the signature, pasting the body and then rebuilding the signature into the email--not really the approach i'd like.
Here is my code:
Sub CreateEmail()
Dim Notes As Object
Dim Maildb As Object
Dim objNotesDocument As Object
Dim objNotesField As Object
Set Notes = CreateObject("Notes.NotesSession")
Set Maildb = Notes.GETDATABASE("", "")
Maildb.OPENMAIL
Set objNotesDocument = Maildb.CREATEDOCUMENT
Subject = "Hey look at my email!!"
Set objNotesField = objNotesDocument.APPENDITEMVALUE("Subject", Subject)
Set objNotesField = objNotesDocument.APPENDITEMVALUE("SendTo", GetPrimaryEmail) 'calls a function to return the SendTo
Set objNotesField = objNotesDocument.APPENDITEMVALUE("Body", bodyInfo) 'calls a function to return the body contents.
Set workspace = CreateObject("Notes.NotesUIWorkspace")
Call workspace.EDITDOCUMENT(True, objNotesDocument)
AppActivate "Lotus Notes"
End Sub
Thanks in advance for any help!

A different approach to set the Body content is to open the new document in edit mode (like you do at the end of your code) and then set cursor to Body field and insert the text. Your code could look like this:
...
Set objNotesField = objNotesDocument.APPENDITEMVALUE("SendTo", GetPrimaryEmail) 'calls a function to return the SendTo
Set workspace = CreateObject("Notes.NotesUIWorkspace")
Call workspace.EDITDOCUMENT(True, objNotesDocument)
Set uidocument = workspace.CurrentDocument
Call uidocument.GotoField("Body")
Call uidocument.InsertText(bodyInfo) 'calls a function to return the body contents.
AppActivate "Lotus Notes"

Related

Copying a lotus notus database view and paste into word document

The code below reads and inserts the email from lotus notes to an excel sheet. However I would like to read a lotus notes database and copy its content and paste it as a rich text into a word document.
I assume this line of code needs to be modified.
Set nitem = .GetFirstItem("Body")
What would be the best way to go about this?
Public Sub Lotus_Notes_Current_Email4()
Dim NSession As Object 'NotesSession
Dim NUIWorkSpace As Object 'NotesUIWorkspace
Dim NUIdoc As Object 'NotesUIDocument
Dim nitem As Object 'NotesItem
Dim lines As Variant
Set NSession = CreateObject("Notes.NotesSession")
Set NUIWorkSpace = CreateObject("Notes.NotesUIWorkspace")
Set NUIdoc = NUIWorkSpace.CurrentDocument
If Not NUIdoc Is Nothing Then
With NUIdoc.Document
Set nitem = .GetFirstItem("Body")
If Not nitem Is Nothing Then
lines = Split(nitem.Text, vbCrLf)
Sheets(1).Activate
Range("H8").Resize(UBound(lines) + 1, 1).Value = Application.WorksheetFunction.Transpose(lines)
End If
End With
Else
MsgBox "Lotus Notes is not displaying an email"
End If
Set NUIdoc = Nothing
Set NUIWorkSpace = Nothing
Set NSession = Nothing
End Sub
Your assumption is incorrect. Your entire script needs to be rewritten.
If you want to copy the contents of a view, then you need to start by opening a NotesView object. Your current code is opening a NotesDocument object. To get the NotesView, you might want to use the CurrentView property NotesUIWorkspace to get a NotesUIView object, and then use that objects View property.
Once you have the NotesView object, then I'm guessing you might want to want to use the columns property to get at the data, but there are other ways you could go about it. Pretty much no matter what you do, though, you're going to have to handle the formatting of the data on your own.

Playing with vba sending email through lotus notes

I have already seen a lot of posts related to that, both on the web overall or on stackoverflow. However, I didn't see people making too much changes and really playing with this macro.
Ok, it's possible to send emails through lotus notes using VBA, but how can I make these emails cooler? Change font format or color for example? Change the styles, choosing to insert picture as a link or embedding it?
Well, this is what I got so far by searching around and making a few changes:
Sub SendEmail(Subject, Text)
Dim Maildb As Object
Dim mailDoc As Object
Dim body As Object
Dim session As Object
'Start a session to notes
Set session = CreateObject("Lotus.NotesSession")
'This line prompts for password of current ID noted in Notes.INI
'Call session.Initialize
Call session.Initialize("Your Password Here")
'Open the mail database in notes
Set Maildb = session.GetDatabase("Mail Server", "mail\ .nsf")
If Not Maildb.IsOpen = True Then
Call Maildb.Open
End If
'Create the mail document
Set mailDoc = Maildb.CreateDocument
Call mailDoc.ReplaceItemValue("Form", "Memo")
'Set the recipient (you can write the name of a list you saved in your Lotus Notes)
Call mailDoc.ReplaceItemValue("SendTo", "email1#email.com.br")
'Set subject
Call mailDoc.ReplaceItemValue("Subject", Subject)
'Create and set the Body content
Set body = mailDoc.CreateRichTextItem("Body")
Call body.AppendText(Text)
'Example to create an attachment (optional)
Call body.AddNewLine(2)
'Insert an pdf attached
Call body.EmbedObject(1453, "", "C:\Desktop\Test.pdf")
Call body.AddNewLine(2) 'add line to separate text
'Message in the end of the email
Call body.AppendText("This is an automatic message.")
'Example to save the message (optional)
mailDoc.SaveMessageOnSend = True
'Send the document
'Gets the mail to appear in the Sent items folder
Call mailDoc.ReplaceItemValue("PostedDate", Now())
Call mailDoc.send(False)
'Clean Up
Set Maildb = Nothing
Set mailDoc = Nothing
Set body = Nothing
Set session = Nothing
End Sub
Btw, I use the Windows Task Scheduler to call a VBS which will then call a macro that will call the macro to send email with a specific subject and text. As I have several macros that generates emails and each one has its subject and text, I thought this would be better.
This is the vbs (this is probably useless and everyone knows here, but I will share anyway):
'Run VBA Using VBS
Option Explicit
On Error Resume Next
ExcelMacroExample
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\Desktop\Macros.xlsm") 'Excel filename
xlApp.Run "SendEmail" 'Excel macro name
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
A couple of things here:
It's going to be easier if you can first write the code in Domino Designer (i.e. get a machine installed with the Notes Client and the Domino Designer Client). At the moment you are using Notes as a COM Server. The big disadvantage is that you have almost no debugging information if something fails. Write the code first in LotusScript, then port it to VBS (they are very similar dialects of BASIC).
You can create a Notes RichText E-Mail (this is what you are doing now with CreateRichTextItem). You can manipulate the RichTextItem with different methods, the most important one being NotesRichTextStyle, which you have to think of as 'bits of formatting that will change everything afterwards'. You need to create the NotesRichTextStyle Object, configure it (i.e. font, bold, etc) and insert it into the rich text field. If this sounds klunky, that's because it is.
Dim db As NotesDatabase
Dim session As New NotesSession
Set db = session.CurrentDatabas
Dim doc As New NotesDocument(db)
Call doc.AppendItemValue("From", session.UserName)
Call doc.AppendItemValue("Subject", _
"Meeting time changed")
Dim richStyle As NotesRichTextStyle
Set richStyle = session.CreateRichTextStyle
Dim richText As New NotesRichTextItem(doc, "Body")
Call richText.AppendText("The meeting is at ")
richStyle.Bold = True
Call richText.AppendStyle(richStyle)
Call richText.AppendText("3:00")
richStyle.Bold = False
Call richText.AppendStyle(richStyle)
Call richText.AppendText(" not 2:00")
Call doc.Save(True, False)
If you want even more control, then you can create an HTML E-Mail wrapped in Mime, but it's fiddly at best and you're looking at several days of painful steps until it works, and you really would need an experienced professional for this. This is a good start: other Stackoverflow question
The way you're referencing the user's mail reference is horrible. It's hardcoded and will only ever work for that one particular database, even if the person in question changes name, for instance. This is much better:
Dim db As New NotesDatabase( "", "" )
Call db.OpenMail

Excel VBA--Insert blank line in lotus notes email body

I am looking to insert a blank line into the body of a lotus notes email.
For example:
Currently my body displays this:
"Hi this is the body of my email. <img></img>"
And I want the body of my email to look like this:
"Hi this is the body of my email.
<img></img>"
How would I go about doing this? Any creative ideas?
Here is my code:
Sub CreateEmail()
Dim Notes As Object
Dim Maildb As Object
Dim objNotesDocument As Object
Dim objNotesField As Object
Dim notesUIDoc As Object
Dim chartBody As Range
Set Notes = CreateObject("Notes.NotesSession")
Set Maildb = Notes.GETDATABASE("", "")
Maildb.OPENMAIL
Set objNotesDocument = Maildb.CREATEDOCUMENT
Subject = "Hi read me!!"
Set objNotesField = objNotesDocument.APPENDITEMVALUE("Subject", Subject)
Set objNotesField = objNotesDocument.APPENDITEMVALUE("SendTo", GetPrimaryEmail)
Set objNotesField = objNotesDocument.APPENDITEMVALUE("CopyTo", GetSecondaryEmail)
Set workspace = CreateObject("Notes.NotesUIWorkspace")
Call workspace.EDITDOCUMENT(True, objNotesDocument)
Set uidocument = workspace.CURRENTDOCUMENT
'Copy and Paste diagram into email
Set chartBody = Worksheets("Sheet1").Range("A1:G16")
chartBody.Copy
Call uidocument.GOTOFIELD("Body")
Call uidocument.Paste 'Paste a diagram in the body of email.
'Paste in body text
Call uidocument.GOTOFIELD("Body")
Call uidocument.INSERTTEXT(bodyInfo)'Calls a function to inserts the text for the body.
AppActivate "Lotus Notes"
End Sub
All that is happening is that I am inserting an image and then inserting text into the body of an email. The problem is that the picture and text get pasted on the same line, which causes weird formatting.
Add Chr(10) twice to your string. You get a blank line between text and image then
Call uidocument.INSERTTEXT(bodyInfo + Chr(10) + Chr(10))

Opening a Lotus Note draft with Excel VBA, in order to replace just values

I'm trying to write a Excel VBA code which allows me to automatically create and send a Lotus Notes Email. The problem I face is the difficulty to create a rich text Email, so I think it would be easier to open a draft email, with a marker text which will be replaced (for exameple PASTE EXCEL CELLS HERE) and then just:
.GotoField ("Body")
.FINDSTRING "PASTE EXCEL CELLS HERE"'
and replace.
Any help on how to open a certain draft email? Perhabs something as .CreateDocument property?
Thank you very much!
Others have proposed interesting concepts, but the most robust approach would be to use HTML in a MIME enitity that is mapped to the Body Rich Text item. Using NotesSession..Convertmime = False you can build the body as HTML and then send the message. Based on the post by Joseph Hoetzl here, the LotusScript equivalent is this:
Sub Initialize()
Dim s As New NotesSession
Dim db As NotesDatabase
Dim stime as Single
Dim alog As New NotesLog("debug")
Call alog.OpenAgentLog()
stime = Timer
On Error GoTo eh
Dim doc As NotesDocument
Dim body As NotesMIMEEntity
Dim header As NotesMIMEHeader
Dim stream As NotesStream
Dim child As NotesMIMEEntity
Dim sendTo As String
Dim subject As String
s.Convertmime = False
sendto = s.Effectiveusername
subject = "Demo Message"
Set db= s.Currentdatabase
Set doc=db.Createdocument()
Set stream = s.CreateStream
Set body = doc.CreateMIMEEntity
Set header = body.CreateHeader({MIME-Version})
Call header.SetHeaderVal("1.0")
Set header = body.CreateHeader("Content-Type")
Call header.SetHeaderValAndParams({multipart/alternative;boundary="=NextPart_="})
'Add the to field
Set header = body.CreateHeader("To")
Call header.SetHeaderVal(SendTo)
'Add Subject Line
Set header = body.CreateHeader("Subject")
Call header.SetHeaderVal(subject)
'Add the body of the message
Set child = body.CreateChildEntity
Call stream.WriteText("<h1>Demo HTML Message</h1>")
Call stream.WriteText(|<table colspacing="0" colpadding="0" border="none">|)
Call stream.WriteText(|<tr><td>cell 1.1</td><td>cell 1.2</td><td>cell 1.3</td></tr>|)
Call stream.WriteText(|<tr><td>cell 2.1</td><td>cell 2.2</td><td>cell 2.3</td></tr>|)
Call stream.WriteText(|<tr><td>cell 3.1</td><td>cell 3.2</td><td>cell 3.3</td></tr>|)
Call stream.WriteText(|</table>|)
Call stream.WriteText(|<div class="headerlogo">|)
Call stream.WriteText(|<!-- ...some more HTML -->|)
Call child.setContentFromText(stream, {text/html;charset="iso-8859-1"}, ENC_NONE)
Call stream.Truncate 'Not sure if I need this
Call stream.Close
Call doc.CloseMIMEEntities(True)
Call doc.replaceItemValue("Form", "Memo")
Call doc.Send(False, sendTo)
es:
Exit Sub
eh:
Dim emsg$
emsg = Error & " at " & Erl & " in " & s.Currentagent.name
Call alog.logError(Err, emsg)
MsgBox "ERROR: " & Err & ": " & emsg
Resume es
End Sub
All of this should convert fairly easily to VBA in Excel. You can, of course be as complex as you want with your HTML.
The word "draft" is probably inappropriate here, but then again so is the word "template". Both have specific meanings in Lotus Notes that aren't what you really want. Users can delete drafts, and templates are an entirely different thing. So let's just call it a boilerplate message.
I would recomemnd creating a special mail database (NSF file) on the Domino server, which will just serve as a repository for your boilerplate. You can create a folder in that mail database called "Boilerplates". Using Domino Designer you can modify that folder's design so that the Subject column is the first column in the view, and it is sorted.
Once you have that done and you have created some boilerplates and saved them in the folder, you can use VBA to do a NotesSession.getDatabase call, NotesDatabase.getView call (this is used for folders as well as views), and then use NotesView.getDocumentByKey() to retrieve a specific boilerplate by the Subject you have assigned to it. Note that you do not have to copy this document to the user's mail database in order to mail it.
What you want to do is non-trivial, but you mention a draft email so there may be a workaround.
In your mail settings you can specify a signature file which can be an external html file on disk. So modify the signature file, then create your new mail which will then populate the body field the way you want it.
For sample code, within the memo form there should be a button to specify what signature file to use. You can use that as the baseline.
Rich text is not that hard to work with, but you need to look at the Domino Designer help, especially the classes NotesRichTextItem and NotesRichTextStyle. You also need to understand the DOM (Domino Object Model). Then you can create your mail content programatically.
Otherwise I think Richard's solution is the best, that you have a separate database where you get the rich text snippets, and use the AppendRTItem method of the NotesRichText class to put it into your email.
Thank you all guys!
But I found exactly what I wanted, without having to recreate the whole Email everytime:
Sub EditSelectedMail()
Dim NSession As Object
Dim NDatabase As Object
Dim NUIWorkspace As Object
Dim NUIdoc As Object
Set NSession = CreateObject("Notes.NotesSession")
Set NUIWorkspace = CreateObject("Notes.NotesUIWorkspace")
Set NDatabase = NSession.GetDatabase("", "")
If Not NDatabase.IsOpen Then NDatabase.OPENMAIL
Set NUIdoc = NUIWorkspace.EDITDOCUMENT(True)
With NUIdoc
'Find the marker text in the Body item
.GotoField ("Body")
.FINDSTRING "**PASTE EXCEL CELLS HERE**"
'Copy Excel cells to clipboard
Sheets("Sheet1").Range("A1:E6").Copy
'Create a temporary Word Document
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = False
WordApp.Documents.Add
'Paste into Word document and copy to clipboard
With WordApp.Selection
.PasteSpecial DataType:=10
'Enum WdPasteDataType: 10 = HTML; 2 = Text; 1 = RTF
.WholeStory
.Copy
End With
'Paste from clipboard (Word) to Lotus Notes document
.Paste
Application.CutCopyMode = False
'WordApp.Quit SaveChanges:=False
Set WordApp = Nothing
End With
End Sub
I just select my "template", copy it into a new message, and then run the macro.

How can I specify a "reply-to" address without specifying a database in lotus notes, through Excel VBA?

I have the code to send an email through Lotus Notes 7. It works well. From what I've seen there are two methods of doing this, and only one of them requires that you specify a database. I'm using the method that doesn't require that, because multiple people will be using this code, and most of them don't know how to modify or read VB.
What I want to do is set the reply-to portion of the email. I have tried every variation I can think of, and nothing seems to work (different errors for different ways).
Thanks in advance,
Aaron.
Sub Email_Atrack_Report(SubjectLine As String, _
AgentOracle As String, TMAddress As String)
Dim NSession As Object
Dim NUIWorkSpace As Object
Dim NDoc As Object
Dim NUIdoc As Object
Set NSession = CreateObject("Notes.NotesSession")
Set NUIWorkSpace = CreateObject("Notes.NotesUIWorkspace")
Set NDoc = NUIWorkSpace.ComposeDocument("", "", "Memo")
Set NUIdoc = NUIWorkSpace.CURRENTDOCUMENT
With NUIdoc
.FieldSetText "EnterSendTo", AgentOracle & "#Company.com"
.FieldSetText "EnterCopyTo", TMAddress
.FieldSetText "Subject", SubjectLine
.FieldSetText "Body", "**PASTE Atrack HERE**"
.GotoField ("Body")
.FINDSTRING "**PASTE Atrack HERE**"
Sheets("EmailOutput").Range("MessageBody").Copy
.Paste
.send
.Close
End With
Set NUIdoc = Nothing
Set NDoc = Nothing
Set NUIWorkSpace = Nothing
Set NSession = Nothing
End Sub
You can use the Principal field to specify an address that will show up as the "From" address. I don't believe there is a way to set this via NotesUIDocument, but you should be able to get the mail database using the NotesDatabase.OpenMail method.
Set session = CreateObject("Notes.NotesSession")
Set maildb = session.getDatabase("", "")
Call maildb.OpenMail
If Not maildb.IsOpen Then Call maildb.Open("", "")
Set maildoc = maildb.createdocument
Set body = maildoc.createrichtextitem("body")
Call body.AppendText( Sheets("EmailOutput").Range("MessageBody").Text )
Call maildoc.replaceitemvalue("form", "memo")
Call maildoc.replaceitemvalue("subject", subject)
Call maildoc.replaceitemvalue("principal", "reply-to-this-user")
Call maildoc.send(false,recipient)
There a two ways to solve this, building the document and use the send method, or copy the document to the mail.box.
A good way to start is to read this blog entry by Jake Howlett
These are the items that can be used in the email:
Principal
iNetFrom
DisplaySent
ErrorsTo
ReplyTo
CopyTo
BlindCopyTo
SendTo
You should just need to set the "ReplyTo" item on the document, as in:
.FieldSetText "ReplyTo", "address#company.com"