Link to home
Start Free TrialLog in
Avatar of kevink34
kevink34Flag for United States of America

asked on

Using Lotus Notes/MS Outlook and MAPI Control To Send Emails

I am trying to create a Visual Basic program which will send emails using either Lotus Notes or Outlook.  The application must be able to handle both email applications within itself (ie  Not one program for Lotus Notes and another for Outlook).
We are able to launch Lotus Notes and enter the "body" text but am unable to enter the "To:" or "CC:" fields.  We are also unable to Send the email and we are unable to close Lotus Notes.  However, when Lotus Notes launches, it prompts the user for the password.  I want to pass the password from the VB program to Lotus Notes.

I am using the 'Microsoft MAPI Controls 6.0" component.

Here is the Logon code I currently have:

Private Function LogOn() As Boolean
On Error GoTo eh
    ' If a session is already started,
    ' exit sub.
    If mapSess.NewSession Then
        MsgBox "Session already established"
        GoTo ex
    End If
    If txtUserName.Text = "" Then
        MsgBox "You must provide a User Name"
        GoTo ex
    End If
    If txtPassword.Text = "" Then
        MsgBox "You must provide a Password"
        GoTo ex
    End If
    With mapSess
        ' Set DownLoadMail to False to prevent immediate download.
        .DownLoadMail = False
        .LogonUI = False ' Use the underlying email system's logon UI.
        .UserName = txtUserName.Text
        .Password = txtPassword.Text
        .SignOn ' Signon method.
        ' Set NewSession to True and set0
        ' variable flag to true
        .NewSession = True
        mblnNewSession = .NewSession
        mapMess.SessionID = .SessionID ' You must set this before continuing.
    End With
    LogOn = True
ex:
    Exit Function
eh:
    If Err.Number = 32003 Then
        MsgBox "Canceled Login"
        LogOn = False
    Else
        MsgBox "Error " & Err.Number & ": " & Err.Description
    End If
    Resume ex
End Function
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is my logoff code:

Private Sub LogOff()
On Error GoTo eh
    ' Logoff the MapSessions control.
    With mapSess
        .SignOff ' Close the session.
        .NewSession = False ' Flag for new session.
        mblnNewSession = .NewSession ' Reset flag.
    End With
ex:
    Exit Sub
eh:
    MsgBox "Error " & Err.Number & ": " & Err.Description
    Resume ex
End Sub
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
And here is the code I am using to send the message:

Private Sub SendMessage()
    On Error GoTo eh
    Dim strMessage As String
    Dim strRecip1 As String
    Dim strRecip2 As String
    If Text1.Text = "" Then
        MsgBox "You must provide a primary recipient"
        GoTo ex
    Else
        strRecip1 = Text1.Text
    End If
    If Text2.Text <> "" Then
        strRecip2 = Text2.Text
    End If
    strMessage = "Message Sent " & Now
    mapMess.Compose
    mapMess.RecipIndex = 0
    mapMess.RecipType = 1
    mapMess.RecipAddress = strRecip1
'    mapMess.ResolveName
    If strRecip2 <> "" Then
        mapMess.RecipIndex = 1
        mapMess.RecipType = 1
        mapMess.RecipAddress = strRecip2
'        mapMess.ResolveName
    End If
    mapMess.MsgSubject = "PeopleSoft Background Check Email Test"
    mapMess.MsgNoteText = strMessage
    mapMess.Send False
ex:
    Exit Sub
eh:
    MsgBox "Error " & Err.Number & ": " & Err.Description
    Resume ex
End Sub

Any help is greatly appreciated.
Thanks!
Avatar of thman
thman
Flag of United States of America image

I currently don't have Lotus Notes environment to do any test about that. I'll be very interested in doing that once I get a chance.

However, are you sure there is also a copy of notes.ini in the windows directory other than users' data directory? When you access Lotus Notes through application outside of Lotus Notes, it sometimes requires to check notes.ini in windows directory.

