Pictures pasted on the body of outlook email are not displayed - excel

I used the code below to copy a range from a file and paste it as a picture on emails, but there's a catch: if you donĀ“t use .display before .send, the picture will not be displayed to the receiver.
Does anyone know a way around this? Just to avoid the outlook window flashing on the screen.
Sub sendMail()
Dim olApp As Object
Dim NewMail As Object
Dim ChartName As String
Dim imgPath As String
Set olApp = CreateObject("Outlook.Application")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
tmpImageName = VBA.Environ$("temp") & "\tempo.jpg"
Workbooks.Open "C:\FilePath\File.xlsm"
Set RangeToSend = Workbooks("File.xlsm").Sheets(Name).Range(" ")
RangeToSend.CopyPicture Appearance:=xlScreen, Format:=xlPicture
Set sht = Sheets.Add
sht.Shapes.AddChart
sht.Shapes.Item(1).Select
Set objChart = ActiveChart
With objChart
.ChartArea.Height = RangeToSend.Height
.ChartArea.Width = RangeToSend.Width
.ChartArea.Fill.Visible = msoFalse
.ChartArea.Border.LineStyle = xlLineStyleNone
.Paste
.Export Filename:=tmpImageName, FilterName:="JPG"
End With
sht.Delete
Workbooks("File.xlsm").Close
Set NewMail = olApp.CreateItem(0)
With NewMail
.Subject = "Latest performance report" ' Replace this with your Subject
.To = "email#email.com" ' Replace it with your actual email
.HTMLBody = "<span LANG=EN>" _
& "<p class=style2><span LANG=EN><font FACE=Calibri SIZE=3>" _
& "Hello, this is the data range that you want:<br> " _
& "<br>" _
& "<img src=" & "'" & tmpImageName & "'/>" _
& "<br>" _
& "<img src=" & "'" & tmpImageName2 & "'/>" _
& "<br>" _
& "<br>Best Regards!</font></span>"
.Display
.Send
Set olApp = Nothing
Set NewMail = Nothing
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End With
End Sub

Looks like you are saving the picture captured in Excel to a disk. And then you are referring to the image in a newly created item body. But the image source still points to the file on your disk. So, the recipient will never get it shown correctly.
Instead, you need to attach a file and then add a reference in the message body.
Const PR_ATTACH_CONTENT_ID = "http://schemas.microsoft.com/mapi/proptag/0x3712001E"
Const PR_ATTACHMENT_HIDDEN = "http://schemas.microsoft.com/mapi/proptag/0x7FFE000B"
...
Set colAttach = mail.Attachments
Set l_Attach = colAttach.Add(path_to_the_file)
Set oPA = l_Attach.PropertyAccessor
oPA.SetProperty PR_ATTACH_CONTENT_ID, "itemID"
oPA.SetProperty PR_ATTACHMENT_HIDDEN, True
Then you can modify the message body in the following way:
.HTMLBody = "<span LANG=EN>" _
& "<p class=style2><span LANG=EN><font FACE=Calibri SIZE=3>" _
& "Hello, this is the data range that you want:<br> " _
& "<br>" _
& "<img src='cid:itemID'/>" _
& "<br>" _
& "<br>Best Regards!</font></span>"
.Send

Related

Using VBA to create an Outlook email in Excel and inserting multiple graphs as pictures

