Generating Email with Hyperlink from MS Access - vba

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.

Related

Send email reminder when task occurs

This code works with Outlook's Task system. I created a task that reoccurs every week on Wednesday. When the task occurs the code is suppose to send an email to "test#work.com" (not the real test email).
I have written the code in the Outlook VBA developer window.
Am I missing a step to get the code to run? The code logic is posted below.
Sub Application_Reminder(ByVal Item As Object)
Dim objPeriodicalMail As MailItem
If Item.Class = olTask Then
If InStr(LCase(Item.Subject), "Send PM Work Order Request Reminder Email") Then
Set objPeriodicalMail = Outlook.Application.CreateItem(olMailItem)
With objPeriodicalMail
.Subject = "REMINDER-Get Work Order Request Submitted"
.To = "Test#work.com"
.HTMLBody = "<HTML><BODY>Hello All Pm's, Please Submit your Work order request by 9:00A.M.</HTML></BODY>"
.Attachments.Add
.Importance = olImportanceHigh
.ReadReceiptRequested = True
.Send
End With
End If
End If
End Sub
To control Outlook objects from outside Outlook, you must establish a reference to the Outlook object library from the project in which you are writing code. To do this, use the References dialog box in the Visual Basic Editor in the primary application. You can then write code that returns a reference to the Outlook Application object. Through this reference, your code has access to all the objects, properties, methods, and constants defined in the Outlook type library.
Read more about that in the Automating Outlook from a Visual Basic Application article.
To set up events you need to define the source object withevents or select in the drop-down list on VBA editor and select the required event. See Using Outlook Visual Basic for Applications to Respond to Outlook Events.

Reply, with template, using properties of original mail

I work at a Company that gets requests we filter in terms of
being eligibile for financing from our financing partner
requiring more information from the enquirer
There is a lot of monotonous work, in copy pasting email replies.
I looked into creating a Quick Action in Outlook, but because our mother company does not allow certain freedoms, like the Font has to be specifically Segoe Ui Light etc. I could not use this, so I thought about writing a macro.
I intended for a macro button to:
Open a new Reply email, replying to all in the original mail.
In this new email text body, use a template email that I already made and saved as a template. (This way it saved the Font, size and other formatting.)
Put in the original Sender and CC'ed mail addresses as well as the Subject from the original mail.
And then display the email, so I could make edits if I wanted to before sending.
Sub ReplyGewerbeanmeldung()
Dim origEmail As MailItem
Dim replyEmail As MailItem
Set origEmail = Application.ActiveWindow.Selection.Item(1)
Set replyEmail = Application.CreateItemFromTemplate(" "C:\Users\XYZ\AppData\Roaming\Microsoft\Templates\ReplyGewerbeanmeldung.oft"\ReplyGewerbeanmeldung.oft")
replyEmail.To = origEmail.Sender
replyEmail.CC = origEmail.CC
replyEmail.Subject = origEmail.Subject
replyEmail.HTMLBody = replyEmail.HTMLBody & origEmail.Reply.HTMLBody
replyEmail.Display
End Sub
First of all, it seems you need to correct the file path to the template message. The following string is not a valid file path:
" "C:\Users\XYZ\AppData\Roaming\Microsoft\Templates\ReplyGewerbeanmeldung.oft"\ReplyGewerbeanmeldung.oft"
Try to use the following string instead:
Set replyEmail = Application.CreateItemFromTemplate("C:\Users\XYZ\AppData\Roaming\Microsoft\Templates\ReplyGewerbeanmeldung.oft")
You can read more about that in the How To: Create a new Outlook message based on a template article.
Anyway, creating items from a template will not preserve the original message body. Moreover, in Outlook you will not get any visual appearance that a particular items was replied. So, you need to call the ReplyAll method on the original item in Outlook to avoid this artefacts in Outlook.
You can create a new mail item, but only for copying the message body response which is required to paste into the reply. The NameSpace.OpenSharedItem method can be used to to open iCalendar appointment (.ics) files, vCard (.vcf) files, and Outlook message (.msg) files. You may consider using it instead of creating a new item based on the template to grab the message body from there.

Activate Out of Office reply

I would like to automate my Out of Office based on the days that I'll be out on a biweekly basis. I don't have access to the Exchange server that hosts our Outlook.
I set an Outlook rule to send a automatic reply on Monday and apply VBA code to disable this rule when I'm in the office (with Outlook open). This is not an elegant way because the rule sends a reply to the user repeatedly every time an email is sent to me.
How can I activate my Out of Office reply on Outlook 2010 using VBA?
Here are the two resources I used:
https://answers.microsoft.com/en-us/msoffice/forum/msoffice_outlook-mso_win10/set-up-recurring-out-of-office-auto-reply-for/71dd1fef-ba99-4a2b-be72-7d509e8848eb
https://superuser.com/questions/292426/outlook-2010-how-to-turn-out-of-office-on-automatically-when-outlook-is-closed
This is the script I have in "ThisOutlookSession" to enable/disable the rule, "HomeTime" containing my Out Of Office-like message.
Option Explicit
Private Sub Application_Quit()
SetRuleEnabled True
End Sub
Private Sub Application_Startup()
SetRuleEnabled False
End Sub
Private Sub SetRuleEnabled(ByVal bEnable As Boolean)
Dim oSession As Outlook.NameSpace
Dim oRule As Outlook.Rule
Dim oRules As Outlook.Rules
Dim oPA As Outlook.PropertyAccessor
Set oSession = Application.Session
Set oRules = oSession.DefaultStore.GetRules()
Set oPA = oSession.DefaultStore.PropertyAccessor
'*** If the Out-Of-Office is already on (eg. holidays, sick leave etc.)
'*** then it might be best to force this rule permanently off
If oPA.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x661D000B") Then
bEnable = False
End If
For Each oRule In oRules
If oRule.Name = "HomeTime" Then
oRule.Enabled = bEnable
oRules.Save
Exit For
End If
Next
End Sub
I am assuming you've checked out Om3r's link, but I have a less elegant, if not clunky solution. I once created a VBA out of office message as a practical joke (just to avoid someone). I could not find the code, but here is a summary of what you'd need to do.
(Outlook has to be running for this to work)
Create a public boolean variable, for example OutofOffice, set by a ribbon/QAT button or on a schedule.
Create and save a draft email with your message (e.g. "I am out of the office...")
Use or set up an Inbox_ItemAdd event listener, and for each incoming email:
Reply to it,
concatenating "Auto-Reply " to the subject line
Retrieve the draft email and concatenate your draft message body to the reply body (and you'll have to figure out HTMLBody versus (non-HTML) Body. Something like:
OutMail.HTMLBody = OutMail.HTMLBody & ObjDraft.HTMLBody
or you might save your OOO message as a public static string (instead of a draft email).
Send the email
as you mentioned, you don't want to repeatedly send this to people who sent you additional emails during this period. I would probably add the sender's email address (after passing to a GetSMTPAddress type function) to an array. I'd add a IsInArray type function to check each new sender (to see if they were emailed already). This array would be erased by your procedure called when you click that control again to turn off the OOO reply.
If this worked for you, of course you could create a userform to edit the OOO message and set the schedule (day of week or specific dates).

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

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/

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!