Link to home
Start Free TrialLog in
Avatar of crescendo
crescendo

asked on

Emailing from VB

Does anyone have any sample code on how I can send a simple email through Notes from a VB program? I am posting the same question in the VB programming section, so there are easy points here...
Avatar of madheeswar
madheeswar
Flag of Singapore image

Your VB/VB Script/VBA code, accessing Notes through COM would look something like:

Dim session
Dim db
Dim doc
Set session = CreateObject("Lotus.NotesSession")
Call session.Initialize("passwordOptional")
- or -
Call session.InitializeUsingNotesUserName("name", "passwordOptional")
Set db = session.GetDatabase("","");
call db.OpenMail()
If db.IsOpen() Then
Set doc = db.create()
call doc.ReplaceItemValue("Form", "Memo")
call doc.ReplaceItemValue("SendTo", "...")
call doc.ReplaceItemValue("Subject", "...")
call doc.send()
call doc.save(True, False) ' If required
End If

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Method 2:
Thanks for the response. My code looks different than yours, but you pointed me in the right direction, thanks very much. If your interested, here's my code (I found part (well, a lot of it) on the Internet).

Dim domNotesDocumentMemo As Domino.NOTESDOCUMENT
Dim domSession As New Domino.NOTESSESSION
Dim domNotesDBDir As Domino.NOTESDBDIRECTORY
Dim domNotesDatabaseMailFile As Domino.NOTESDATABASE
Dim sUser As String

domSession.Initialize ("")
sUser = domSession.USERNAME
Set domNotesDBDir = domSession.GETDBDIRECTORY(sUser)

Set domNotesDatabaseMailFile = domNotesDBDir.OpenMailDatabase

' Create a new memo document.
Set domNotesDocumentMemo = domNotesDatabaseMailFile.CREATEDOCUMENT

Call domNotesDocumentMemo.APPENDITEMVALUE("Form", "Memo")
Call domNotesDocumentMemo.APPENDITEMVALUE("From", domSession.COMMONUSERNAME)
Call domNotesDocumentMemo.APPENDITEMVALUE("SendTo", "") 'email address must be entered here
Call domNotesDocumentMemo.APPENDITEMVALUE("Subject", "")
Call domNotesDocumentMemo.APPENDITEMVALUE("Body", "")

' Send the document.
domNotesDocumentMemo.SEND (False)

Set domNotesDocumentMemo = Nothing
Set domNotesDatabaseMailFile = Nothing
Set domNotesDBDir = Nothing
Set domSession = Nothing

Exit Sub

ErrorHandler:
MsgBox Err.Number & " " & Err.Description

End Sub

I never tested the above code. Hope it helps.
And check this code also:
The following VB code opens a local replica of the mail file specified, creates a new memo and attaches a file named c:\dir.txt and sends the mail to me.

You can change the code to get the current user's mail file and make other changes to make it more flexible -- this is just to show you how to create Notes mail with an attachment in Visual Basic.

Private Sub Command1_Click()
Dim session As Object
Dim db As Object
Dim doc As Object
Dim rtitem As Object
Set session = CreateObject( "Notes.NotesSession" )
Set db = session.GetDatabase( "", "mail\groberts.nsf" )
Set doc = db.CreateDocument
doc.Form = "Memo"
doc.Subject = "Test Mail from Visual Basic"
Set rtitem = doc.CreateRichTextItem( "Body" )
Call rtItem.EmbedObject(EMBED_ATTACHMENT, "", "c:\dir.txt")
doc.SendTo = "Gary_Roberts@westcare.org"
Call doc.Send( False )
Set session = Nothing
Set db = Nothing
Set doc = Nothing
End Sub

Avatar of qwaletee
qwaletee

Madheeswar,

Shouldn't you credit the sources of the code you copied in?  (Don't think it was me.)
Yes. I want to give credit for the person who has done this piece of code.

But, unfortunately I don't have their names.

Sorry Qwalette.
Do you at least have the web site the code was on?
I think it is from notes.net
Why? Do u want to tell them? Just joking.
Oh boy! Easy points!!!

I shouldn't been sleeping so late today :-(
OK! Here.

What is missing in the code above is - Multiple attachment handling. So here it goes.




