Save email after modification - ms-access

I have code, similar to the following, that I would like to modify:
Sub SendEmail()
Dim myOlApp As Outlook.Application
Dim myItem As Outlook.MailItem
'Create an Outlook application object
Set myOlApp = New Outlook.Application
'Create a new MailItem form
Set myItem = myOlApp.CreateItem(olMailItem)
'Build and display item
With myItem
.To = “test#test.com”
.Subject = “Test Subject”
.HTMLBody = “Test Body”
.Display
.SaveAs “C:\Test.msg”, olMSG
End With
End Sub
This code is called from various buttons throughout the application. When a button is clicked, a new email is created and saved. Unfortunately, the email is saved as soon as it is created and BEFORE it is sent... so, if any modifications are made to it, they will not be in the saved version.
What can I do to modifiy this code to ONLY save the email once it has been sent?
Feel free to ask any followup questions as necessary and I will respond as best I can.
Thanks!
Robert

You can use Outlook events with Access. For this example you will need a Class Module called clsOlMail with this code:
''Requires reference to the Microsoft Outlook x.x Object Library
Dim WithEvents conItems As Outlook.Items
Private Sub Class_Initialize()
Set oApp = Outlook.Application
Set oNS = oApp.GetNamespace("MAPI")
Set conFolder = oNS.GetDefaultFolder(olFolderSentMail)
Set conItems = conFolder.Items
End Sub
Private Sub Class_Terminate()
Set conItems = Nothing
Set conFolder = Nothing
Set oNS = Nothing
Set oApp = Nothing
End Sub
Sub ConItems_ItemAdd(ByVal Item As Object)
Dim frm As Form
Set frm = Forms!frmEmailDetails
frm.txtSenderName = Item.SenderName
frm.txtSentOn = Item.SentOn
frm.txtTo = Item.To
frm.txtCreationTime = Item.CreationTime
frm.txtBCC = Item.BCC
frm.txtCC = Item.CC
frm.txtSentOnBehalfOfName = Item.SentOnBehalfOfName
frm.txtSubject = Item.Subject
frm.txtBody = Item.Body
End Sub
You will also need a form called frmEmailDetails with these textboxes:
txtSenderName, txtSentOn, txtTo, txtCreationTime, txtBCC, txtCC, txtSentOnBehalfOfName, txtSubject, txtBody
And this code:
Private oEvent As clsOLMail
''Requires reference to Microsoft Outlook x.x Object Library
Public oApp As Outlook.Application
Public oNS As Outlook.NameSpace
Public conFolder As Outlook.MAPIFolder
Private Sub Form_Open(Cancel As Integer)
Set oEvent = New clsOlMail
End Sub
Open the form and send an email through Outlook, you can use one of the examples shown above. The form fields should fill with the relevant details from the sent email. You are likely to get an Outlook security warning.
From: http://wiki.lessthandot.com/index.php/Access_and_Email

The problem is there is no EntryID for the newly created item. Once you save/send this item, the reference is no longer good. Why is probably due to how MAPI works. Remou suggests using the ItemAdd event to handle the item newly added to the special folder "Sent Items". From this event you can save the message. The only issue I see is how would you know passed item is the sent item. You are calling Display, which allows the user to preview, edit, send, or close the message without sending. Therefore, the item may not be the mail item you created. To get around this, add a custom property to your mail item. When the ItemAdd event is fired, you can inspect the passed item for the custom property, and save if needed.

Related

How to remove a warning set in the body of incoming mail from outside of my organisation [duplicate]

I'm writing a macro that creates tickets on a database based on alerts received from a Nagios server as an email. However, I cannot let the macro run in an infinite loop while checking for mails because it is just too resource heavy and makes my desktop hang. I need to find a way to trigger the macro only when a new mail is received.
I looked for something along the lines of NewMail events on the MSDN website, but I can't find anything coherent. Can anyone show me just a bit of sample code to show how to trigger macros from new mail events?
This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error Goto ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
' do something here
' ******************
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
After pasting the code in ThisOutlookSession module, you must restart Outlook.
Try something like this inside ThisOutlookSession:
Private Sub Application_NewMail()
Call Your_main_macro
End Sub
My outlook vba just fired when I received an email and had that application event open.
Edit: I just tested a hello world msg box and it ran after being called in the application_newmail event when an email was received.

