VBA CDO Sending old image in email body - vba

I'm using vba to send email using CDO (See below) it keeps pulling a old image from over 30 days ago for the email that it is sending out. Can anyone help?
Public Function sndmail(ByVal RecipientList As String, _
ByVal Subject As String, ByVal body As String, Optional ByVal Attachment As String, _
Optional ByVal cc As String)
Dim iMsg As Message
Dim iConf As Configuration
Dim strbody As String
Dim Flds As Variant
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
iConf.Load -1 ' CDO Source Defaults
Set Flds = iConf.Fields
With Flds
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "SMTP.xx.xyz.COM"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False
.Update
End With
With iMsg
Set .Configuration = iConf
.To = RecipientList
.cc = cc
.From = "chris#yoohoo.com"
.Subject = Subject
.HTMLBody = body
End With
iMsg.Send
End Function
...
imgfile = "C:\TEMP\FDW_Img.png"
imgfile2 = "C:\TEMP\FDW_DoD.png"
Set pp = New PowerPoint.Application
Set ppt = pp.Presentations.Open("C:\TEMP\bpp.pptx")
wbk1.Sheets("Summary by Modcode").Range("F22:Z28").Copy
ppt.Slides(1).Shapes.PasteSpecial (ppPasteBitmap)
ppt.Slides(1).Shapes(1).Export imgfile, ppShapeFormatPNG
ppt.Close
pp.Quit
DoEvents
'list of recipients
sndto = ""
'subject line for email
subj = "5 State Capital Finance Reports for " & Date
'body of email
bod = "Happy " & WeekdayName(Weekday(Date)) & "! <br>" & WeekdayName(Weekday(Date)) & "'s reports have been updated and can be found at the below links and snapshots can be found at the first weblink:<br><br>" & _
"<a href = a weblink here that currently works fine> Finance Website </a> <br>" & _
"<a href = another one here... works fine> Open vs Actuals </a> <br>" & _
"<a href = another one here... works fine> EE Report <a><br>" & _
"<a href = another one here... works fine> FDW Actuals <a>" & _
" <br> <br><img src='C:\Temp\FDW_img.png'><br><br>" & sig
'function to send email
sndmail sndto, subj, bod
Application.CutCopyMode = False
wbk1.Close False
This line is where it adds the image to the body of the email and it is adding an old image... the strange thing is that on the host pc if I pull up my email it shows correctly but on all other recipients or if I pull up my email on another pc it shows up with the old image.
" <br> <br><img src='C:\Temp\FDW_img.png'><br><br>" & sig

Related

Generate email body with values from MS Access userform

