Load HTML file into VBA Microsoft Access Email - html

I am trying to load an HTML file into an email that gets sent by my Microsoft Access database. The email gets sent when the user clicks a button (Command109)
Here is my code that sends the email:
Private Sub Command109_Click()
'Start of code
Dim strEmail, strBody As String
Dim objOutlook As Outlook.Application
Dim objEmail As Outlook.MailItem
'Creates an instance of Outlook
Set objOutlook = CreateObject("Outlook.Application")
DoEvents
Set objEmail = objOutlook.CreateItem(olMailItem)
DoEvents
'Creates string with email address
strEmail = PayeeEmail
strBody = "WHAT SHOULD I PUT HERE TO LOAD AN EXTERNAL HTML FILE?"
DoEvents
'Creates and sends email
With objEmail
DoEvents
.To = strEmail
DoEvents
.Subject = "Your Distribution from " & COMPANY & " has been processed."
DoEvents
.HTMLBody = strBody
DoEvents
DoEvents
.Send
End With
Set objEmail = Nothing
'Closes Outlook. Remove if you do not want to close Outlook
'objOutlook.Quit
Exit Sub
End Sub
I have this other code that allows me to load an HTML file into Outlook, but I'm not sure how to combine the code - so that the HTML file gets loaded into the BODY of the email being sent by Access.
Here is the code I have for a macro that will load an HTML file into Outlook:
Sub insertHTML()
Dim insp As Inspector
Set insp = ActiveInspector
If insp.IsWordMail Then
Dim wordDoc As Word.Document
Set wordDoc = insp.WordEditor
wordDoc.Application.Selection.InsertFile "C:\Users\me\Desktop\emailtemplate.html",
, False, False, False
End If
End Sub
Can anyone help me figure this out? Thank you for your time!

To concatenate strings on multiple lines you must have a space between the '&' and '_' as they are separate operators.
strBody = "<html><p> some of my html text here" & _ 'Note the spaces
"more formatted html text here" & _
"even more formatted html text here" & _
"don't forget your closing html brackets</p></html>"
with objEmail
.to = strTo
.subject = strSubject
.HTMKBody = strBody
.send
end with
For ease of readability in the code you can even create a seperate module with just the email string, just make sure it's public so that it can be called.
public strBody as string = your string here

I'm not sure about importing an HTML file directly, however in the past I have just placed the HTML code straight into the module. This is possible because you're using the .HTMLBody instead of .Body. You can also insert variable into the HTML code this way.
Straight HTML string
strBody = "<html> YOUR HTML CODE HERE </html>"
HTML using VBA variables
strBody = "<html><p> This is an email from " & COMPANY & ". We value your business</p></html>"
Obviously this isn't ideal if the template will change frequently. When I've done this in the past I've just made a template in outlook, copied the HTML code into VBA and then inserted variables where I wanted them.
There is likely a better way to do this though.

Related

How to include "mailto" in body of email?

I send an email through Outlook. I am trying to put an email address link within the body of the email, so that one can click on it and an email opens.
E.g. "If you have any questions, please contact us at ABC", where the "ABC" is the link that represents email address, ABC#gmail.com (not the real address).
I understand, from scouring the web, this is the syntax:
<a href="mailto:ABC#gmail.com\>ABC\</a>
I borrowed code that uses HTML to format a message in the body of an email, and replaced a line with what I wanted.
I received a Compile Error (which I think is actually a syntax error in this case?).
When debugging, the "mailto" text was highlighted.
My insertion:
ABC mailbox
.HTMLBody = "\<HTML\>\<BODY\>\<a href="mailto:ABC#gmail.com"\>ABC mailbox\</a>\</BODY\>\</HTML\>"
Sub SendEmailformattext()
'Update by Extendoffice.com
Dim xRg As Range
Dim xRgEach As Range
Dim xRgVal As String
Dim xAddress As String
Dim OutlookApp As Object
Dim MItem As Object
On Error Resume Next
xAddress = ActiveWindow.RangeSelection.Address
Set xRg = Application.InputBox("Please select email address range", "KuTools For Excel", xAddress, , , , , 8)
If xRg Is Nothing Then Exit Sub
Application.ScreenUpdating = False
Set OutlookApp = CreateObject("Outlook.Application")
Set MItem = OutlookApp.CreateItem(olMailItem)
Set xRg = xRg.SpecialCells(xlCellTypeConstants, xlTextValues)
For Each xRgEach In xRg
xRgVal = xRgEach.Value
If xRgVal Like "?*#?*.?\*" Then
Set MItem = xOutApp.CreateItem(olMailItem)
With MItem
.Display
.To = xRgVal
.Subject = "Test"
.HTMLBody = "\<HTML\>\<BODY\>\<a href="mailto:ABC#gmail.com"\>ABC mailbox\</a>\</BODY\>\</HTML\>"
'.Send
End With
End If
Next
Set xMailOut = Nothing
UNCLASSIFIED
Set xOutApp = Nothing
Application.ScreenUpdating = True
End Sub
The original code worked so I know the mailto text is the problem.
Use the Chr(34) function if you need to use double quotes in the string:
.HTMLBody = "\<HTML\>\<BODY\>\**<a href="& Chr(34) & "mailto:ABC#gmail.com" & Chr(34) & "\>ABC mailbox\</a>**\</BODY\>\</HTML\>"

