Sending IBM Lotus Notes email using excel VBA sends from wrong email address - vba

I currently have two Lotus Notes databases, each with their own email addresses associated with them. As expected, when I send an email through the first database to my gmail account, it shows up as "From: notesAccount1#db1.com" and when I send using the second database, the message shows up as "From: notesAccount2#db2.com" in my gmail.
I have working code that opens up the second database, searches the inbox for an email containing a certain keyword, and extracts an email address from that email. It then creates a new document in that second database, inserts the recipients name, subject, body, etc., sends the email, and saves it to my sent folder. Everything works smoothly up to this point.
However, when I send an email from the second database to my gmail account using this VBA method, the email shows up in my gmail as "From: notesAccount1#db1.com" - the email associated with the first database.
I can't figure out why this is happening. Pretty limited knowledge of the interactions between VBA and Lotus Notes, and Lotus Notes servers/databases in general. The first database is technically my default one that only I have access to and the second database was added later and multiple people have access to it. I don't know if that's relevant.
Would appreciate any help! Thanks.
Note: This code was copied and adapted from several sources, including some on SO, IBM and other Notes sources, and anything else Google threw my way, including
http://www.fabalou.com/vbandvba/lotusnotesmail.asp
http://www-01.ibm.com/support/docview.wss?uid=swg21178583
Code: (This will have to be adapted as I have taken out server names and mail file names)
Sub ReadNotesEmail()
Dim sess As Object
Dim db As Object
Dim folder As Object
Dim docNext As Object
Dim memoSenders As Variant
Dim newEmail As Object
Dim view As Object
Dim entry As Object
Dim entries As Object
Dim templateEmail As Object
Dim mailServer As String
Dim mailFile As String
Dim folderName As String
Dim todayDate As String
Dim memoBody As String
Dim senderEmail As String
Dim emailStartPos As Integer
Dim emailEndPos As Integer
'This program will search a particular folder in a Notes database that I designate.
'It will search that folder for emails that contain certain key words. Once it finds
'an email that fits, it will grab the sender's email address (written in the body, not
'in the 'from') and send them an email.
'Name of folder to search for emails
folderName = "($Inbox)"
'Create a Lotus Notes session and open it (will require password)
Set sess = CreateObject("Lotus.NotesSession")
sess.Initialize ("")
'Set the mail server, mail file, and database. This will be the tricky part as I need this to
'look at the second mail server as opposed to the default mail server of jdyagoda
Set db = sess.GETDATABASE("***name of second Notes server***", "***name of second mail file***")
'Open the mail database in notes
If Not db.IsOpen = True Then
Call db.Open
End If
Set folder = db.GetView(folderName)
'Now look through the emails one at a time with a loop that ends when no emails are left.
'If an email contains the key word, look for the email address of the person who submitted
'the contact-us form. It follows the string "Email:" and preceeds
'the string "Phone:".
Set doc = folder.GetFirstDocument
Do Until doc Is Nothing
Set docNext = folder.GETNEXTDOCUMENT(doc)
memoBody = LCase(doc.GetItemValue("body")(0))
If (memoBody Like "*") Then 'This is where you designate the keyword
'Here's where you extract the email address - taken out for the purpose of this SO question
'senderEmail = testName#test.com
'Now create a new email to the intended recipient
Set newEmail = db.CREATEDOCUMENT
Call newEmail.ReplaceItemValue("Form", "Memo")
Call newEmail.ReplaceItemValue("SendTo", senderEmail)
Call newEmail.ReplaceItemValue("Subject", "Thank you for your email")
Call newEmail.ReplaceItemValue("body", "Test Body 1. This is a test.")
newEmail.SAVEMESSAGEONSEND = True
'Send the new email
Call newEmail.ReplaceItemValue("PostedDate", Now()) 'Gets the mail to appeaer in the sent items folder
Call newEmail.SEND(False)
End If
Set doc = docNext
Loop
End Sub

Notes will normally send the mail using the email address for the ID you use to login. So if you login using notesAccount1/Domain, then all emails will be coming from notesAccount1#example.com.
If you want to fake the sender, you need to use an undocumented method: inject the email directly into mail.box.
You should not attempt to do this unless you really know what you are doing.
I have posted code on my blog for a mail notification class, it supports this work-around to set the sender on outgoing emails. You can find the latest code at http://blog.texasswede.com/updated-mailnotification-class-now-with-html-email-support-and-web-links/

Related

VBA Lotus Notes sender email address as CC

I created a makro in excel to send all TODOs to the responsible people. Now I want to add the sender address into the CC. I know how to set the CC but I don't know how to get the current sender address.
Set session = CreateObject("Notes.NotesSession")
Set db = session.GETDATABASE("", "")
Call db.OPENMAIL
Set doc = db.CREATEDOCUMENT
Call doc.REPLACEITEMVALUE("CopyTo", strEmail)
I think it should work with the notes session, but I didn't find any method for this.
You can just use NotesSession.UserName(). This is Notes mail you are sending. You don't need a full SMTP-style address with the # and the DNS domain name. You can just put the user's Notes username in an addressing field and the Domino router will do the lookup and it will just work.
The above is true as long as (a) the server that you have established the session with is either the user's home mail server, a member of the same Notes domain (which is not the same thing as a DNS domain), or a member of a Notes domain that includes the user's Notes domain as part of its Directory Assistance (or its cascading address book list if it's using 20-year-old configurations), and (b) the username is unique within the above scope.
another suggestion, copy sender from last sent mail, to test
Set view = db.GetView("(($Sent))")
Set sentdoc = View.GetLastDocument
sender=sentdoc.getItemValue("From")
The way I automated Lotus Notes and sending emails was using this site below:
Send files using Lotus Notes
The area you want to pay attention to is at the bottom, which takes "noDocument" and adds the relevant titles "Subject", "to", "Sendto" etc.
'Add values to the created e-mail main properties.
With noDocument
.Form = "Memo"
.SendTo = vaRecipients
.CopyTo = vaCopyTo
.Subject = stSubject
.Body = vaMsg
.SaveMessageOnSend = True
.PostedDate = Now()
.Send 0, vaRecipients
End With
Use NotesSession.userName() to get the current username. If you really want the full email address you might also be able use #namelookup formula.
However, I would stay away from accessing notes via COM as it does not work on 64bit and IBM couldn't care less about it. I had several excel files which used this handy technique, but they are all broken since we moved to 64bit. Check this old kb https://www-304.ibm.com/support/docview.wss?uid=swg21454291

Generating Email with Hyperlink from MS Access

I'm attempting to generate an email from MS Access when a particular procedure is run and certain conditions are met, the email will include a hyperlink. I've found the sendobject macro command does not allow for hyperlink, only static text. It seems that the solution is to code the portion of the entire process that generates and sends the email in VBA and call on that code in the appropriate segment of my if function within my macro.
I can't figure out the appropriate code to generate and send and email with a hyperlink to an individual however. It will be very simple, single recepient, unchanging title, and the body will read 'New providers require designation, please access the provider designation dashboard for provider designation' ideally the provider designation dashboard would be the hyperlink and point to a shared network space.
What commands do I need to accomplish this, I'm inexperienced in VBA and this is eating up a fair amount of time I don't have.
Thank you
There are some different approaches for sending e-mail with code. The code bellow uses an Outlook Application COM object to generate the message with a hyperlink - thus, it will only work if MS Outlook is installed in the user's machine.
Sub NewEmail(ByVal mylink As String, ByVal therecipient As String)
Dim Outlook As Object, Email As Object
Set Outlook = CreateObject("Outlook.Application")
Set Email = Outlook.CreateItem(0) 'olMailItem = 0
With Email
.Subject = "My Subject" 'message subject
.HTMLBody = "Greetings, please check this link: <a href='" & mylink & "'>Click me</a>." 'message body, in html. concatenate multiple strings if you need to
.To = therecipient 'recipient
'use this if you want to generate the message and show it to the user
.Display
'use this instead if you want the mail to be sent directly
'.Send
End With
Set Email = Nothing
Set Outlook = Nothing
End Sub
Put the code in a module. Then anywhere in your code you may call the procedure with something like:
NewEmail "www.mysite.com/targetpage.html", "persontomail#domain.com"
Notice that the routine above uses late binding. To use early binding (and get intellisese, but with some drawbacks), you would have to add a reference to Microsoft Outlook XX.X Object Library and dim the "Outlook" and "Email" objects as Outlook.Application and Outlook.MailItem, respectively.

Getting new email senders address

I composed a new email. Before sending this email, I would like (using VBA) to get the senders email address.
I wrote the following example code. When I run this code, the first message box displays the email subject correctly, however the second message box shows nothing (the message box is empty).
Sub email_test()
Dim eSubject As String
Dim eSender As String
eSubject = Application.ActiveInspector.currentItem.subject
MsgBox eSubject
eSubject = Application.ActiveInspector.currentItem.SenderEmailAddress
MsgBox eSender
End Sub
A new mail item doesn't have the Sender* related properties set. They are set right after the message is processed by the transport provider and can be get, for example, from the Sent Items folder. You can handle the ItemAdd event of the Items class which comes from the Sent Items folder. Be aware, the SaveSentMessageFolder property of the MailItem class can be used to set a Folder object that represents the folder in which a copy of the e-mail message will be saved after being sent. Also the DeleteAfterSubmit property can be set, in that case a copy of the mail message is not saved after being sent.
You may be interested in the SendUsingAccount property which allows to get or set set an Account object that represents the account under which the MailItem is to be sent.
Use MailItem.SendUsingAccount.SmtpAddress. If MailItem.SendUsingAccount is null, you can asssume the default account will be used - the address can be accessed from Application.Session.CurrentUser.Address. In case of an Exchange mailbox, use Application.Session.CurrentUser.AdderssEntry.GetExchangeUser.PrimarySmtpAddress

VBA Lotus Notes - Pop Open New Email Window

I'm tasked with a very simple objective. Open a new email window in lotus notes using VBA, but please keep reading the fully understand my issue. Currently, I have developed vba code that creates a new email in lotus notes and fills it with all sorts of information, such as the recipient, subject, body and attachments; and then finally sends the email to the recipient. It all works flawlessly. The only problem is that it does all of this behind the scenes, and if it wasn't for checking with the recipient I would have no idea the email sent. To get around this I want the vba code to psychically pop open a new email window, with all of the same information, but instead force me to manually send the email (by hitting the send button). This way I know the email will have been sent, and also so I can add in extra information if needed.
I've looked at more threads than I can count and all seem to address a slightly different issue than mine. Any suggestions or hints in the right direction would be appreciated.
Thanks!
Thanks for the suggestions. Heres my code:
Sub Prepare_email()
Dim Maildb As Object
Dim MailDoc As Object
Dim Body As Object
Dim Session As Object
Dim Subject As String
'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
'Open the mail database in notes
Set Maildb = Session.GETDATABASE("", MailDbName)
If Maildb.IsOpen = True Then
Else
Call Maildb.Open
End If
'Create the mail document
Set MailDoc = Maildb.CREATEDOCUMENT
Call MailDoc.ReplaceItemValue("Form", "Memo")
'Set the recipient, calls a GetPrimary Email function
Call MailDoc.ReplaceItemValue("SendTo", GetPrimaryEmail)
'Set subject, calls subject function
Subject = getCompanyName
Call MailDoc.ReplaceItemValue("Subject", Subject)
'Create and set the Body content
Set Body = MailDoc.CREATERICHTEXTITEM("Body")
Call Body.APPENDTEXT("BODY Content")
'Example to save the message
MailDoc.SAVEMESSAGEONSEND = True
'Send the document
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
By "behind the scenes", I presume you mean that you are using the Notes "back-end classes". If you want to actually open a window in the client, you have to use the "front-end" classes.
An important difference to understand is that the "front-end" classes are exposed as OLE objects (Notes.NotesUIWorkspace), and the "back-end" classes are exposed both as OLE (Notes.NotesSession) and COM (Lotus.NotesSession) objects. Note the different prefixes: 'Notes' for OLE classes, 'Lotus' for COM classes.
The NotesUIWorspace class and the other front-end classes that you can drive through it are all about automating the actual operation of the Notes client. You can find documentation for the NotesUIWorkspace class here. When you use OLE classes, the Notes client starts automatically unless it is already running. When you use the COM classes, the Notes client does not need to be running and does not start automatically.
The first step involves saving your document instead of calling Send, i.e. call Call doc.Save( True, True ) if doc is your NotesDocument class.
The second step is showing the document by using CreateObject("Notes.NotesUIWorkspace").EDITDOCUMENT True, doc
As a side note: Showing your code would actually help answering the question!

lotus notes to VBA

I'm stuck with this problem for days
I have to read a specific mailbox in lotus notes and bring all the content into an excel spread sheet
but so far I have only been able to read the default inbox and have no way of switching to the other mailbox. I 'm really new to VBA can any one help me sort this out
here is the code I 'm using
Set NSession = CreateObject("Notes.NotesSession")
'get the name of the mailfile of the current user
DbLocation = NSession.GETENVIRONMENTSTRING("mail/mailbox", True)
'Get the notesdatabase for the mail.
Set NMailDb = NSession.GETDATABASE("mailboxer", DbLocation)
MsgBox (DbLocation)
I get an empty msgbox poping up
GetEnvironmentString() reads the notes.ini file. I'm not sure that's what you really want to be doing. Just from the syntax, I think you're using "mail/mailbox" as a placeholder for the actual path to the mailbox that you're looking for. E.g., you're really trying to read the mail from something like "mail/jsmith.nsf". (If I'm wrong, and you really do want to be reading the notes.ini file to get the location of the mail file, then your problem is that "mail/mailbox" is not a valid key for an ini file entry.)
My next assumption is that the Domino server where the mailbox lives is called "mailboxer", because that's what you're putting in the first argument of GetDatabase().
If I'm right about these things, then what what you need is
Set NMailDb = NSession.GETDATABASE("mailboxer", "mail/mailbox")
where "mail/mailbox" is replaced with the actual path to the mailbox that you are trying to open.
Some thoughts:
use Lotus.NotesSession if you don't have to interact with the Notes UI (Lotus.NotesSession is COM based, whereas Notes.NotesSession is OLE based)
make sure the user of the Notes client on the workstation running your VBA application has the rights require to open and read the mailbox
As D. Bugger stated, you need to be sure you have the Notes client installed on the same client machine your VB code will run, and you need to be sure the folder with the nnotes.exe file and the folder with the notes.ini file are in your environment path. (If not, you will get a COM error instantiating the Notes.NotesSession object.
If this helps, here is some starter code - not tested, but a rough guide... This walks through all documents in a Notes mailbox database, ignores anything except email documents (which have the form field = "Memo") and grabs some fields from each email.
Public Sub exportNotesMail(MailServer$, MailDBPath$)
Dim mailDb As Object, doc As Object, alldocs As Object, Session As Object
Set Session = CreateObject("Notes.NotesSession")
Set mailDb = Session.GETDATABASE(MailServer, MailDbPath$)
If mailDb.IsOpen = False Then mailDb.OPENMAIL
Set alldocs = mailDb.AllDocuments
Set doc = alldocs.GetFirstDocument
while not (doc is nothing)
If doc.GetItemValue("Form")(0) = "Memo" Then
thisSubject = doc.getItemValue("Subject")(0)
thisFrom = doc.getItemValue("From")(0)
' get more field values
' Export to Excel or wherever
End If
Set doc = alldocs.GetNextDocument(doc)
Next i
' done
End Sub
call exportNotesMail ("MyServer", "mail\myMailFile.nsf")