Code loses Outlook email template formatting

I am using this code in MS Access to to open a saved HTML Outlook Template. The code searches for "SALUTATION" in the body of the email and replaces it with controls data from my form.
It works pretty well but, I lose the email formatting which includes formatted text, multiple links and a few images.
How can my code be changed to keep the original formatting?
Private Sub Command139_Click()
Dim myOlApp As Outlook.Application
Dim MyItem As Outlook.MailItem
Dim value As String
value = Me.Salutation & " " & Me.LastName
Set myOlApp = CreateObject("Outlook.Application")
Set MyItem = myOlApp.CreateItemFromTemplate("C:\Users\Meiaer\AppData\Roaming\Microsoft\Templates\ELMOVM.oft")
MyItem.Display
With MyItem
.To = Me.EMAIL_ADDRESS
MyItem.Body = Replace(MyItem.Body, "SALUTATION", value)
End With
Set MyItem = Nothing
Set myOlApp = Nothing
End Sub
Thank you
You need to edit MyItem.HTMLBody, not MyItem.Body (which is the plaintext representation of the mail body).
See https://technet.microsoft.com/en-us/library/ff868941(v=office.14).aspx

How can I get current Office Windows account email using VBA?

How can I get current Office Windows account email using VBA code?
I do not mean the account which the user is logged in the Windows, I mean the account that is authorized in office
See image:
I don't believe you can access it. Your best bet is linking Access to Outlook and trying to access it from there.
For example you Set a reference to the Outlook object library and then :-
Dim olook As Outlook.Application
Dim EAddress As String
Set olook = GetObject(, "Outlook.Application")
Set olook = CreateObject("Outlook.Application")
EAddress = olook.Session.CurrentUser.Address
I have a similar solution calling out to Outlook, I'm using Excel and found a way to do this, I've only ever found one address in the Accounts collection, but have a suffix match to try and catch the #company.com I'm looking for:
Dim NameSpace As Object
Dim strEmailAddress As String
Set NameSpace = CreateObject("Outlook.Application").GetNameSpace("MAPI")
strEmailAddress = ""
For Each Account In NameSpace.Accounts
If LCase(Split(Account.SMtpAddress, "#")(1)) = "contoso.com" Then
strEmailAddress = Account.SMtpAddress
Else
strEmailAddress = "Unknown"
End If
' If you want to see more values, uncomment these lines
'Debug.Print Account.DisplayName
'Debug.Print Account.UserName
'Debug.Print Account.SMtpAddress
'Debug.Print Account.AccountType
'Debug.Print Account.CurrentUser
Next
Outlook interrupts the VBA-execution (to access Outlook objects from macro) due to security.
Snap shot
Outlook Security
Hence only to get eMailID without opening object as well as handling error in case of non availability of outlook/account, following code can work in your case
VBA Code
Sub Email_Address()
Dim MAPI As Object
Status = "unknown"
On Error GoTo return_value
Set MAPI = CreateObject("Outlook.Application").GetNameSpace("MAPI")
i = 1
Do While True
Debug.Print MAPI.Accounts.Item(i)
i = i + 1
Loop
return_value:
If i > 1 Then: Status = "done..."
Debug.Print Status
End Sub

How to export data from VB6 to an HTML TextBox