Set a web link to a "word" in a VBA email

If this email does not display properly, please click here.
I would like to be able to have the person in the email click on the word "here" and then it will take them to a website.
This is what I have bee using but it just puts the full link into the email.
mymsg = "<HTML><BODY>"
mymsg = "If this email does not display properly, please click " & "<A href=http://us.localnews.com/ov?mailing=3TVGZMLJ-WDS49&m2u=3TVGZMLK-3TVGZMLJ-12Z630I>URL Text</A>"
mymsg = mymsg & "</BODY></HYML>"
Keep it simple, no need for the HTML/BODY tags
Example
Option Explicit
Public Sub Example()
Dim OutApp As Object
Set OutApp = CreateObject("Outlook.Application")
Dim OutMail As Object
Set OutMail = OutApp.CreateItem(0)
With OutMail
.HTMLBody = "If this email does not display properly, please click " & _
"<A href=https://stackoverflow.com/>" & _
"Here</A>"
.Display
End With
End Sub
Make sure you are using HTMLBody Property
MSDN - HTMLBody Property
Returns or sets a String representing the HTML body of the specified item. The HTMLBody property should be an HTML syntax string. Read/write.

Splitting a report into separate emails with their individual reports

I am trying to send separate Employees a PDF/page of their section/report. The information is based on their EmployeeID (which is text not long number). So each person has their balance information on a page then there's a page break, and then next page shows the next person's details. With the code below, it does email each of the employees one page but it so happens to only email the first person's page to EVERYONE. Is it possible to somehow automate each week so that each user is emailed his/her individual page of the report?
Another error is that the email pop up one by one so I have to press send each time for over 200 people, and that the email seems to be sending to the email but then followed by #mailto:the email# for example email#email.com#mailto:email#email.com#
I just started Access and have been copying and scraping code off of places I have found online. Many thanks in advance, if you can assist!
Have a great day!
Private Sub cmdSendAll_Click()
Dim rsAccountNumber As DAO.Recordset
Dim strTo As Variant
Dim strSubject As String
Dim strMessageText As String
Set rsAccountNumber = CurrentDb.OpenRecordset("SELECT DISTINCT EmployeeID, [Email] FROM [queAutoUpdate]", dbOpenSnapshot)
Debug.Print strTo
With rsAccountNumber
Do Until .EOF
DoCmd.OpenReport "test", _
acViewPreview, _
WhereCondition:="EmployeeID = '" & !EmployeeID & "'", _
WindowMode:=acHidden
strTo = ![Email]
strSubject = "Updated Balance "
strMessageText = "Text Here"
DoCmd.SendObject ObjectType:=acSendReport, _
ObjectName:="test", _
OutputFormat:=acFormatPDF, _
To:=strTo, _
Subject:=strSubject, _
MESSAGETEXT:=strMessageText, _
EditMessage:=True
DoCmd.Close acReport, "Unaffirmed Report", acSaveNo
.MoveNext
Loop
.Close
End With
End Sub
Your opening a report called test and then closing another report called "Unaffirmed Report". You need to open and close the same report, in this case "test".
DoCmd.Close acReport, "test", acSaveNo. This should fix the employee data not updating, since the report remains open on the first employee.
To directly send the message you need change EditMessage:=True to EditMessage:=False.
Check the docs:
https://learn.microsoft.com/en-us/office/vba/api/access.docmd.sendobject
Also if you need to test this, set outlook in Offline mode, and run your code, check the messages in your Outbox to see if they're as expected. You can delete the messages from the Outbox to prevent them from being sent. Once you're finished with testing you can set Outlook back to Online Mode.
Regarding the email address issue, this comes automatically when using hyperlinks in your controls. You'll need to strip the extra part out with strTo = Left(![Email],InStr(![Email],"#")-1). Check your data if this will be valid for all email addresses. For a more advanced solution you can look at this post https://codekabinett.com/rdumps.php?Lang=2&targetDoc=access-hyperlink-data-type.
Code provided as reference, please see the post for the explanation.
'copied from https://codekabinett.com/rdumps.php?Lang=2&targetDoc=access-hyperlink-data-type
Public Function GetHyperlinkFullAddress(ByVal hyperlinkData As Variant, Optional ByVal removeMailto As Boolean) As Variant
Const SEPARATOR As String = "#"
Dim retVal As Variant
Dim tmpArr As Variant
If IsNull(hyperlinkData) Then
retVal = hyperlinkData
Else
If InStr(hyperlinkData, SEPARATOR) > 0 Then
' I append 4 separators at the end, so I don't have to worry about the
' lenght of the array returned by Split()
hyperlinkData = hyperlinkData & String(4, SEPARATOR)
tmpArr = Split(hyperlinkData, SEPARATOR)
If Len(tmpArr(1)) > 0 Then
retVal = tmpArr(1)
If Len(tmpArr(2)) > 0 Then
retVal = retVal & "#" & tmpArr(2)
End If
End If
Else
retVal = hyperlinkData
End If
If Left(retVal, 7) = "mailto:" Then
retVal = Mid(retVal, 8)
End If
End If
GetHyperlinkFullAddress = retVal
End Function
Consider using the MS Outlook object library to send emails. Whereas DoCmd.SendObject is a convenience handler, you control more of the process with initializing an Outlook application object and creating an Outlook email object setting all needed elements.
However, with this approach you need to first export your filtered report to PDF and then attach to email for final send. See inline comments for specific details.
Dim rsAccountNumber As DAO.Recordset
' CHECK Microsoft Outlook #.# Object Library UNDER Tools/References
Dim olApp As Outlook.Application, olEmail As Outlook.MailItem
Dim fileName As string, todayDate As String, strEmail As String
todayDate = Format(Date, "YYYY-MM-DD")
Set rsAccountNumber = CurrentDb.OpenRecordset("SELECT DISTINCT EmployeeID, [Email] FROM [queAutoUpdate]", dbOpenSnapshot)
Set olApp = New Outlook.Application
With rsAccountNumber
Do Until .EOF
' SETTING FILE NAME TO SAME PATH AS DATABASE (ADJUST AS NEEDED)
fileName = Application.CurrentProject.Path & "\Balance_Report_" & !EmployeeID & "_" & todayDate & ".pdf"
' OPEN AND EXPORT PDF TO FILE
DoCmd.OpenReport "test", acViewPreview, "EmployeeID = '" & !EmployeeID & "'"
' INTENTIONALLY LEAVE REPORT NAME BLANK FOR ABOVE FILTERED REPORT
DoCmd.OutputTo acReport, , acFormatPDF, fileName, False
DoCmd.Close acReport, "test"
' CREATE EMAIL OBJECT
strEmail = ![Email]
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
.Recipients.Add strEmail
.Subject = "Updated Balance"
.Body = "Text Here"
.Attachments.Add fileName ' ATTACH PDF REPORT
.Send ' SEND WITHOUT DISPLAY TO SCREEN
End With
Set olEmail = Nothing
.MoveNext
Loop
.Close
End With
MsgBox "All emails successfully sent!", vbInformation, "EMAIL STATUS"
Set rsAccountNumber = Nothing: Set olApp = Nothing

