with the function below, I have the option of sending e-mails from Excel via IBM Notes. Basically, it works very well. However, I recently had to revise the code, as the message text was always inserted under the IBM Notes signature. I was able to solve this problem, but unfortunately two problems have now emerged that I did not had before.
I am grateful for every tip and every help!
UPDATE 21.12.2021 21:30: #Tode I've followed your instructions but the problems are still there. May be I've failed to put the codelines in the right order?
The problems
The "Save" function no longer works, i.e. IBM Notes also saves the e-mail in the "Sent" folder if I do not want it (parameter blnSaveEMail = false).
The second problem has to do with my work context: I have two email accounts. A personal service e-mail address jdoe#company.com (mailfile: jdoe.nsf) and a branch e-mail address mybranch#company.de (mailfile: mybranch.nsf). As far as I could determine, both mail files are in the same base directory. If I use the code below with my personal e-mail, the parameter blnQuickSend = true works without problems, if I use my branch e-mail address, IBM Notes asks me whether I want to save the changes, although I would like to send an e-mail without asking.
I hope I was able to describe my issue clearly and understandably. I thank you for your attention!
Warm greetings from Dresden
Sergeij
PS: I'am a german native :), thankfully Google helped me a lot to translate my problem in english.
The code
Public Function Send_EMail( _
varRecipient As Variant, _
varCopyTo As Variant, _
varBlindcopyTo As Variant, _
strSubject As String, _
strMessage As String, _
strAttachement As String, _
Optional blnSaveEMail As Boolean = True, _
Optional blnQuickSend As Boolean = False, _
Optional strAlternative_Mailfile As String _
) As Boolean
Dim objLotusNotes As Object
Dim objMaildatabase As Object 'Die Maildatabase
Dim strMailServer As String 'Der Mailserver
Dim strMailFile As String ' Die Maildatei
Dim objEMail As Object 'Die E-Mail in IBM Notes
Dim objAttachement As Object 'Das Anlage Richtextfile Object
Dim objSession As Object 'Die Notes Session
Dim objEmbedded As Object 'Attachement
Dim arrAttachements() As String 'Liste mehrere Anhänge
Dim lngIndex As Long
Dim strFilepath As String
Dim objNotesfield As Object 'Datenfeld in IBM Notes
Dim objCurrentEMail As Object 'Aktuelle E-Mail
'Start an IBM Notes Session
Set objSession = CreateObject("Notes.NotesSession")
'Open IBM-Notes-Database
strMailServer = objSession.GetEnvironmentString("MailServer", True)
If VBA.Len(strAlternative_Mailfile) = 0 Then
strMailFile = objSession.GetEnvironmentString("MailFile", True)
Else
strMailFile = "mail/" & strAlternative_Mailfile
End If
Set objMaildatabase = objSession.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 objMaildatabase.IsOpen Then objMaildatabase.OPENMAIL
'Create new email
Set objEMail = objMaildatabase.CREATEDOCUMENT
'set saveoption
objEMail.ReplaceItemValue "SAVEOPTIONS", "0"
'Put content in fields
Set objNotesfield = objEMail.APPENDITEMVALUE("Subject", strSubject)
Set objNotesfield = objEMail.APPENDITEMVALUE("SendTo", varRecipient)
Set objNotesfield = objEMail.APPENDITEMVALUE("BlindCopyTo", varBlindcopyTo)
Set objNotesfield = objEMail.APPENDITEMVALUE("CopyTo", varCopyTo)
'Load workspace
Set objLotusNotes = CreateObject("Notes.NotesUIWorkspace")
'Add attachements
arrAttachements = VBA.Split(strAttachement, ";")
For lngIndex = LBound(arrAttachements) To UBound(arrAttachements)
strFilepath = arrAttachements(lngIndex)
If strFilepath <> "" And VBA.Dir(strFilepath) <> "" Then
Set objAttachement = objEMail.CREATERICHTEXTITEM("Attachment" & lngIndex)
Set objEmbedded = _
objAttachement.EMBEDOBJECT(1454, "", strFilepath, "Attachment" & lngIndex)
End If
Next
'Open eMail in frontend and assign to NotesUIDocument variable
Set objCurrentEMail = objLotusNotes.EDITDOCUMENT(True, objEMail)
'Put content into email
objCurrentEMail.GotoField "Body"
objCurrentEMail.InsertText strMessage
'Check, whether the email should be sent immediately or not
If blnQuickSend = True Then
'Send email
objCurrentEMail.Send
'Save email, if requested
If blnSaveEMail Then objCurrentEMail.Save
'Close email
objCurrentEMail.Close
End If
'Return TRUE
Send_EMail = True
End Function
Ok... where should I start... there are some logical errors in your code based on not understanding the methods you use and the difference between frontend- and backend- classes...
Let's begin at the top:
'Check whether the maildatabase is open or not 'Throws an error,
'if the database is not open
If Not objMaildatabase.IsOpen Then objMaildatabase.OPENMAIL
Your comment is wrong. No error is thrown at all. 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.
'Create new email-document
objLotusNotes.EDITDOCUMENT True, objEMail
Again: Comment is wrong. What this command does is: It opens the email that you created in backend (represented by variable objEMail) in the frontend.
'Select the current email
Set objCurrentEMail = objLotusNotes.CurrentDocument
and assigns it to a NotesUIDocument- frontend- variable (select the current email is wrong).
As "EDITDOCUMENT" already returns as NotesUIDocument, you could shorten this like this:
'Open eMail in frontend and assign to NotesUIDocument variable
Set objCurrentEMail = objLotusNotes.EDITDOCUMENT(True, objEMail)
After having created a frontenddocument you still continue to manipulate the (now linked) backend document. You should move the creation of the frontend all the way down to the end of your code as having a document open in frontend does not work well with manipulating the same document in backend, especially when handling NotesRichtextItems and attachments. So move the above lines just below the for- loop.
'Set if email should be saved or not
objEMail.SAVEMESSAGEONSEND = blnSaveEMail
Yes... but no: You set the property SAVEMESSAGEONSEND to the backend document objEMail. Unfortunately the frontend- document objCurrentEMail does not care at all for this. To have your code obey this option, you would have to use the send- method of objEMail, not the send- method of objCurrentEMail.
If you want the frontend to not save a document that it sends, you need to do it differently by setting a field called "SAVEOPTIONS" to "0":
objEMail.ReplaceItemValue( "SAVEOPTIONS", "0" )
'Send email
objCurrentEMail.Send False, varRecipient
regarding your comment: almost... unfortunately you try the NotesDocument backend method "send" (that has 2 parameters) against the NotesUIDocument- Object "objCurrentEMail.
NotesUIDocument has a send method as well, but it does not have any parameters..normally an error should be thrown here....
EITHER you try to send the backend:
objEMail.Send False, varRecipient
OR you send it in the frontend:
objCurrentEMail.Send
Your "objCurrentEMail.Close" will always ask you if you want to save the document unless you have set SAVEOPTIONS = "0". If you really want to save the document after sending, use
objCurrentEMail.Save
before the close.
Hope that helps you sort out some of the issues.
Related
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.
In my excel spreadsheet I have column A and column B. In column A I have email addresses, in column B I have unique variables. The code below is designed to look into an inbox, compare if any of the subject lines match the unique variable in column B and if they do then forward the email to the email address from column A of that unique variable. This is the code currently:
Public Sub Forward_Email(findSubjectLike As String, forwardToEmailAddresses As String)
Dim NSession As Object
Dim NMailDb As Object
Dim NViewObj As Object
Dim NInboxView As Object
Dim NDocument As Object
Dim NUIWorkspace As Object
Dim NUIDocument As Object
Dim NFwdUIDocument As Object
Set NSession = CreateObject("Lotus.NotesSession")
Call NSession.Initialize("password")
Set NUIWorkspace = CreateObject("Notes.NotesUIWorkspace")
Set NMailDb = NSession.GetDatabase("", "TEST.nsf")
Set NViewObj = NMailDb.GetView("Inbox")
Set NDocument = Find_Document(NInboxView, findSubjectLike)
If Not NDocument Is Nothing Then
Set NUIDocument = NUIWorkspace.EditDocument(False, NDocument)
NUIDocument.Forward
Set NFwdUIDocument = NUIWorkspace.CurrentDocument
Sleep 100
NFwdUIDocument.GoToField "To"
Sleep 100
NFwdUIDocument.InsertText forwardToEmailAddresses
NFwdUIDocument.GoToField "Body"
NFwdUIDocument.InsertText "This email was forwarded at " & Now
NFwdUIDocument.InsertText vbLf
NFwdUIDocument.Send
NFwdUIDocument.Close
Do
Set NUIDocument = NUIWorkspace.CurrentDocument
Sleep 100
DoEvents
Loop While NUIDocument Is Nothing
NUIDocument.Close
Else
MsgBox vbCrLf & findSubjectLike & vbCrLf & "not found in Inbox"
End If
Set NUIDocument = Nothing
Set NFwdUIDocument = Nothing
Set NDocument = Nothing
Set NMailDb = Nothing
Set NUIWorkspace = Nothing
Set NSession = Nothing
End Sub
Private Function Find_Document(NView As Object, findSubjectLike As String) As Object
Dim NThisDoc As Object
Dim thisSubject As String
Set Find_Document = Nothing
Set NThisDoc = NView.GetFirstDocument
While Not NThisDoc Is Nothing And Find_Document Is Nothing
thisSubject = NThisDoc.GetItemValue("Subject")(0)
If LCase(thisSubject) = LCase(findSubjectLike) Then Set Find_Document = NThisDoc
Set NThisDoc = NView.GetNextDocument(NThisDoc)
Wend
End Function
The issue is that now the code looks within the user inbox of the logged in user (in this case being me). I have another inbox open (lets call it TEST) am I able to specify this code to view the information from the open TEST inbox instead. Right now it compares the information from my inbox with TEST as it triggers the error line "not found in inbox".
What it does currently is it looks for the unique variable within my finds it, then tries to compare with TEST for that subject line to forward it. I want it to both look in TEST and then compare with TEST.
You state "The issue is that now the code looks within the user inbox of the logged in use". It doesn't. It uses NSession.CurrentDatabase,, and your NotesSession is loaded into VBA using the Notes OLE classes. It's the OLE classes becuase you are using Notes.NotesSession instead of Lotus.NotesSesion. In the COM classes, that are loaded if you use Lotus.NotesSession., the CurrentDatabase property isn't defined. In the OLE classes, I honestly don't know what the expected behavior is in the OLE classes, but I know for sure that you can't rely on the current database always being the current user's mailbox database.
In any case, if you want to access another user's Inbox, first you have to open that user's mailbox database. To do that, you have to know what server that mailbox database is on, and what the path to the mailbox is on that server. You do that by writing code to read that information from that user's Person document in the Domino Directory, or you can put that information into your spreadsheet for each user. With that, you can use NotesSession.GetDatabase, open the database, and access it more or less the way you are accessing your own mailbox database.
I know about topics dealing with similar problem but none of them solves directly my problem (or at least I don't see it). I am using following code:
Sub SendEmailUsingCOM()
'*******************************************************************************************
' Unlike OLE automation, one can use Early Binding while using COM
' To do so, replace the generic "object" by "commented" UDT
' Set reference to: Lotus Domino Objects
'*******************************************************************************************
Dim nSess As Object 'NotesSession
Dim nDir As Object 'NotesDbDirectory
Dim nDb As Object 'NotesDatabase
Dim nDoc As Object 'NotesDocument
Dim nAtt As Object 'NotesRichTextItem
Dim vToList As Variant, vCCList As Variant, vBody As Variant
Dim vbAtt As VbMsgBoxResult
Dim sFilPath As String
Dim sPwd As String
'*******************************************************************************************
'To create notesession using COM objects, you can do so by using.
'either ProgID = Lotus.NotesSession
'or ClsID = {29131539-2EED-1069-BF5D-00DD011186B7}
'Replace ProgID by the commented string below.
'*******************************************************************************************
Set nSess = CreateObject("Lotus.NotesSession") 'New:{29131539-2EED-1069-BF5D-00DD011186B7}
'*******************************************************************************************
'This part initializes the session and creates a new mail document
'*******************************************************************************************
sPwd = Application.InputBox("Type your Lotus Notes password!", Type:=2)
Call nSess.Initialize(sPwd)
Set nDir = nSess.GetDbDirectory("")
Set nDb = nDir.OpenMailDatabase
Set nDoc = nDb.CreateDocument
'*******************************************************************************************
'If you want to send it to multiple recipients then use variant array to get the names from
'the specified range as below
'Add / Remove Comment mark from vCCList as per your needs.
'*******************************************************************************************
vToList = Application.Transpose(Range("A1").Resize(Range("A" & Rows.Count).End(xlUp).Row).Value)
vCCList = Application.Transpose(Range("B1").Resize(Range("B" & Rows.Count).End(xlUp).Row).Value)
'*******************************************************************************************
'If you want to send it to multiple recipients then use variant array to get the names from
'the specified range as below
'Add / Remove Comment mark from vCCList as per your needs.
'*******************************************************************************************
With nDoc
Set nAtt = .CreateRichTextItem("Body")
Call .ReplaceItemValue("Form", "Memo")
Call .ReplaceItemValue("Subject", "Test Lotus Notes Email using COM")
With nAtt
.AppendText (Range("C2").Value)
'Decide if you want to attach a file.
vbAtt = MsgBox("Do you want to attach document?", vbYesNo, "Attach Document")
Select Case vbAtt
Case 6
.AddNewLine
.AppendText ("********************************************************************")
.AddNewLine
sFilPath = Application.GetOpenFilename
Call .EmbedObject(1454, "", sFilPath) '1454 = Constant for EMBED_ATTACHMENT
Case 7
'Do Nothing
End Select
End With
Call .ReplaceItemValue("CopyTo", vCCList)
Call .ReplaceItemValue("PostedDate", Now())
Call .Send(False, vToList)
End With
End Sub
The code stops at Set nSess = CreateObject("Lotus.NotesSession") saying Run-time error 429: ActiveX component can't create object
I saw some discussions about missing nnotes.dll but when I try to add it using Tools>References> and browse to the nnotes.dll file, it says "Can't add a reference to the specified file"
For sure I miss some basic knowledge, but I would just love to make it work and send specific ranges in excel via email.
Do you know, ideally step by step, what I should do?
I'm trying to edit an existing notes document via VBA and then send it automatically.
I've already created pretty much everything - just need to figure out how exactly I can add a certain text at a certain position within the richtext element.
Sub sendMail() 'inputIndID As String, inputRecipient As String, inputIncDescription As String)
Dim mailDB As Object
Dim mailToSend As Object
Dim body As Object
Dim session As Object
Dim view As Object
Dim entries As Object
Dim docIDs() As String
Dim docSubjects() As String
Dim incID, incDescription As String
Dim element As String
Dim bodyNavigator As Object
incID = "<INC-ID>"
incDescription = "<INC-Betreff>"
'Start a session to notes
Set session = CreateObject("Notes.NotesSession")
'This line prompts for password of current ID noted in Notes.INI
'Call Session.Initialize
'or use below to supply password of the current ID
'Open the mail database in notes
Set mailDB = session.GetDatabase("Eschen10/Presta", "mail\qcpcsupport.nsf")
If mailDB.IsOpen = False Then
Call mailDB.Open
End If
'Search for all the messages in the folder "Umfrage"
Set view = mailDB.GetView("Umfrage")
Set entries = view.AllEntries
If entries.Count = 0 Then
MsgBox "Keine Nachricht im Umfrage Ordner."
End If
ReDim docIDs(entries.Count - 1)
ReDim docSubjects(entries.Count - 1)
Set entry = entries.GetFirstEntry
Do Until entry Is Nothing
docIDs(i) = entry.NoteID
docSubjects(i) = entry.Document.GetItemValue("Subject")(0) 'based on standard R5 mail template column order
'If the documents title matches the searched one it will be taken and worked with later
If docSubjects(i) = "Umfrage PC-Support Servicequalität" Then
Set mailToSend = entry.Document
End If
i = i + 1
Set entry = entries.GetNextEntry(entry)
Loop
'Set the recipient
Call mailToSend.ReplaceItemValue("SendTo", "simon.hartmann#thyssenkrupp.com")
'Get and change the body content
Set body = mailToSend.GetFirstItem("Body")
Set bodyNavigator = body.CreateNavigator()
'Replace markers with correct text
element = "<"
If (body.Type = RICHTEXT) Then
Call bodyNavigator.FindFirstString(element)
Call body.BeginInsert(bodyNavigator, True)
Call body.AppendText("123456")
Call bodyNavigator.FindNextString(element)
Call body.BeginInsert(bodyNavigator, True)
Call body.AppendText("Antrag Guest WLAN")
End If
'Example to save the message (optional)
mailToSend.SaveMessageOnSend = True
'Send the document
'Gets the mail to appear in the Sent items folder
mailToSend.Save True, False
Call mailToSend.ReplaceItemValue("PostedDate", Now())
Call mailToSend.Send(False)
'changes the body back and saves the document in the folder "Umfrage" so it can be resent next time
Call mailToSend.PutInFolder("Umfrage")
'Clean Up
Set mailDB = Nothing
Set mailToSend = Nothing
Set body = Nothing
Set session = Nothing
End Sub
Currently I am failing at the following line:
Call body.BeginInsert(bodyNavigator, True)
I get the error - Runtime Error 13 - Type Mismatch
I also already tried to give all variables the correct data type of Lotus Notes - but then I have the problem with each of those variables.
Is there a way I can "force" the bodynavigator to be of the correct type? Or where do I have my mistake? Am I missing a library or anything?
Thanks in advance!!!
Regards,
Simon
Did you read the documentation for NotesRichtextNavigator?
You find the following information there:
Parameters
target$
String. The search string.
options$
Long. Any of the following. Specify multiple options by combining them with addition or logical ORs.
RT_FIND_ACCENTINSENSITIVE (4) (default is accent sensitive)
RT_FIND_CASEINSENSITIVE (1) (default is case sensitive)
RT_FIND_PITCHINSENSITIVE (2) (default is pitch insensitive)
So: Your second parameter "true" is simply the wrong type... therefor the type mismatch...
I'm trying to send an Outlook email from Excel 2010 using VBA.
Most answers on Stack Overflow don't seem to have a method of using VBA to avoid the Outlook security warning, nor for Outlook/Excel 2010.
Do any free methods exist? The Redemption method won't be a viable option, unless it is easy to install on 10 machines in a large company.
How I send emails:
Dim emailAddr As String
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = "xxxx#xxxx.edu"
.Subject = "Demande"
.HtmlBody = CombinedValueHtml
.Send
End With
Set OutMail = Nothing
Set OutApp = Nothing
Exit Sub
This is a partial answer. I have made it a Community Wiki answer in the expectation that someone else can explain the final part which I cannot get to work.
This web page, http://msdn.microsoft.com/en-us/library/office/aa155754(v=office.10).aspx , explains the first three parts of the process. It was written in 1999 so cannot be followed exactly because it refers to old versions of Windows and Office.
The first step is to add Digital Signature for VBA Projects to your Office installation although I found it under Shared Tools rather than Office Tools. Don't make the mistake of just adding Digital Signature for VBA Projects to Outlook because, as I discovered, that means you uninstall Word, Excel, etc.
The second step is to run Selfcert.exe to create a digital certificate in your own name.
The third step is to open Outlook's VBA editor, select Tools then Digital Certificate then Choose to sign the project with your certificate.
With these steps you can suppress the warning that Outlook contains macros but this does not suppress that warning that a macro is accessing emails. To suppress that warning, you need a fourth step which is to place your certificate within the Trusted Root Certificate Authorities Store. This web page http://technet.microsoft.com/en-us/library/cc962065.aspx explains about the Certification Authority Trust Model but I cannot successfully use Microsoft Management Console to achieve the fourth step.
Instead .send use the following:
.Display 'displays outlook email
Application.SendKeys "%s" 'presses send as a send key
note: be careful when using display keys, if you move the mouse and click while the program is running it can change whats going on. also outlook will display on ur screen and send.. if you working on something else's and this bothers you, yea.. not the best idea
The Redemption method won't be a viable option, unless it is easy to
install on 10 machines inside of a large company.
You can use RedemptionLoader (I am its author) - it loads the dll directly and does no require the dll to be installed using the registry.
It is either Extended MAPI in C++ or Delphi, Redemption (I am its author - wraps Extended MAPI and can be used form any language) or a utility like ClickYes.
If you don't send the message immediately but just display it and let the user do modifications (if any) and let them press the send button theirselves, this would work:
i.e. use
.Display
instead of
.Send
I explained how you can use vba to send emails in this answer You will find a macro that I use extensively in my daily work.
Following recomendations from #Floern, here is the explanation:
In order to insert images (signature as images) you could use the following code:
Step 1. Copy this code an paste in class module and name that class module like "MailOptions"
Private Message As CDO.Message
Private Attachment, Expression, Matches, FilenameMatch, i
Public Sub PrepareMessageWithEmbeddedImages(ByVal FromAddress, ByVal ToAddress, ByVal Subject, ByVal HtmlContent)
Set Expression = CreateObject("VBScript.RegExp")
Expression.Pattern = "\<EMBEDDEDIMAGE\:(.+?)\>"
Expression.IgnoreCase = True
Expression.Global = False 'one match at a time
Set Message = New CDO.Message
Message.From = FromAddress
Message.To = ToAddress
Message.Subject = Subject
'Find matches in email body, incrementally increasing the auto-assigned attachment identifiers
i = 1
While Expression.Test(HtmlContent)
FilenameMatch = Expression.Execute(HtmlContent).Item(0).SubMatches(0)
Set Attachment = Message.AddAttachment(FilenameMatch)
Attachment.Fields.Item("urn:schemas:mailheader:Content-ID") = "<attachedimage" & i & ">" ' set an ID we can refer to in HTML
Attachment.Fields.Item("urn:schemas:mailheader:Content-Disposition") = "inline" ' "hide" the attachment
Attachment.Fields.Update
HtmlContent = Expression.Replace(HtmlContent, "cid:attachedimage" & i) ' update the HTML to refer to the actual attachment
i = i + 1
Wend
Message.HTMLBody = HtmlContent
End Sub
Public Sub SendMessageBySMTP(ByVal SmtpServer, ByVal SmtpUsername, ByVal SmtpPassword, ByVal UseSSL)
Dim Configuration
Set Configuration = CreateObject("CDO.Configuration")
Configuration.Load -1 ' CDO Source Defaults
Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = SmtpServer
'Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = SmtpPort
Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 30
If SmtpUsername <> "" Then
Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = SmtpUsername
Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = SmtpPassword
End If
Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = UseSSL
Configuration.Fields.Update
Set Message.Configuration = Configuration
Message.Send
End Sub
Step 2. In an standar module you will elaborate your .html content and instantiate a object from the class:
public sub send_mail()
Dim signature As String
dim mail_sender as new MailOptions 'here you are instantiating an object from the class module created previously
dim content as string
signature = "C:\Users\your_user\Documents\your_signature.png"
content = "<font face=""verdana"" color=""black"">This is some text!</font>"
content = content & "<img src=""<EMBEDDEDIMAGE:" & signature & " >"" />"
mail_sender.PrepareMessageWithEmbeddedImages _
FromAddress:="chrism_mail#blablabla.com", _
ToAddress:="addressee_mail#blablabla.com", _
Subject:="your_subject", _
HtmlContent:=content
'your_Smtp_Server, for example: RelayServer.Contoso.com
correos.SendMessageBySMTP "your_Smtp_Server", "your_network_user_account", "your_network_user_account_password", False
end sub