I would like to know how can I export data from VB6 textbox to a HTML textbox? It could be a simple html page or an asp page.
for example, on my VB6 form, i have an name field. Upon clicking of a button on the VB6 form, the data in the name field will be exported to a textbox on the html page.
Thank you all for help and time for reading this.
To see this demo in action, and be able to follow it through and learn how to grab from it what you need:
Create a form with a lable over a textbox, and stick 1 command buttons on the form. Don't rename any of them - the program expects the text1, command1
The following CODE is the complete FORM CODE to copy/paste into it.
Add refernce to your project from (Project=>References)Microsoft Internet Controls,Microsoft HTML Object Library,
Option Explicit
Public TargetIE As SHDocVw.InternetExplorer
Private Sub Command1_Click() ' Send text to first IE-document found
GetTheIEObjectFromSystem
SendTextToActiveElementWithSubmitOptionSet (False)
End Sub
Private Sub Form_Load()
Me.Text1 = "This is a sample text message set and submitted programmatically" 'make text1 multiline in design
Me.Command1.Caption = "Text to the first IE browser document found"
End Sub
Public Sub GetTheIEObjectFromSystem(Optional ByVal inurl As String = ".") ' "." will be found in ALL browser URLs
Dim SWs As New SHDocVw.ShellWindows
Dim IE As SHDocVw.InternetExplorer
Dim Doc As Object
For Each IE In SWs
If TypeOf IE.Document Is HTMLDocument Then ' necessary to avoid Windows Explorer
If InStr(IE.LocationURL, inurl) > 0 Then
Set TargetIE = IE
Exit For
End If
End If
Next
Set SWs = Nothing
Set IE = Nothing
End Sub
Private Sub SendTextToActiveElementWithSubmitOptionSet(ByVal bSubmitIt As Boolean)
Dim TheActiveElement As IHTMLElement
Set TheActiveElement = TargetIE.Document.activeElement
If Not TheActiveElement.isTextEdit Then
MsgBox "Active element is not a text-input system"
Else
TheActiveElement.Value = Me.Text1.Text
Dim directParent As IHTMLElement
If bSubmitIt Then
Dim pageForm As IHTMLFormElement
Set directParent = TheActiveElement.parentElement
' find its parent FORM element by checking parent nodes up and up and up until found or BODY
Do While (UCase(directParent.tagName) <> "FORM" And UCase(directParent.tagName <> "BODY"))
Set directParent = directParent.parentElement
Loop
If UCase(directParent.tagName) = "FORM" Then
Set pageForm = directParent
pageForm.submit 'intrinsic Form-element Method
Else
MsgBox ("Error: No form unit for submitting the text on this page!")
End If
End If
Set pageForm = Nothing
Set directParent = Nothing
End If
Set TheActiveElement = Nothing
Set TargetIE = Nothing
End Sub

open file from path stored in access db when user clicks button on form

I'm new to Access VBA development and being asked to debug and add features to an Access 2007 application that two previous developers worked on.
A form displays records from a database and shows a button for each record. The button is supposed to open a file using the appropriate path. But when the user clicks the button, it always uses the filepath from the first record that the form displays, instead of the filepath from the correct record.
The code looks like it is trying to use a bookmark to open the correct file, but as stated above, that isn't working. Here is the relevant code from the button click event. When I try to Debug.Print form.Bookmark to the immediate window, it just displays a question mark.
Dim rs As Recordset
Set rs = form.RecordsetClone
rs.Bookmark = form.Bookmark
Edit: adding more code per #Remou's request. When button is clicked:
Private Sub OpenFile_Click()
Form_FilingProcess.Subform_cmdOpenFile_Click Me
End Sub
Which calls:
Public Sub Subform_cmdOpenFile_Click(frm As Form)
Set rs = frm.RecordsetClone
rs.Bookmark = frm.Bookmark
And then it goes on to open the file.
If the button is for each record, there is no need for any messing around with the recordset. You can use the name of the control to get the file:
TheFile=Me.MyControl
It seems that you have both a form and subform. I am guessing from your answers that the set-up is something like this:
|------------------------------|
| Main Form |
--------------------------------
Sub form
--------------------------------
Row Button
--------------------------------
Row Button
--------------------------------
If the name of the button is OpenFile, try:
Private Sub OpenFile_Click()
MsgBox Me.NameOfAContolHere & ""
'Form_FilingProcess.Subform_cmdOpenFile_Click Me
End Sub
This can then be used to ope a file like so:
Private Sub OpenFile_Click()
FollowHyperlink Me.NameOfControlWithPathToFile
'Form_FilingProcess.Subform_cmdOpenFile_Click Me
End Sub
Here is what your sub should look like:
Public Sub Subform_cmdOpenFile_Click(frm As Form)
Dim CurrentBookmark as String
Set rs = frm.RecordsetClone
CurrentBookmark = frm.Bookmark
rs.Bookmark = CurrentBookmark
End Sub
Set a string variable to the value of the form's bookmark. Then set the recordset's bookmark to the string variable value.
Dim rs As Recordset
dim CurrentBookmark as String
Set rs = Me.RecordsetClone
CurrentBookmark = Me.Bookmark
rs.Bookmark = CurrentBookmark
http://msdn.microsoft.com/en-us/library/aa223967(office.11).aspx