Embedding image in original size in HTML email

I am working with VBA through Access to create mail.
When I adjust an image size to less than the actual size, it embeds. When I omit size or put in as actual size, the image comes as an attachment.
Below is code snippet, miniplane.jpg comes as an attachment. Its actual size is 600x160. If I change in the code to 300x80 it shows.
Sub send_SHCmail()
'>>>> Declarations >>>>
Dim strPath As String
Dim strFileName As String
Set appOutLook = CreateObject("Outlook.Application")
Set MailOutLook = appOutLook.CreateItem(olMailItem)
Dim olApp As Object
Dim objMail As Object
Set SHCData1 = Nothing
Set SHCData2 = Nothing
'>>>> Email Creation and Outlook Error Loop >>>>
On Error Resume Next 'Keep going if there is an error
Set olApp = GetObject(, "Outlook.Application") 'See if Outlook is open
If Err Then 'Outlook is not open
Set olApp = CreateObject("Outlook.Application") 'Create a new instance
End If
'Create e-mail item
Set objMail = olApp.CreateItem(olMailItem)
With objMail
'Set body format to HTML
.BodyFormat = olFormathtml
.To = "no-reply#email.com"
.Bcc = SHCDistribution
.Sentonbehalfofname = "test#email.com"
.Subject = "Planning Report - " & Format(Now, "MMMM d, yyyy")
.Attachments.Add "\\local\Sdata\Logo-Facet-01.png", olByValue, 0
.Attachments.Add "\\local\Sdata\miniplane.jpg", olByValue, 0
.HTMLBody = "<!DOCTYPE html>"
'Body Header
.HTMLBody = .HTMLBody & "<html><head><body>"
.HTMLBody = .HTMLBody & "<img src=""cid:Logo-Facet-01.png"" alt=""Image Missing"" width=""215.6"" height=""96.53"" style=""display: block;"" />"
.HTMLBody = .HTMLBody & "<img src=""cid:miniplane.jpg"" alt=""Image Missing"" width=""600"" height=""160"" style=""display: block;"" />"
.Display
End With
End Sub
Firstly, don't use HTMLBody as an intermediate variable - reading and setting it is expensive. Use a local variable to build HTML , then set HTMLBody property only once.
If you are setting img tag through the src attribute, you must set the PR_ATTACH_CONTENT_ID property - see How to add images from resources folder as attachment and embed into outlook mail body in C#