I have a sheet "Graphs" that basically contains all the information I need to send via Outlook email.
I managed to shovel together a macro that will extract the graphs, convert them as images and paste it to Outlook body email, along with some other information from the sheet.
My issue is, that sometimes there is less or more graphs being added to this sheet, and I am not sure how to loop that in the html section of the macro, so it will automatically adjust how many picture to declare and paste to the email body.
Section Private Sub export_chart() set up to extract all graphs as .jpg files.
But on the Private Sub Send_Automate_Mail() I have to declare them one by one:
.Attachments.Add file_path & "Chart_1.jpg"
.Attachments.Add file_path & "Chart_2.jpg"
And add them one by one on the html section:
"<img src='cid:Chart_1.jpg'" & "width='1000' height='460'>" & "<br>" & "<p>" & _
"<img src='cid:Chart_2.jpg'" & "width='450' height='265'>" & _
But because the number of charts are changing, I wonder if there is a way to do this part as a loop as long as there are Chart_1.jpg, Chart_2.jpg... files are present.
I am only a beginner of that kind of coding, could someone help me out please?
My current code below. I am happy for any suggestions or a completely new code if there is an easier method out there, I'm kind of lost at this point!
I know there is an easy way to just send the whole sheet as is, but I cannot do that because recipients are having problem viewing (big gaps in-between graphs; email loading slowly). So I have to convert the graphs to pictures.
Thank you in advance!
Option Explicit
Dim folder_path As String
Dim chart_no As Integer
Dim file_path As String
Sub mail_2_IBUhead()
Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String
Dim rng As Range
Dim x As Integer, y As Integer
Dim total_Resource As Integer
Application.ScreenUpdating = False
Sheets("Graphs").Select
Call export_chart
Call Send_Automate_Mail
'Delete the htm file we used in this function
Kill file_path & "Chart_1.jpg"
Kill file_path & "Chart_2.jpg"
Kill file_path & "Chart_3.jpg"
Kill file_path & "Chart_4.jpg"
Kill file_path & "Chart_5.jpg"
Kill file_path & "Chart_6.jpg"
Kill file_path & "Chart_7.jpg"
Kill file_path & "Chart_8.jpg"
Kill file_path & "Chart_9.jpg"
Kill file_path & "Chart_10.jpg"
MsgBox "Draft Mails have been generated", vbDefaultButton1, "Mail Drafted!"
End Sub
Private Sub Send_Automate_Mail()
' This macro would only send the mail
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim strbody_1 As String, strbody_2 As String, strbody_3 As String
' Dim Start_row As Integer, Start_column As Integer, End_row As Integer, End_Column As Integer
' selecting the entire table range in the sheet
Sheets("Graphs").Select
Range("A:P").Select
Set rng = Selection.SpecialCells(xlCellTypeVisible)
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected. " & _
vbNewLine & "Please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strbody_1 = "<BODY style=font-size:11pt;font-family:Calibri>Good morning all,<p>" & _
" Please see MTO update for today, <br> </BODY> "
strbody_2 = "<BODY style=font-size:11pt;font-family:Calibri>" & _
" "
strbody_3 = "<BODY style=font-size:11pt;font-family:Calibri> " & _
" </BODY> "
file_path = folder_path & "\"
With OutMail
.To = ""
.CC = ""
.BCC = ""
.Subject = "BE. RawData"
.Attachments.Add file_path & "Chart_1.jpg"
.Attachments.Add file_path & "Chart_2.jpg"
.Attachments.Add file_path & "Chart_3.jpg"
.Attachments.Add file_path & "Chart_4.jpg"
.Attachments.Add file_path & "Chart_5.jpg"
.Attachments.Add file_path & "Chart_6.jpg"
.Attachments.Add file_path & "Chart_7.jpg"
.Attachments.Add file_path & "Chart_8.jpg"
.Attachments.Add file_path & "Chart_9.jpg"
.Attachments.Add file_path & "Chart_10.jpg"
.htmlbody = strbody_1 & "<p>" & "<p>" & _
"<img src='cid:Chart_1.jpg'" & "width='1000' height='460'>" & "<br>" & "<p>" & _
"<img src='cid:Chart_2.jpg'" & "width='450' height='265'>" & _
"<img src='cid:Chart_3.jpg'" & "width='450' height='265'>" & _
"<img src='cid:Chart_4.jpg'" & "width='450' height='265'>" & "<br>" & "<p>" & _
"<img src='cid:Chart_5.jpg'" & "width='650' height='300'>" & _
"<img src='cid:Chart_6.jpg'" & "width='650' height='300'>" & "<br>" & "<p>" & _
"<img src='cid:Chart_7.jpg'" & "width='650' height='300'>" & "<br>" & "<p>" & _
"<img src='cid:Chart_8.jpg'" & "width='450' height='265'>" & _
"<img src='cid:Chart_9.jpg'" & "width='450' height='265'>" & "<br>" & "<p>" & _
"<img src='cid:Chart_10.jpg'" & "width='1000' height='460'>" & "<br>" & "<p>" & _
RangetoHTML(rng) & "<br>" & _
strbody_3
.Importance = 2
' display the e-mail message, change it to ".send" to send the mail on running the macro
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' this function is used in code "Send_Automate_Mail"
' do not change the code if you are new to coding :)
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", "align=left x:publishsource=")
TempWB.Close savechanges:=False
'Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
Private Sub export_chart()
' this code will export all the graphs present in the sheet
Dim objCht As ChartObject
Dim myPic As Shape
Dim tempChartObj As ChartObject
Dim x As Integer
folder_path = Application.ActiveWorkbook.Path
' for each graph present in the sheet, it will get exported
Sheets("Graphs").Select
x = 1
For Each objCht In ActiveSheet.ChartObjects
objCht.Chart.Export folder_path & "\Chart_" & x & ".jpg", "JPG"
x = x + 1
Next objCht
End Sub