Is it okay with your application to send email through Notes API? I mean whether it's okay or not for you to write two different programs in one application to handle Lotus Notes and outlook.
ASKER CERTIFIED SOLUTION
Avatar of TimCottee
TimCottee
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kevink34

ASKER

Thanks for the info!

TimCottee, The code is great!  I am able to use it to send but there are two minor issues.
1.  Where I work, they require a user id and password when you open a session of Lotus Notes.  I am unable to determine how to get those variables into Notes.  I do not want the users to have to enter their user id and password.
2.  I am unable to close the object.  When the email is sent, Notes is still open and I would like to close it.

As always, any help is really appreciated!
Avatar of Richie_Simonetti
I can solve your problem with Lotus , but not with both.
To solve with Lotus only, see this:


www.angelfire.com/realm/vb-shared/index.html
Richie,
Thanks for the info but I am unable to get the zip file.  Angelfire does not allow it?!?!?!?!?!
Yeah!, sometimes yes and sometimes not!! >(
I will post entire code here: Wich version of Notes do you use?
4.x or 5.x
Here we start:
'code to frmInit

VERSION 5.00
Begin VB.Form frmInit
   BorderStyle     =   4  'Fixed ToolWindow
   Caption         =   "Choose an option"
   ClientHeight    =   1515
   ClientLeft      =   45
   ClientTop       =   285
   ClientWidth     =   2985
   LinkTopic       =   "Form1"
   MaxButton       =   0   'False
   MinButton       =   0   'False
   ScaleHeight     =   1515
   ScaleWidth      =   2985
   ShowInTaskbar   =   0   'False
   StartUpPosition =   3  'Windows Default
   Begin VB.CommandButton Command1
      Caption         =   "&Cancel"
      Height          =   315
      Index           =   1
      Left            =   1680
      TabIndex        =   4
      Top             =   1080
      Width           =   1215
   End
   Begin VB.CommandButton Command1
      Caption         =   "&OK"
      Height          =   315
      Index           =   0
      Left            =   1680
      TabIndex        =   3
      Top             =   660
      Width           =   1215
   End
   Begin VB.OptionButton Option1
      Caption         =   "COM (Lotus 5.x)"
      Height          =   495
      Index           =   1
      Left            =   60
      TabIndex        =   1
      Top             =   1020
      Width           =   1575
   End
   Begin VB.OptionButton Option1
      Caption         =   "OLE (Lotus 4.x)"
      Height          =   495
      Index           =   0
      Left            =   60
      TabIndex        =   0
      Top             =   480
      Width           =   1575
   End
   Begin VB.Label Label1
      Caption         =   "Please, choose an option to work with:"
      Height          =   315
      Left            =   120
      TabIndex        =   2
      Top             =   120
      Width           =   2775
      WordWrap        =   -1  'True
   End
End
Attribute VB_Name = "frmInit"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit

Private Sub Command1_Click(Index As Integer)
Select Case Index
Case 0
    If Option1(0).Value Then
        frmNotesOLE.Show
    ElseIf Option1(1).Value Then
        frmNotesCOM.Show
    End If
End Select

Unload Me
End Sub


'Code to frmNotesCOM

VERSION 5.00
Object = "{F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0"; "COMDLG32.OCX"
Begin VB.Form frmNotesCOM
   BorderStyle     =   1  'Fixed Single
   Caption         =   "Notes by COM"
   ClientHeight    =   5070
   ClientLeft      =   45
   ClientTop       =   330
   ClientWidth     =   6270
   Icon            =   "frmNotesCOM.frx":0000
   LinkTopic       =   "Form1"
   MaxButton       =   0   'False
   MinButton       =   0   'False
   ScaleHeight     =   5070
   ScaleWidth      =   6270
   StartUpPosition =   3  'Windows Default
   Begin MSComDlg.CommonDialog CDlg
      Left            =   300
      Top             =   2340
      _ExtentX        =   847
      _ExtentY        =   847
      _Version        =   393216
   End
   Begin VB.TextBox Text1
      Height          =   1635
      Index           =   3
      Left            =   960
      MultiLine       =   -1  'True
      ScrollBars      =   2  'Vertical
      TabIndex        =   7
      Top             =   1440
      Width           =   5175
   End
   Begin VB.Frame Frame1
      Caption         =   "Compose:"
      Height          =   5055
      Left            =   0
      TabIndex        =   0
      Top             =   0
      Width           =   6255
      Begin VB.ListBox lstFiles
         Height          =   1815
         Left            =   960
         TabIndex        =   12
         Top             =   3120
         Width           =   3435
      End
      Begin VB.CommandButton cmdSend
         Caption         =   "&Send"
         Height          =   315
         Left            =   4440
         TabIndex        =   11
         Top             =   4620
         Width           =   1695
      End
      Begin VB.CommandButton Command1
         Caption         =   "Attach  All in Folder"
         Height          =   315
         Index           =   1
         Left            =   4440
         TabIndex        =   10
         Top             =   3480
         Width           =   1695
      End
      Begin VB.CommandButton Command1
         Caption         =   "Attach one file"
         Height          =   315
         Index           =   0
         Left            =   4440
         TabIndex        =   9
         Top             =   3120
         Width           =   1695
      End
      Begin VB.TextBox Text1
         Height          =   315
         Index           =   2
         Left            =   960
         TabIndex        =   6
         Top             =   1080
         Width           =   5175
      End
      Begin VB.TextBox Text1
         Height          =   315
         Index           =   1
         Left            =   960
         TabIndex        =   4
         Top             =   660
         Width           =   5175
      End
      Begin VB.TextBox Text1
         Height          =   315
         Index           =   0
         Left            =   960
         TabIndex        =   2
         Top             =   240
         Width           =   5175
      End
      Begin VB.Label Label1
         AutoSize        =   -1  'True
         BackStyle       =   0  'Transparent
         Caption         =   "Message:"
         Height          =   195
         Index           =   3
         Left            =   180
         TabIndex        =   8
         Top             =   1560
         Width           =   690
      End
      Begin VB.Label Label1
         AutoSize        =   -1  'True
         BackStyle       =   0  'Transparent
         Caption         =   "Subject:"
         Height          =   195
         Index           =   2
         Left            =   180
         TabIndex        =   5
         Top             =   1140
         Width           =   585
      End
      Begin VB.Label Label1
         AutoSize        =   -1  'True
         BackStyle       =   0  'Transparent
         Caption         =   "cc:"
         Height          =   195
         Index           =   1
         Left            =   180
         TabIndex        =   3
         Top             =   720
         Width           =   225
      End
      Begin VB.Label Label1
         AutoSize        =   -1  'True
         BackStyle       =   0  'Transparent
         Caption         =   "To:"
         Height          =   195
         Index           =   0
         Left            =   180
         TabIndex        =   1
         Top             =   300
         Width           =   240
      End
   End
End
Attribute VB_Name = "frmNotesCOM"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Dim COMSess As Domino.NotesSession
Dim COMDB As Domino.NotesDatabase
Dim FilePath As String

Private Sub cmdSend_Click()
Dim Doc As NotesDocument
Dim NItem As NotesItem

'Creates new document/message
Set Doc = COMDB.CreateDocument
    With Doc
        ' Creates Rich body item and adds all headers
        Set NItem = Doc.CreateRichTextItem("BODY")
        .AppendItemValue "Form", "memo"
        .AppendItemValue "SendTo", Text1(0).Text
        .AppendItemValue "CopyTo", Text1(1).Text
        .AppendItemValue "Subject", Text1(2).Text
        .AppendItemValue "BODY", Text1(3).Text
       
        ' Check is there is some files to attach to message
        ' if so, attaches them.
        If lstFiles.ListIndex <> -1 Then
            Dim obj As Object
            Dim i As Integer, UpperLstCount As Integer
            UpperLstCount = lstFiles.ListCount
            For i = 0 To UpperLstCount - 1
                lstFiles.Selected(i) = True
                Set obj = NItem.EmbedObject(EMBED_ATTACHMENT, "", lstFiles.Text)
            Next i
        End If
        .Send False
    End With

End Sub


Private Sub Command1_Click(Index As Integer)
lstFiles.Clear
Select Case Index
Case 0
    With CDlg
        .ShowOpen
        If .FileName <> "" Then
            lstFiles.AddItem .FileName
            lstFiles.Selected(0) = True
        End If
    End With
   
Case 1
    Dim strFiles As String
    FilePath = BrwFolder
        If FilePath <> "" Then
            strFiles = Dir$(FilePath & "*.*", vbArchive)
            Do While strFiles <> ""
                lstFiles.AddItem FilePath & strFiles
                '.Visible = True
                strFiles = Dir$()
            Loop
            lstFiles.Selected(0) = True
        End If
End Select
End Sub

Private Sub Form_Load()
' Creates new Notes session object and prompt user to
' enter servername, password and database mail.
' Prompt for password can be override if you pass password value
' as parameter of initialize method.
' This could be stored on registry/ini file to ask the
' user only the first time.
' I used inputbox for easy, you could add a form to get all
' values.
Set COMSess = New Domino.NotesSession

COMSess.Initialize InputBox$("Please enter Database password.", "Enter Password")
Set COMDB = COMSess.GetDatabase(InputBox$("Please enter Domino server name here.", "Server name", "FRE-AR-BA-H01"), _
                                    InputBox$("Please enter Domino database name here.", "Enter database name", "\mail\7\ARBA0137.nsf"), _
                                    False)
With COMDB
    If Not .IsOpen Then
        MsgBox "Unable to open Notes session.", vbCritical, "Init Error"
        Set COMDB = Nothing
        Set COMSess = Nothing
        Exit Sub
    End If
End With
End Sub


Private Sub Form_Unload(Cancel As Integer)
On Error Resume Next
' set objects variables to nothing
' and close session.
Set COMDB = Nothing
Set COMSess = Nothing
End
End Sub


'Code to frmNotesOLE

VERSION 5.00
Object = "{F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0"; "COMDLG32.OCX"
Begin VB.Form frmNotesOLE
   BorderStyle     =   1  'Fixed Single
   Caption         =   "Notes by OLE"
   ClientHeight    =   5070
   ClientLeft      =   45
   ClientTop       =   330
   ClientWidth     =   6270
   Icon            =   "frmNotesOLE.frx":0000
   LinkTopic       =   "Form1"
   MaxButton       =   0   'False
   MinButton       =   0   'False
   ScaleHeight     =   5070
   ScaleWidth      =   6270
   StartUpPosition =   3  'Windows Default
   Begin MSComDlg.CommonDialog CDlg
      Left            =   300
      Top             =   2340
      _ExtentX        =   847
      _ExtentY        =   847
      _Version        =   393216
      DefaultExt      =   "*.*"
      DialogTitle     =   "Attach file"
      FileName        =   "*.*"
      Filter          =   "*.*"
      InitDir         =   "curdir"
   End
   Begin VB.TextBox Text1
      Height          =   1635
      Index           =   3
      Left            =   960
      MultiLine       =   -1  'True
      ScrollBars      =   2  'Vertical
      TabIndex        =   7
      Top             =   1440
      Width           =   5175
   End
   Begin VB.Frame Frame1
      Caption         =   "Compose:"
      Height          =   5055
      Left            =   0
      TabIndex        =   0
      Top             =   0
      Width           =   6255
      Begin VB.ListBox lstFiles
         Height          =   1815
         Left            =   960
         TabIndex        =   12
         Top             =   3120
         Width           =   3435
      End
      Begin VB.CommandButton cmdSend
         Caption         =   "&Send"
         Height          =   315
         Left            =   4440
         TabIndex        =   11
         Top             =   4620
         Width           =   1695
      End
      Begin VB.CommandButton Command1
         Caption         =   "Attach  All in Folder"
         Height          =   315
         Index           =   1
         Left            =   4440
         TabIndex        =   10
         Top             =   3480
         Width           =   1695
      End
      Begin VB.CommandButton Command1
         Caption         =   "Attach one file"
         Height          =   315
         Index           =   0
         Left            =   4440
         TabIndex        =   9
         Top             =   3120
         Width           =   1695
      End
      Begin VB.TextBox Text1
         Height          =   315
         Index           =   2
         Left            =   960
         TabIndex        =   6
         Top             =   1080
         Width           =   5175
      End
      Begin VB.TextBox Text1
         Height          =   315
         Index           =   1
         Left            =   960
         TabIndex        =   4
         Top             =   660
         Width           =   5175
      End
      Begin VB.TextBox Text1
         Height          =   315
         Index           =   0
         Left            =   960
         TabIndex        =   2
         Top             =   240
         Width           =   5175
      End
      Begin VB.Label Label1
         AutoSize        =   -1  'True
         BackStyle       =   0  'Transparent
         Caption         =   "Message:"
         Height          =   195
         Index           =   3
         Left            =   180
         TabIndex        =   8
         Top             =   1560
         Width           =   690
      End
      Begin VB.Label Label1
         AutoSize        =   -1  'True
         BackStyle       =   0  'Transparent
         Caption         =   "Subject:"
         Height          =   195
         Index           =   2
         Left            =   180
         TabIndex        =   5
         Top             =   1140
         Width           =   585
      End
      Begin VB.Label Label1
         AutoSize        =   -1  'True
         BackStyle       =   0  'Transparent
         Caption         =   "cc:"
         Height          =   195
         Index           =   1
         Left            =   180
         TabIndex        =   3
         Top             =   720
         Width           =   225
      End
      Begin VB.Label Label1
         AutoSize        =   -1  'True
         BackStyle       =   0  'Transparent
         Caption         =   "To:"
         Height          =   195
         Index           =   0
         Left            =   180
         TabIndex        =   1
         Top             =   300
         Width           =   240
      End
   End
End
Attribute VB_Name = "frmNotesOLE"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
' OLE is late binding....
Dim OLESess As Object
Dim OLEDB As Object
Dim FilePath As String

' API calls to close notes window since it doesn't closes
' itself when finish.
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long

Private Sub cmdSend_Click()
Const EMBED_ATTACHMENT = 1454
' Creates a new document/message.
Dim Doc As Object
    Dim NItem As Object
    Set Doc = OLEDB.CreateDocument
    With Doc
        ' creates body of message and populates headers
        Set NItem = Doc.CreateRichTextItem("BODY")
        .Form = "Memo"
        .subject = Text1(2).Text
        .sendto = Text1(0).Text
        .copyto = Text1(1).Text
        .body = Text1(3).Text
        .postdate = Date
        ' if there is files to attach, it does
        If lstFiles.ListIndex <> -1 Then
            Dim i As Integer, UpperLstCount As Integer
            UpperLstCount = lstFiles.ListCount
            For i = 0 To UpperLstCount - 1
                lstFiles.Selected(i) = True
                Call NItem.EmbedObject(EMBED_ATTACHMENT, "", lstFiles.Text)
            Next i
        End If
        .Send False
    End With
End Sub

Private Sub Command1_Click(Index As Integer)
Select Case Index
Case 0
    With CDlg
        .ShowOpen
        If .FileName <> "" Then
            lstFiles.AddItem .FileName
            lstFiles.Selected(0) = True
        End If
    End With
   
Case 1
    Dim strFiles As String
    FilePath = BrwFolder
        If FilePath <> "" Then
            strFiles = Dir$(FilePath & "*.*", vbArchive)
            Do While strFiles <> ""
                lstFiles.AddItem strFiles
                '.Visible = True
                strFiles = Dir$()
            Loop
            lstFiles.Selected(0) = True
        End If
End Select
End Sub

Private Sub Form_Load()
' Creates new Notes session object and prompt user to
' password and uses default database mail.
' Prompt for password cannot be override.
Set OLESess = CreateObject("Notes.Notessession")
Set OLEDB = OLESess.GetDatabase("", "")

With OLEDB
    .OPENMAIL
    If Not .IsOpen Then
        MsgBox "Unable to open Notes session.", vbCritical, "Init Error"
        Exit Sub
    End If
End With
End Sub


Private Sub Form_Unload(Cancel As Integer)
On Error Resume Next
' Set object variables to nothing and
' search for Notes window to close it.
Set OLEDB = Nothing
Set OLESess = Nothing

Const WM_CLOSE = &H10
Dim hw As Long
hw = FindWindow("NOTES", vbNullString)
If hw <> 0 Then
    SendMessage hw, WM_CLOSE, 0&, 0&
End If
End
End Sub


' NotesAutomation.vbp


Type=Exe
Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\..\WINNT\System32\stdole2.tlb#OLE Automation
Reference=*\G{29131520-2EED-1069-BF5D-00DD011186B7}#1.0#0#..\..\lotus\notes\domobj.tlb#Lotus Domino Objects
Reference=*\G{1CF542E0-D988-11CF-B485-00805F98FACE}#1.0#0#..\..\lotus\notes\notes32.tlb#Lotus Notes Automation Classes
Object={F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0; COMDLG32.OCX
Form=frmNotesOLE.frm
Form=frmNotesCOM.frm
Form=frmInit.frm
Module=modNotes; modNotes.bas
Startup="frmInit"
HelpFile=""
Command32=""
Name="NotesAutomation"
HelpContextID="0"
CompatibleMode="0"
MajorVer=1
MinorVer=0
RevisionVer=0
AutoIncrementVer=0
ServerSupportFiles=0
VersionCompanyName="FMC Argentina"
CompilationType=0
OptimizationType=0
FavorPentiumPro(tm)=0
CodeViewDebugInfo=0
NoAliasing=0
BoundsCheck=0
OverflowCheck=0
FlPointCheck=0
FDIVCheck=0
UnroundedFP=0
StartMode=0
Unattended=0
Retained=0
ThreadPerObject=0
MaxNumberOfThreads=1

[MS Transaction Server]
AutoRefresh=1
Thanks for the info Richie!
We were able to get the close from your code!

We do not want to use the Domino object.  With that in mind, how can we get around the password prompt box?  We would like to pass it as some kind of parameter rather than send keys.

Thanks for all your help!
There is no way to avoid password prompt in version below 5.x, sorry.
It was implemented from 5.x and ahead.

There is another limitation with 4.x: The program loads to end user and there is nothing you can do to avoid that.
And not discg!harges from memory even if you release those objects.
Due to this limitation, i used an api function to search Notes window and send it a message to close.

Anyway, 5.x has backwards since if your last login to Notes was other user, that method will fail.
To work arond this limitation, we need to edit notes.ini file and change lastuser to the user who is login at this time.

Hope i was clear.
Thank you everyone for your comments and help.  Tim really helped the most in getting what we were after.
Avatar of hiba_t
hiba_t

Hi everyone,

I can see that Tim's code has been helpful for more than one person here.. And since I'm also trying to right a VB program to send emails through lotus notes I wanted to look at Tim's code.. But when I tried to open  http://www.geocities.com/TimCottee, It couldn't find the page..

Can anyone help me here ? This code should help me out.. if anyone can send it to me.. My email is hiba_t_t@hotmail.com..

Thanks,
Hiba_t
why don't you use the code provided here?
Because I want to use the MAPI, and as I read the code that posted here it doesn't use it..

I also managed to write something using MAPI but the problem is that when running it lotus just opens a new message and fills the fields with data but doesn't send it automatically so I was hoping that Tim's code will help me solving this problem..