'This is a combination of a number of routines for sending an Notes Email
'from Visual Basic. This works on Notes 4.x and 5.x (at least up to 5.06a).
'Lotus Notes must be installed on the computer which will run this code.
'Parameters for the routine are:
'Subject : String - Can be a comma seperated list of addresses.
'Attachement : String - Can be a pipe (|) delimited list of fully qualified filenames
'BodyTest : String - Nothing to say, just a string as long as you like
'CC : String - Can be a comma seperated list of addresses. (Optional)
'BCC : String - Can be a comma seperated list of addresses. (Optional)
'SaveIt : Boolean - Set to True to save in the Sent Folder after sending (Optional)

Public Sub SendNotesMail(Subject As String, Attachment As String, BodyText As String, SendTo As String, Optional CC As String = "", Optional BCC As String = "", Optional SaveIt As Boolean = False)
    'Set up the objects required for Automation into lotus notes
    Dim Maildb As Object 'The mail database
    Dim UserName As String 'The current users notes name
    Dim MailDbName As String 'THe current users notes mail database name
    Dim MailDoc As Object 'The mail document itself
    Dim AttachME As Object 'The attachment richtextfile object
    Dim Session As Object 'The notes session
    Dim EmbedObj As Object 'The embedded object (Attachment)
    'Start a session to notes
    Set Session = CreateObject("Notes.NotesSession")
    'Get the sessions username and then calculate the mail file name
    'You may or may not need this as for MailDBname with some systems you
    'can pass an empty string
    UserName = Session.UserName
    MailDbName = Left$(UserName, 1) & Right$(UserName, (Len(UserName) - InStr(1, UserName, " "))) & ".nsf"
    'Open the mail database in notes
    Set Maildb = Session.GETDATABASE("", MailDbName)
    If Maildb.ISOPEN = True Then
    'Already open for mail
    Else
    Maildb.OPENMAIL
    End If
    'Set up the new mail document
    Set MailDoc = Maildb.CREATEDOCUMENT
    With MailDoc
        .Form = "Memo"
        .SendTo = Split(SendTo, ",")
        .CopyTo = Split(CC, ",")
        .BlindCopyTo = Split(BCC, ",")
        .Subject = Subject
        .Body = BodyText
        .SAVEMESSAGEONSEND = SaveIt
    'Set up the embedded object and attachment and attach it
        Dim aryAttachment() As String
        aryAttachment = Split(Attachment, "|")
        For intAttach = LBound(aryAttachment) To UBound(aryAttachment)
            Set AttachME = .CREATERICHTEXTITEM("Attachment" & CStr(intAttach))
            Set EmbedObj = AttachME.EMBEDOBJECT(1454, "", aryAttachment(intAttach), "Attachment" & CStr(intAttach))
            .CREATERICHTEXTITEM ("Attachment" & CStr(intAttach))
        Next intAttach
    'Send the document
        .PostedDate = Now() 'Gets the mail to appear in the sent items folder
        .SEND False
    End With
    'Clean Up
    Set Maildb = Nothing
    Set MailDoc = Nothing
    Set AttachME = Nothing
    Set Session = Nothing
    Set EmbedObj = Nothing
End Sub





This code was originally written by Tim Cottee, VB Guru.

ASKER CERTIFIED SOLUTION
Avatar of RanjeetRain
RanjeetRain

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 crescendo

ASKER

It's looking good, folks, and I'll close the question and award points shortly.

One last question. Can anyone point me to documentation of the object models used in the sample code?
Do the following:

1. Open VB on any computer having both Lotus Notes client and Visual Basic installed.
2. Create a new Standard EXE project.
3. Set refrences to two libraries (MENU > Project > refrences)
      a. Lotus Domino Object (domobj.tlb)
      b. Lotus Notes automation classes (notes32.tlb)
If they are not alredy listed search for the above files or browse to them.
4. Press <F2> (or MENU > View > Object Browser.


Behold, you have access to every COM/OLE functionality Lotus Notes offers.
Ah, but not much explanation... I am only human, and need some idea of which method or property to use, and in what order.
Easy again!

Open Lotus Domino Designer Help. That's all that is there. And thats all you might ever NEED as a developer. Admins need more input than Help can provide... but developers? Its enough! I myself rely most on Designer help only.
See the section LotusScript/COM/OLE Classes under Contents tab.
If you still need more help, we (all@EE) are always there for you.

More so if you keep posting questions and keep awarding point generously ;-) Just kidding :-)
Unfortunately, I don't have Domino Designer Help on my machine. I am a MS developer primarily and the Lotus thing is all down to one client's requirements, hence posting the question on how to do it. I am going to have to develop in the office, then go to the client's premises and test and tweak. Not ideal, but I can't think of another way, short of installing Domino here, which is a major overkill. If there was documentation on the Internet, I could at least check my code to some extent before I go to the client.