I created a form and would like to send an email using a button capturing data from the sub-form (based on a query).
I am using this YouTube video as a guide and get stuck (starting from msg =....
Private Sub cmd_EmailContact_Click()
Dim Msg As String
msg = "Dear " & First name & ",<P>" & _
Student First name & "has been successfully been loaded on the platform" & ",<P>" & _
"Student login details on the platform are:" & ",<P>" & _
"Username:" & Username & ",<P>" & _
"Password:" & Password**
Dim O As Outlook.Application
Dim M As Outlook.MailItem
Set O = New Outlook.Application
Set M = O.CreateItem(olMailItem)
With M
.BodyFormat = olFormatHTML
.HTMLBody = Msg
.To = Email
.Subject = "Student available on OARS"
.Display
End With
Set M = Nothing
Set O = Nothing
End Sub
Variables are populated on a query on the form.
First name (Name of teacher)
Student First name
Username
Password
To send the email as HTML, you will need to format the body with HTML tags and set the HTMLBody property of the olMailItem (email) as shown below.
The example uses late binding (no reference to Outlook needed) which means it can run with different versions of outlook installed.
Private Sub cmd_EmailContact_Click()
Dim firstName As String, _
studentFirstName As String, _
userName As String, _
password As String, _
email As String, _
body_ As String
'provide values
firstName = "ABC"
studentFirstName = "XYZ"
userName = "User"
password = "Pass"
email = "foo#bar.com"
'build body
body_ = "<p> Dear" & firstName & ", </p>" _
& "<p>" & studentFirstName & " has been successfully been loaded on the platform. </p>" _
& "<p> Student login details on the platform are: </p>" _
& "<p> Username: " & userName & "</p>" _
& "<p> Password: " & password & "</p>"
'send email
With CreateObject("Outlook.Application")
With .CreateItem(0) 'olMailItem
.BodyFormat = 2 'olFormatHTML
.To = email
.Subject = "Student available on OARS"
.HTMLBody = "<html><head></head><body>" & body_ & "</body></html>"
.Display
End With
End With
End Sub
You will need to provide values for the following variables:
FirstName
StudentFirstName
UserName
Password
Email

Display each email for manual editing before sending in a loop

I have over 200 emails to send with individual attachments.
The list is in Excel.
With code from elsewhere, I managed to open an email, with the attachment, email address, subject and body text.
I want the loop to pause once the email has been opened, so I can check the details, add in a signature etc. I then want the loop to move on to the next iteration but not until I click "Send".
Also, more minor point, but vbNewLine doesn't seem to create a new line?
Sub SendEmail_Example1()
Dim EmailApp As Outlook.Application
Dim Source As String
Dim Attachment As String
Dim edress As String
Set EmailApp = New Outlook.Application
Dim EmailItem As Outlook.MailItem
Set EmailItem = EmailApp.CreateItem(olMailItem)
i = 2
Do Until IsEmpty(Cells(i, 1))
Attachment = "C:\Users\username\Downloads\" + Cells(i, 4)
edress = Cells(i, 1)
EmailItem.To = edress
EmailItem.Subject = "Test Email From Excel VBA"
EmailItem.HTMLBody = "Hi," & vbNewLine & vbNewLine & _
"This is my first email from Excel" & _
vbNewLine & vbNewLine & _
"Regards," & vbNewLine & _
"VBA Coder"
Source = ThisWorkbook.FullName
EmailItem.Attachments.Add (Attachment)
EmailItem.Display
i = i + 1
Loop
Set EmailApp = Nothing
Set EmailItem = Nothing
End Sub
It's been 15 years since I tried this, but try the modal property on the EmailItem.Display method
https://learn.microsoft.com/en-us/office/vba/api/outlook.mailitem.display

How can I Include additional code to then send email via Vba through Gmail?

I have seen similar questions but mine is quite specific let me explain.
I have this code that runs from a button if clicked it prints the active sheet as a pdf to the same pathway as my workbook, this works as it should as the active sheet information changes via a list to present each customer info for each financial period.
Each month i then need to attach each of these pdf files to emails and send to customers which is a long winded process, if i input the email to appear in a cell eg ("E1") automatically when the customer is selected can i then adapt my code to open an email and send the pdf to that email address?
Sub PDFActiveSheet()
Dim ws As Worksheet
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
On Error GoTo errHandler
Set ws = ActiveSheet
'enter name and select folder for file
' start in current workbook folder
strFile = Replace(Replace(Range("B1"), "", ""), "", "") _
& " Period " _
& Format(Now(), Cells.Range("J1")) _
& ".pdf"
strFile = ThisWorkbook.Path & "\" & strFile
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If myFile <> "False" Then
ws.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
You can automate email sending through Outlook, but it seems like accessing Gmail and sending mail through the web would be a whole different ballpark. Gmail does have an API, which you can get documentation for here: https://developers.google.com/gmail/api/.
My suggestion is to setup Outlook with your Gmail account and then send through that, which is more likely way easier.
From Ron DeBruins website I found this and tested successfully. I did have to enable "All less secure apps" in my gmail settings. Here's the code in case his site ever goes down.
Sub CDO_Mail_Small_Text_2()
Dim iMsg As Object
Dim iConf As Object
Dim strbody As String
Dim Flds As Variant
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
iConf.Load -1 ' CDO Source Defaults
Set Flds = iConf.Fields
With Flds
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "Your gmail address"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "gmail pw"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Update
End With
strbody = "Hi there" & vbNewLine & vbNewLine & _
"This is line 1" & vbNewLine & _
"This is line 2" & vbNewLine & _
"This is line 3" & vbNewLine & _
"This is line 4"
With iMsg
Set .Configuration = iConf
.To = ""
.CC = ""
.BCC = ""
' Note: The reply address is not working if you use this Gmail example
' It will use your Gmail address automatic. But you can add this line
' to change the reply address .ReplyTo = "Reply#something.nl"
.From = """FROM??"" <Reply#something.nl>"
.Subject = "Important message"
.TextBody = strbody
.Send
End With
End Sub

Saving Excel file as PDF then send by Outlook as Attachment but no signature in the messge

I have some Excel VBA code which save active sheet as PDF then attach that PDF file to outlook new mail everything works fine except the signature in outlook when the code starts outlook and new message it does not show the signature despite its in HTML and I can already insert it manually.
so any adjustment to the code will be appreciated.
Sub Send_To_Pdf()
Dim PdfPath As String
Dim BoDy As String
BoDy = Msg = "Dear Mr. " & vbCrLf & vbCrLf & "Good Day" & vbCrLf & vbCrLf & "Kindly find the attahched P.O to be delivered to " & Cells(10, 12)
PdfPath = Save_as_pdf
EnvoiMail Right(PdfPath, InStr(1, StrReverse(PdfPath), "\") - 1), "recepient1#domain.com;recepient2#domain.com", , , BoDy, 1, PdfPath
End Sub
Public Function Save_as_pdf() As String
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = "C:\Users\" & Environ("UserName") & "\Desktop\" & ThisWorkbook.Name
If FSO.FileExists(ThisWorkbook.FullName) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=sNewFilePath, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
Save_as_pdf = sNewFilePath
End Function
Sub EnvoiMail(Subject As String, Destina As String, Optional CCdest As String, Optional CCIdest As String, Optional BoDyTxt As String, Optional NbPJ As Integer, Optional PjPaths As String)
Dim MonOutlook As Object
Dim MonMessage As Object
Set MonOutlook = CreateObject("Outlook.Application")
Set MonMessage = MonOutlook.createitem(0)
Dim PJ() As String
PJ() = Split(PjPaths, ";")
With MonMessage
.Subject = Subject '"Je suis content"
.To = Destina '"marcel#machin.com;julien#chose.com"
.cc = CCdest '"chef#machin.com;directeur#chose.com"
.bcc = CCIdest '"un.copain#supermail.com;une-amie#hotmail.com"
.BoDy = BoDyTxt
If PjPaths <> "" And NbPJ <> 0 Then
For i = 0 To NbPJ - 1
'MsgBox PJ(I)
.Attachments.Add PJ(i) '"C:\Mes Documents\Zoulie Image.gif"
Next i
End If
.display
'.send '.Attachments.Add ActiveWorkbook.FullName
End With '?plusieurs?MonMessage.Attachments.Add "D:\Prof\Janvier\Base clients.mdb"
Set MonOutlook = Nothing
End Sub
After a new message is created you need to insert a new text before the default signature (not to overwrite it), for example:
.BoDy = BoDyTxt
The default signature will be erased in that case.
.Body = BoDyTxt & .Body
In that case the text will be inserted in the beginning of the message leaving the signature as is.
The Outlook object model provides three different ways for working with item bodies:
Body - a plain text.
HTMLBody - an HTML markup.
The Word Editor. Outlook uses Word as an email editor, so you can use it to format the email message. The WordEditor property of the Inspector class returns an instance of the Document class which represents the message body.
You can read more about all these ways in the Chapter 17: Working with Item Bodies in MSDN.
thanks Eugene Astafiev
i changed some of the code and i got it worked after all
the changed part is as following:
Sub EnvoiMail(Subject As String, Destina As String, Optional CCdest As String, Optional CCIdest As String, Optional BoDyTxt As String, Optional NbPJ As Integer, Optional PjPaths As String)
Dim MonOutlook As Object
Dim MonMessage As Object
Dim strbody As String 'i added this part <<>>>'
Set MonOutlook = CreateObject("Outlook.Application")
Set MonMessage = MonOutlook.CreateItem(0)
strbody = "Hello" ' i put my messages here as well which i change it in my main code to get values from cells <<<<>>>'
Dim PJ() As String
PJ() = Split(PjPaths, ";")
With MonMessage
.Display ' <<<<< the most important part of the code which solved 50% of the problem >>>>'
.Subject = Subject
.To = Destina
.CC = CCdest
.BCC = CCIdest
.HTMLBoDy = strbody & "<br>" & .HTMLBoDy ' <<<< the second import part of the code and solved the other 50% >>>>> '
If PjPaths <> "" And NbPJ <> 0 Then
For i = 0 To NbPJ - 1
'MsgBox PJ(I)
.Attachments.Add PJ(i)
Next i
End If
.Display
'.send
End With
Set MonOutlook = Nothing
End Sub

How do send a link to a document using word vba CDO email process?

Does anybody know how to send a link to a word document via email in word vba? I want to use gmail not outlook. I found a solution for outlook:
http://www.rondebruin.nl/win/s1/outlook/bmail10.htm
Is there anyway that can be modified to work using gmail?
I modified: http://www.rondebruin.nl/win/s1/cdo.htm to work with gmail, and it is working fine. I just need to add a link to the body of the email.
You'll need to use the htmlBody property instead of TextBody and use an <a> tag in the HTML.
I didn't know how to send my code...So I posted it as an answer. Hope that's ok. Also I get a strange run time error that I wasn't getting before. Other than that it works.
Thanks!
Danielle
Option Explicit ' Modified for dSavage
'If you have a GMail account then you can try this example to use the GMail smtp server
'The example will send a small text message
'You must change four code lines before you can test the code
'.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "Full GMail mail address"
'.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "GMail password"
'Use your own mail address to test the code in this line
'.To = "Mail address receiver"
'Change YourName to the From name you want to use
'.From = """YourName"" "
'If you get this error : The transport failed to connect to the server
'then try changing the SMTP port from 25 to 465
Sub CDO_Mail_Example()
Dim iMsg As Object
Dim iConf As Object
Dim strbody As String
Dim sAddForm As String
Dim sForm As String
Dim Flds As Variant
Dim iSMTP_Port As Integer
Dim sFirstReviewer As String
Dim sUserName As String
Dim sGmailPassword As String
sFirstReviewer = Range("F4").Value
sUserName = Range("F6").Value & "#indicate1.com"
sGmailPassword = Range("F8").Value
iSMTP_Port = Range("F10").Value '25 at Indicate; 465 away.
sAddForm = Range("I12").Value
'sForm = Range("F4").Value
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
If sAddForm = "Yes" Then
sForm = "Z:\Quality# # Document_Development# Documents_for_Review\12002-01-01 Company Handbook.doc"
Else
sForm = ""
End If
Debug.Print "sForm = " & sForm ' *******************************************
Debug.Print "sUserName = " & sUserName ' *******************************************
iConf.Load -1 ' CDO Source Defaults
Set Flds = iConf.Fields
With Flds
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = sUserName
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "Micro5cope"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = iSMTP_Port '25 at Indicate; 465 away.
.Update
End With
strbody = "To " & sFirstReviewer & vbNewLine & vbNewLine & _
"This is line 1" & vbNewLine & _
"This is line 2" & vbNewLine & vbNewLine & _
"This is line 3" & vbNewLine & _
"This is line 4" & vbNewLine & vbNewLine & vbNewLine & _
"Z:\Quality\# # Document_Development\# Documents_for_Review\12000-00-00 Tables 9-11 Template OLD - TEST.doc" & vbNewLine & _
sForm & vbNewLine
With iMsg
Set .Configuration = iConf
.To = sFirstReviewer & "#indicate1.com"
.CC = "" 'sUserName & "; " & "johanson111#comcast.net"
.BCC = ""
.From = sUserName
.Subject = "Test Message"
.textbody = strbody
.HtmlBody = "Google Page"
.AddAttachment "Z:\Quality\# # Document_Development\12001-02-01 Document Review Form.pdf"
.AddAttachment "Z:\Quality\# # Document_Development\12001-02 Document Review Draft 9.doc"
.Send
End With
Debug.Print "CC = " & sUserName ' *******************************************
End Sub