Getting Access to send emails to dynamic addresses

This is in Access 2010 and I have virtually no experience or familiarity with VBA.
In my form (frmEmailLookup), I have combo boxes and list boxes and a subform set up so that when the user selects a building from cmbBuilding the remainder of the form populates with the data on that building, including the contact emails for up to 4 people in the building (lstBuildingRepEmail1, lstBuildingRepEmail2, lstBuildingRepEmail3, lstBuildingRepEmail4). I need a button (butEmailRecords) to generate an email with the query from the subform (qryBuildingAreaLookup) as an attachment. I can set up a macro that will something close, but it doesn't allow for dynamic email addresses. I don't want my users to have to go that far into the program to make updates.
Any help is appreciated and I know I'm asking for a lot of code writing help.
Here's what I've tried:
Option Compare Database
Private Sub butEmailRecords_Click()
Dim outputFileName As String
outputFileName = CurrentProject.Path & "\BuildingInventory" & ".xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "qryBuildingAreaLookup", outputFileName, True
On Error GoTo Error_Handler
Dim objOutlook As Outlook.Application
Dim objEmail As Outlook.MailItem
Set objOutlook = CreateObject("Outlook.application")
Set objEmail = objOutlook.CreateItem(olMailItem)
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("qryBuildinAreaLookup")
With rs
With objEmail
.To = tblBuilding.BuildingRep1
.To = tblBuilding.BuildingRep2
.To = tblBuilding.BuildingRep3
.To = tblBuilding.BuildingRep4
.Subject = "Look at this sample attachment"
.body = "The body doesn't matter, just the attachment"
.Attachments.Add "L:\Administration\FacilityInventoryDatabase\BuildingInventory.xls x"
.Send
'.ReadReceiptRequested
End With
Exit_Here:
Set objOutlook = Nothing
Exit Sub
Error_Handler:
MsgBox Err & ": " & Err.Description
Resume Exit_Here
End Sub
Here is the basics of what I use:
'Refers to Outlook's Application object
Dim appOutlook As Object
'Refers to an Outlook email message
Dim appOutlookMsg As Object
'Refers to an Outlook email recipient
Dim appOutlookRec As Object
'Create an Outlook session in the background
Set appOutlook = CreateObject("Outlook.Application")
'Create a new empty email message
Set appOutlookMsg = appOutlook.CreateItem(olMailItem)
'Using the new, empty message...
With appOutlookMsg
'SQL statement to grab emails
Set recordset = currentdb.openrecordset('SQL statement')
Do While Not recorset.EOF
Set appOutlookRec = .Recipients.Add(recordset.Email)
appOutlookRec.Type = olTo
recordset.MoveNext
Loop
.Subject = ....
.Body = ....
.Send
End With
and that's the basics of what I use. I'm a beginner so this may not be the best way, but it should be a start. (I also had to add Microsoft Oulook in the reference library.)
I use CDO objects to send messages because I prefer not to rely on Outlook (for anything).
There is quite a comprehensive article on using CDO to send mail (including downloadable VBA code) here:
http://www.cpearson.com/excel/Email.aspx