My only experience of Domino to date is their pizzas...
Thanks to all who partcipated. RanjeetRain's code looks like it will do the trick and is clear to understand. No doubt RanjeetRain will pass the points on to Tim Cottee, who actually wrote the code. ;-)

Thanks again!
By the way, I'm just about to post another easy question in the Lotus Notes section, asking about a development server setup for Domino. See you there!
OK! We have a few things in common!

I am also PRIMARILY an MS developer. And Domino indeed was a Pizza brand for me sometime ago :-))

Tim Cottee got so many eggs to hatch, he got not time to count the chickens. So if you don't tell him, he wouldn't ever ask me his share ;-)

I'll send you a couple of links shortly. Let it be a surprise gift for you.

See you at your new post :-)
Download the Domino Designer 6 Developer's Handbook from here - http://www.redbooks.ibm.com/pubs/pdfs/redbooks/sg246854.pdf

Its a PDF. You may carry them everywhere on a CD and and read at your convenience without having to worry about the availability of Lotus Note client. Its comprehensive and covers a lot. Even if you use R5, its applicable.
Lotus Domino Release 5.0: A Developer's Handbook is here - http://www.redbooks.ibm.com/pubs/pdfs/redbooks/sg245331.pdf
Hi RanjeetRain

That's fantastic, should be just what I need.

Thanks!
LOL at the comment this code was originally written by Tim Cottee VB Guru.

It should probably read, this code was ripped by Tim Cottee from the following site.....

http://www.fabalou.com/VBandVBA/lotusnotesmail.asp
Hi fabalou,

With due respect to your abilities...

It is very difficult if not impossible to tell who wrote which piece of code first and who posted it first (there is absolutely no one I know who track flow of information on net) unless and untill it was "Hello World" program by Dennis Ritchie.

Anybody can ask you back... "this code was ripped by Tim Cottee??? OR fabalou ripped it from <put Tim Cottee's URL here> ???" Most certainly, no one knows. I gave the credit to the person, whose site I got it first at. Today I have several variations and improvised version of similar code but that is purely coincidental. As a software person I would love to give the credit for people who own the intellectual rights over it.

You might have a reason to LOL at my comment but at the same time I have every right to LOL at yours and reject it!
Ooh nice comment....you've just opened yourself up for a flaming.......

Obviously not knowing that flow of information is tracked on the net shows your shortsightedness.

http://web.archive.org/web/20010109222200/www.fabalou.co.uk/VBandVBA/lotusnotesmail.htm

So that dates it at least back to March 2000. Now I'm not one to split hairs but having a look at Tim Cottee's site I'm thinking the earliest he put it up was THIS YEAR.

I'm reasonably sure I put it up even earlier than 2000 but off the top of my head I'm not sure. I know I wrote the code over 3 years ago.

What irks me is the fact that people will quiet happily take the code pass it off as their own and not even bothering to change it one bit.

Some of us don't profit from giving the advice....some of us try to gain kudos by passing off other peoples code. The previous comment was intended to shed a bit of light on the fact your praise was wrong.

fabalou,

C'mon, give him a break!  He gave attribution, not his fault if his source didn't attribute it to someone earlier.  Heck, very similar code when the first Notes.NotesSession exposure came out, I think it was in 4.5, around eight years ago.

And BTW, archive.org is known for missing lots of stuff and general inaccuracy.
fabalou,

Your comment only shows how incomplete you are in your knowledge and how poor in expressing your thoughts. I have no time to give you a damn anymore.
Tell you what...why not pop back to Tim's site in the next few days when he's going to be putting up a link for the originator of that code.
Well whoever wrote the code, this whole question worked for me. I got the code snippet, links to documentation and lots of advice, so thanks all round, whether you wrote the original code or not. Its all appreciated.
Thanks for very useful tip, whoever wrote it.   It's a really good bit of code, and saved me at least a week of work.