Combine code to attach pdf and screenshot

I have two pieces of code that work independently.
I would like to add a button to my sheet to do both. In other words to create the email with the screenshot generated by ScreenShotResults4() and attach the pdf generated by PrintPIP_To_PDF().
I tried combining but got syntax errors. I cobble code together with the help of sites like this.
Public Sub ScreenShotResults4()
Dim rng As Range
Dim olApp As Object
Dim Email As Object
Dim Sht As Excel.Worksheet
Dim wdDoc As Word.Document
Set rng = Sheets("Summary").Range("B21:N37")
rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set olApp = CreateObject("Outlook.Application")
Set Email = olApp.CreateItem(0)
Set wdDoc = Email.GetInspector.WordEditor
'strbody = "See production data for most recent 3 months. "
With Email
.To = Worksheets("Summary").Range("B21").Value
.Subject = "12 Month LO Production Lookback for " & Worksheets("Summary").Range("B21").Value & " (" & Worksheets("Summary").Range("B23").Value & "- " & Worksheets("Summary").Range("B35").Value & ")"
'.HTMLBody = "<BODY style=font-size:12.5pt;font-family:Calibri>" & "</p>" & strbody & RangetoHTML(rng) & Signature
.Display
wdDoc.Range.PasteAndFormat Type:=wdChartPicture
'if need setup inlineshapes hight & width
With wdDoc.Content
'--- paste the range image first, because it overwrites
' everything in the document
.PasteAndFormat Type:=wdChartPicture
'--- now add our greeting at the start of the email
.InsertBefore "See 12 month production data. " & vbCr & vbCr
'--- finally add our sign off after the image
.InsertAfter vbCr & _
"Thank you" & vbCr & vbCr
End With
.Display
End With
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set Email = Nothing
Set olApp = Nothing
End Sub
Sub PrintPIP_To_PDF()
Application.EnableEvents = True
ActiveSheet.Unprotect Password:="Mortgage1"
Dim PrintRng As Range
Dim pdfile As String
'Setting range to be printed
Set PrintRng = Worksheets("PIP").Range("B3:M27")
'Range("B25:C25").Font.Color = RGB(255, 255, 255)
sPath = Environ("USERPROFILE") & "\Desktop\"
pdfile = Application.GetSaveAsFilename _
(InitialFileName:=sPath & "PIP" & " " & Worksheets("Summary").Range("B21").Value, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
Filename = pdfile
If Filename = False Then
Exit Sub
Else
PrintRng.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=pdfile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Call MsgBox(pdfile & " file has been saved!")
ActiveSheet.Protect Password:="Mortgage1"
End If
End Sub
pls try this.
after displaying draft email .Display
use .Attachment.Add "C:\Test.pdf"
also if u wish to, u can save a copy of draft email (before sending) using
.SaveAs "C:\OutLookDrafts\Draft1.msg"

Outlook image error when pasting a range as a picture

I have this code that emails a range as a picture via outlook. The problem is that the recipients are getting the outlook error "The linked image cannot be displayed. The file may have been moved, renamed, or deleted. Verify that the link points to the correct file and location."
Anyone know how I can fix this?
Sub RectangleRoundedCorners1_Click()
ActiveSheet.Unprotect Password:="Mortgage1"
Dim TempFilePath As String
Dim xOutApp As Object
Dim xOutMail As Object
Dim xHTMLBody As String
Dim xRg As Range
On Error Resume Next
Set xRg = ActiveSheet.Range("C5:F17")
If xRg Is Nothing Then Exit Sub
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
ActiveSheet.Shapes("Rectangle: Rounded Corners 13").Visible = False
Set xOutApp = CreateObject("outlook.application")
Set xOutMail = xOutApp.CreateItem(olMailItem)
Call createJpg(ActiveSheet.Name, xRg.Address, "DashboardFile")
TempFilePath = Environ$("temp") & "\"
xHTMLBody = "<span LANG=EN>" _
& "<p class=style2><span LANG=EN><font FACE=Calibri SIZE=3>" _
& "<img src='cid:DashboardFile.jpg'>" _
'& "<br> "
StrBody = "<br />" & "<b><FONT SIZE = 5><font color=red>Rates are subject to change
without notice</b></FONT SIZE = 5></font color=red>"
With xOutMail
.Subject = "Bench Mark Rates" & " " & Date
.HTMLBody = xHTMLBody & StrBody
.Attachments.Add TempFilePath & "DashboardFile.jpg", olByValue
.To = "mcerrato#hotmail.com
.cc = "mcerrato#loandepot.com"
.Display
End With
ActiveSheet.Shapes("Rectangle: Rounded Corners 13").Visible = True
ActiveSheet.Protect Password:="Mortgage1"
End Sub
Just try so switch this two lines
As is
.HTMLBody = xHTMLBody & StrBody
.Attachments.Add TempFilePath & "DashboardFile.jpg", olByValue
To be
.Attachments.Add TempFilePath & "DashboardFile.jpg", olByValue
.HTMLBody = xHTMLBody & StrBody

Need help attaching a pdf file that I am saving into an email

Currently my code is below. It works well but for some reason it will not let me attach the file that I am saving. I have tried rewriting it several times but it won't work. Please let me know if there is an easy fix to this.
Sub Email_Sheet_Click()
Dim objOutlook As Object
Dim objMail As Object
Dim signature As String
Dim oWB As Workbook
Set oWB = ActiveWorkbook
s = Range("F9").Value
'
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
s, Quality:=xlQualityStandard, IncludeDocProperties _
:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
PDF_File = "Q:\227_Saginaw\Texas\UFPIndustrial RFQ Quotes" & Format(Now, "YYMMDD") & ActiveSheet.Range("F6") & ".pdf"
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
With objMail
.Display
End With
signature = objMail.HTMLBody
With objMail
.To = ActiveSheet.Range("F6")
.Subject = ActiveSheet.Range("F11")
.HTMLBody = "<font face=" & Chr(34) & "Calibri" & Chr(34) & " size=" & Chr(34) & 4 & Chr(34) & ">" & ActiveSheet.Range("F12") & "<br> <br>" & "Insert email body here" & "<br> <br>" & signature & "</font>"
End With
Set objOutlook = Nothing
Set objMail = Nothing
End Sub
Thanks

Excel VBA delete email after sending

might be you are able to help me with VBA code.
I got a code that send as PDF part of excel sheet.
Problem is that email is used by many people and sometimes text is confidential. Is there an option to delete email (sent items and deleted items) after email is sent?
Using office 2000
Here is my existing code.
Sub SendDDocs()
Dim IsCreated As Boolean
Dim PdfFile As String, Title As String
Dim OutlApp As Object
Dim rng As Range
Set rng = Range("A1:J103")
Title = Range("o1")
Title = Range("o1").Value & " Confidetial"
PdfFile = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" & Title & ".pdf"
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
On Error Resume Next
Set OutlApp = GetObject(, "Outlook.Application")
If Err Then
Set OutlApp = CreateObject("Outlook.Application")
IsCreated = True
End If
OutlApp.Visible = True
On Error GoTo 0
With OutlApp.CreateItem(0)
.Subject = Title
.To = "email#email.com"
.CC = "email#email.com"
.Body = "" & vbLf & vbLf _
& "a" & vbLf & vbLf _
& "" & vbLf _
& Application.UserName & vbLf & vbLf
.Attachments.Add PdfFile
Application.Visible = True
.Display
End With
Kill PdfFile
If IsCreated Then OutlApp.Quit
Set OutlApp = Nothing
End Sub
Instead of .Display use
.DeleteAfterSubmit = True
.Send
to not save a copy in sent items.
See MailItem.DeleteAfterSubmit Property (Outlook).

Resources