I have a macro to send some emails, but the embed images goes with a "x" to the recievers.
My email have: anex, body text and the embed images.
Option Explicit
Dim lsave As String
Sub Arquivoanex()
Application.DisplayAlerts = False
Dim OutApp As Object
Dim OutMail As Object
Dim oEmail As Object
Dim strBody As String
Dim line As String
Dim subject As String
Dim destine As String
Dim anex As String
Dim product As String
Dim unit As String
Dim retval As String
Dim anex_name As String
Dim validation As String
Dim signature As String
line = 3
product = "x"
Do While product <> ""
Set oEmail = CreateObject("CDO.Message")
product = Sheets("Send_Emails").Range("M" & line)
unit = Sheets("Send_Emails").Range("N" & line)
destine = Sheets("Send_Emails").Range("O" & line)
subject = Sheets("Send_Emails").Range("P" & line)
anex = Sheets("Send_Emails").Range("Q" & line)
anex_name = Sheets("Send_Emails").Range("R" & line)
validation = Sheets("Send_Emails").Range("L" & line)
signature = "\\...\signature.png"
Sheets("Send_Emails").Range("S1") = product
retval = Dir(anex)
If retval = anex_name Then
Else
GoTo next_anex
End If
If anex = "" Then
GoTo next_anex
End If
Sheets("Send_Emails").Select
ActiveSheet.Calculate
Select Case product
Case Is = "X"
Sheets("X").Select
Range("K3") = unit
ActiveSheet.Calculate
Case Is = "Y"
If validation = "Send" Then
Sheets("Y").Select
Range("K3") = unit
ActiveSheet.Calculate
Else: GoTo next_anex
End If
End Select
On Error Resume Next
Call lCriarImagem 'Creates the image and give the location
strBody = Sheets("Send_Emails").Range("B9") & "<img src=""cid:TempExportChart.bmp""height=520 width=750>" & "<br/><br/>TKS! <br/><br/></body>"
MailItem.Attachments.Add FName, 1, 0
With oEmail
.Display
oEmail.From = "mail_from#mail"
oEmail.To = "mail_to#mail"
oEmail.subject = subject
oEmail.Attachments.Add FName, 1, 0
oEmail.AddAttachment anex
oEmail.HTMLBody = strBody & .HTMLBody
oEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
oEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "myserver.server"
oEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/authenticate") = 1
oEmail.Configuration.Fields.Update
oEmail.Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
next_anex:
line = line + 1
Loop
Application.DisplayAlerts = True
End Sub
It's posible to fix this problems using this code structure?
Obs: This is the code after all the sugestions.
I still facing the problems with the "X" on the email:https://ibb.co/0hX6Dvf ("The photo cannot be show. Maybe the file cam be moved, renamed or excluded. Verify if the destiny is in the correct location").
You need to add the images as file attachments, set the "content-id" MIME header on these attachment MIME parts, and make suire teh HTML body refers to the image attachents by content id (e.g. <img src="cid:my-xcontent-id">).
You need to add the image and hide it. The position 0 will add and hide it.
MailItem.Attachments.Add Fname, 1, 0
The 1 is the Outlook Constant olByValue.
Once you add the image then you have to use "cid:FILENAME.jpg" as shown below. For example:
With OutMail
.To = tName
.Subject = "Hello world!"
.Attachments.Add Fname, 1, 0
.HTMLBody = "<img src=""cid:Claims.jpg""height=520 width=750>"
.Display
End With
Also, you may set the attachment content ID explicitly:
Function SendasAttachment(fName As String)
Dim olApp As Outlook.Application
Dim olMsg As Outlook.MailItem
Dim olAtt As Outlook.Attachments
Set olApp = Outlook.Application
Set olMsg = olApp.CreateItem(0) ' email
Set olAtt = olMsg.Attachments
Const PR_ATTACH_MIME_TAG = "http://schemas.microsoft.com/mapi/proptag/0x370E001E"
Const PR_ATTACH_CONTENT_ID = "http://schemas.microsoft.com/mapi/proptag/0x3712001E"
Const PR_ATTACHMENT_HIDDEN = "http://schemas.microsoft.com/mapi/proptag/0x7FFE000B"
' attach file
olAtt.Add (fldName & fName)
Set l_Attach = olAtt.Add(fldName & fName)
Set oPA = l_Attach.PropertyAccessor
oPA.SetProperty PR_ATTACH_MIME_TAG, "image/jpeg"
oPA.SetProperty PR_ATTACH_CONTENT_ID, "myident"
oPA.SetProperty PR_ATTACHMENT_HIDDEN, True
olMsg.PropertyAccessor.SetProperty "http://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/8514000B", True
olMsg.To = "test#somedomain.com"
msgHTMLBody = "<HTML>" & _
"<head>" & _
"</head>" & _
"<BODY>" & "Hi " & olMsg.To & ", <br /><br /> I have attached " & fName & " as you requested." & _
"<br /><img align=baseline border=1 hspace=0 src=cid:myident width='400'/>" & _
"</BODY></HTML>"
' send message
With olMsg
.Subject = "Hello world!"
.BodyFormat = olFormatHTML
.HTMLBody = msgHTMLBody
.Save
'.Display
.Send
End With
End Function
Related
When I go to sent emails with the code below it sends a previous version of the email. It doesn't reset.
Private Sub CommandButton16_Click()
Dim EmailApp As Outlook.Application
Dim EmailItem As Outlook.MailItem
Set EmailApp = New Outlook.Application
Dim EmailAddress As String
Dim EmpName As String
Dim ProvName As String
Dim PayMonth As String
Dim Filename As String
Dim Filepath As String
Dim FileExists As String
Dim Subject As String
Dim Source As String
Dim AltEmail As String
Dim ExtraMsg As String
Dim i As Long
'Loop through and get email address and names
i = 2
PayMonth = TextBox6.Value
AltEmail = TextBox7.Value
ExtraMsg = TextBox8.Value
Do While Worksheets("Provider Template").Cells(i, 1).Value <> ""
ProvName = Worksheets("Provider Template").Cells(i, 1).Value
EmpName = Worksheets("Provider Template").Cells(i, 11).Value
If AltEmail = "" Then EmailAddress = Worksheets("Provider Template").Cells(i, 20).Value Else EmailAddress = AltEmail
Filename = ProvName & " " & PayMonth
Filepath = ThisWorkbook.Path & "\Remittance PDFs\"
Source = Filepath & Filename & ".pdf"
Subject = "Monthly Remittance Advice for" & " " & ProvName & " - " & PayMonth
FileExists = Dir(Source)
If FileExists = "" Then GoTo Lastline Else GoTo SendEmail
SendEmail:
Set EmailItem = EmailApp.CreateItem(olMailItem)
With EmailItem
EmailItem.To = EmailAddress
EmailItem.CC = "******************"
EmailItem.Subject = Subject
EmailItem.HTMLBody = "<html><body><p>Here is the tax invoice and calculation sheet for " & ProvName & ".</p><p>" & ExtraMsg & "</p><p>Kind regards, ******</p><p>****** ******</p><p>Practice Manager</p></body></html>"
EmailItem.Attachments.Add Source
EmailItem.Send
End With
GoTo Lastline
Lastline:
i = i + 1
Loop
End Sub
I thought it was a problem in the code then I ran it on a different machine and fresh emails were sent. I uploaded the updated version to a work machine and the old emails are going again, like there is a cache of this stuff somewhere.
You can try to check your "Sent" box in outlook next time. It's possible that outlook did'nt sent them (offline or other reason),thety are still there as a draft. That could be the reason that they where sent later.
And adjust:
With EmailItem .To = EmailAddress
And you can leave this out;
GoTo Lastline Lastline:
I have a list of names, email, attachment name and I need to send email and attach these attachment, my macro worked if I specify number of attachment, but what I have is not a fix number of attachments for each name/email, sometimes it's one and sometimes more than 1. Can you check my macro and advise what should I change/add in order to make the attachment dynamic?
Sub CreateNewMessage()
Dim aOutlook As Object
Dim aEmail As Object
Dim obj As Object
Dim olInsp As Object
Dim myDoc As Object
Dim oRng As Object
Set aOutlook = CreateObject("Outlook.Application")
Set aEmail = aOutlook.CreateItem(0)
Dim ToCc As Range, strBody, strSig As String
Dim fColorBlue, fColorGreen, fColorRed, fDukeBlue1, fDukeBlue2, fAggieMaroon, fAggieGray As String
Dim Greeting, emailContent As String
Dim emailOpen, emailMid1, emailMid2, emailMid3, emailClose, emailCustom, emailSig As String
Dim AttachmentPath, AttachmentNm As String
AttachmentPath = [O1] & "\"
fColorBlue = "#003846"
fColorGreen = "#5e9732"
fColorRed = "#FF0000"
fDukeBlue1 = "#001A57"
fDukeBlue2 = "#00009C"
fAggieMaroon = "#500000"
fAggieGray = "#332C2C"
For Each ToCc In ActiveSheet.[A2:A100] 'This is the range for how many records (rows) you want to send email
'=============================================================
Dim ToEmail, CcEmail, ToNm, CcNm, CcLNm As String
Dim DescrDt, LocID, LsmID, DescrNm As String
Dim Attach1, Attach2, Attach3 As String
ToNm = Cells(ToCc.Row, [To___fName].Column).Value
CcNm = Cells(ToCc.Row, [Cc___fName].Column).Value
CcLNm = Cells(ToCc.Row, [Cc___LName].Column).Value
ToEmail = Cells(ToCc.Row, [To___Email].Column).Value
CcEmail = Cells(ToCc.Row, [Cc___Email].Column).Value
Attach1 = Cells(ToCc.Row, [Attachment1].Column).Value
Attach2 = Cells(ToCc.Row, [Attachment2].Column).Value
Attach3 = Cells(ToCc.Row, [Attachment3].Column).Value
AttachmentNm1 = Attach1
AttachmentNm2 = Attach2
AttachmentNm3 = Attach3
Dim FileAttach1 As String
Dim FileAttach2 As String
Dim FileAttach3 As String
FileAttach1 = AttachmentPath & AttachmentNm1
FileAttach2 = AttachmentPath & AttachmentNm2
FileAttach3 = AttachmentPath & AttachmentNm3
'MsgBox FileAttach1
'MsgBox FileAttach2
'MsgBox FileAttach3
'Exit Sub
'=============================================================
Set aEmail = aOutlook.CreateItem(0)
With aEmail
'.SentOnBehalfOfName = "name#company.com"
.SentOnBehalfOfName = "name2#company.com"
.To = ToEmail
.cc = CcEmail '& "; " & SupvEmail & "; " & HREmail
.Subject = "LSM Monthly Dashboard " & Application.WorksheetFunction.Proper(ToNm) & Chr(32) & Application.WorksheetFunction.Proper(DescrNm)
'.BodyFormat = olFormatPlain ' send plain text message
'.BodyFormat = olFormatHTML
'.Importance = olImportanceHigh
'.Sensitivity = olConfidential
.HTMLBody = emailContent
'MsgBox FileAttach1
.Attachments.Add FileAttach1
.Attachments.Add FileAttach2
.Attachments.Add FileAttach3
.display
' .send
End With
NEXT_ToCC:
Set aEmail = Nothing
Set olInsp = Nothing
Set myDoc = Nothing
Set oRng = Nothing
Next ToCc
End Sub
You should use array to do this.
Add files paths to an array.
Dim files()
Files = array(path1, path2)
And after ‚htmlbody’ write:
For i = lbound(files) to ubound(files)
.attachments.add files(i)
Next i
I'm trying to send an email with the body of the message consisting of the contents of a text box. So far I've tried pulling in the text box through vba as a string, but that takes away all the new-lines formatting. Is there a way to get the text box contents exactly as they are into the email?
Sub Send_Email()
Dim OutApp As Object
Dim OutMail As Object
Dim title As String, emailto As String
Dim texts As String
title = Range("email_subject").Value
emailto = Range("email_to").Value
texts = Worksheets("Input").Shapes("TextBox 2").TextFrame.Characters.Text
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = emailto
.Subject = title
.HTMLBody = texts
.display
End With
On Error GoTo 0
End Sub
Please find an example below that might help with your question. You will have global variable that will hold information from excel worksheet and use them in the email. Whithout a image on how your data looks cannot really guess what you are trying to do. Maybe you can separete the text in different cells that way you can loop throught and put them in different variables and you can construct your email in the SendEmail procedure. Or if you have the same text and it doesn't change you can make it as per the below example.
Option Explicit
Dim titleName As String
Dim firstName As String
Dim lastName As String
Dim fullName As String
Dim clientEmail As String
Dim ccEmail As String
Dim bccEmail As String
Dim emailMessage As String
Sub GenerateInfo()
Dim WS As Worksheet
Dim lrow As Long
Dim cRow As Long
Set WS = ActiveSheet
With WS
lrow = .Range("E" & .Rows.Count).End(xlUp).Row
Application.ScreenUpdating = False
For cRow = 2 To lrow
If Not .Range("L" & cRow).value = "" Then
titleName = .Range("D" & cRow).value
firstName = .Range("E" & cRow).value
lastName = .Range("F" & cRow).value
fullName = firstName & " " & lastName
clientEmail = .Range("L" & cRow).value
Call SendEmail
.Range("Y" & cRow).value = "Yes"
.Range("Y" & cRow).Font.Color = vbGreen
Else
.Range("Y" & cRow).value = "No"
.Range("Y" & cRow).Font.Color = vbRed
End If
Next cRow
End With
Application.ScreenUpdating = True
MsgBox "Process completed!", vbInformation
End Sub
Sub SendEmail()
Dim outlookApp As Object
Dim outlookMail As Object
Dim sigString As String
Dim Signature As String
Dim insertPhoto As String
Dim photoSize As String
Set outlookApp = CreateObject("Outlook.Application")
Set outlookMail = outlookApp.CreateItem(0)
'Change only Mysig.htm to the name of your signature
sigString = Environ("appdata") & _
"\Microsoft\Signatures\Marius.htm"
If Dir(sigString) <> "" Then
Signature = GetBoiler(sigString)
Else
Signature = ""
End If
insertPhoto = "C:\Users\marius\Desktop\Presale.jpg" 'Picture path
photoSize = "<img src=""cid:Presale.jpg""height=400 width=400>" 'Change image name here
emailMessage = "<BODY style=font-size:11pt;font-family:Calibri>Dear " & titleName & " " & fullName & "," & _
"<p>I hope my email will find you very well." & _
"<p>Our <strong>sales preview</strong> starts on Thursday the 22nd until Sunday the 25th of November." & _
"<p>I look forward to welcoming you into the store to shop on preview.<p>" & _
"<p> It really is the perfect opportunity to get some fabulous pieces for the fast approaching festive season." & _
"<p>Please feel free to contact me and book an appointment." & _
"<p>I look forward to seeing you then." & _
"<p>" & photoSize & _
"<p>Kind Regards," & _
"<br>" & _
"<br><strong>Marius</strong>" & _
"<br>Assistant Store Manager" & _
"<p>"
With outlookMail
.To = clientEmail
.CC = ""
.BCC = ""
.Subject = "PRIVATE SALE"
.BodyFormat = 2
.Attachments.Add insertPhoto, 1, 0
.HTMLBody = emailMessage & Signature 'Including photo insert and signature
'.HTMLBody = emailMessage & Signature 'Only signature
.Importance = 2
.ReadReceiptRequested = True
.Display
.Send
End With
Set outlookApp = Nothing
Set outlookMail = Nothing
End Sub
Function GetBoiler(ByVal sFile As String) As String
Dim fso As Object
Dim ts As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
GetBoiler = ts.readall
ts.Close
End Function
I'm attempting to add attach a file to an email created from a template. The idea is to be able to use the File Picker to select multiple files and excel sends an email to the proper recipients with the correct attachments.
The problem is that I cannot use the ".Display" method without getting an error and I want to review the email before sending so I do not want to use ".Send".
However, for whatever reason, if I clear the email template body with ".Body = ''", I am able to Display the email and attach the correct file. I'd like to keep the email body from the template as is though without clearing it and rewriting it.
So it seems that I cannot use an email template if I want to first display before sending? Has anyone ever had this problem or know how to solve?
The Error message is:
'-2147221233(8004010f)' The attempted operation failed. An object could not be found.
Btw, most of the variables are declared globally so that is why they are not visible.
Dim Agency As String
Dim xfullName As Variant
Dim Template As String
Dim mail As Outlook.mailItem
Dim myOlApp As Outlook.Application
Dim selectedFile As Variant
Dim emailBody As String
Dim emailType As String
Dim recipients As String
Sub Recall_Email()
Dim fileName As String
Dim inputFile As FileDialog
Set myOlApp = CreateObject("Outlook.Application")
Set inputFile = Application.FileDialog(msoFileDialogFilePicker)
Template = "C:\Users\me\AppData\Roaming\Microsoft\Templates\Recall Templates\Recall Template.oft"
With inputFile
.AllowMultiSelect = True
If .Show = False Then Exit Sub
End With
For Each selectedFile In inputFile.SelectedItems
xfullName = selectedFile
fileName = Mid(inputFile.SelectedItems(1), InStrRev(inputFile.SelectedItems(1), "\") + 1, Len(inputFile.SelectedItems(1)))
Agency = Left(fileName, 3)
CreateTemplate(Template)
Next selectedFile
End Sub
Private Sub CreateTemplate(temp)
Set myOlApp = CreateObject("Outlook.Application")
Set mail = myOlApp.CreateItemFromTemplate(temp)
Set olAtt = mail.Attachments
With mail
'.Body = "" -- If I use this line, everything attaches
.Subject = Agency & " Recall File"
.To = "email"
.Attachments.Add xfullName
.Display '.Send
End With
End Sub
Here is a working example on how to attach or embed files to outlook.
Option Explicit
Dim titleName As String
Dim firstName As String
Dim lastName As String
Dim fullName As String
Dim clientEmail As String
Dim ccEmail As String
Dim bccEmail As String
Dim emailMessage As String
Sub GenerateInfo()
Dim WS As Worksheet
Dim lrow As Long
Dim cRow As Long
Set WS = ActiveSheet
With WS
lrow = .Range("E" & .Rows.Count).End(xlUp).Row
Application.ScreenUpdating = False
For cRow = 2 To lrow
If Not .Range("L" & cRow).value = "" Then
titleName = .Range("D" & cRow).value
firstName = .Range("E" & cRow).value
lastName = .Range("F" & cRow).value
fullName = firstName & " " & lastName
clientEmail = .Range("L" & cRow).value
Call SendEmail
.Range("Y" & cRow).value = "Yes"
.Range("Y" & cRow).Font.Color = vbGreen
Else
.Range("Y" & cRow).value = "No"
.Range("Y" & cRow).Font.Color = vbRed
End If
Next cRow
End With
Application.ScreenUpdating = True
MsgBox "Process completed!", vbInformation
End Sub
Sub SendEmail()
Dim outlookApp As Object
Dim outlookMail As Object
Dim sigString As String
Dim Signature As String
Dim insertPhoto As String
Dim photoSize As String
Set outlookApp = CreateObject("Outlook.Application")
Set outlookMail = outlookApp.CreateItem(0)
'Change only Mysig.htm to the name of your signature
sigString = Environ("appdata") & _
"\Microsoft\Signatures\Marius.htm"
If Dir(sigString) <> "" Then
Signature = GetBoiler(sigString)
Else
Signature = ""
End If
insertPhoto = "C:\Users\marius\Desktop\Presale.jpg" 'Picture path
photoSize = "<img src=""cid:Presale.jpg""height=400 width=400>" 'Change image name here
emailMessage = "<BODY style=font-size:11pt;font-family:Calibri>Dear " & titleName & " " & fullName & "," & _
"<p>I hope my email will find you very well." & _
"<p>Our <strong>sales preview</strong> starts on Thursday the 22nd until Sunday the 25th of November." & _
"<p>I look forward to welcoming you into the store to shop on preview.<p>" & _
"<p> It really is the perfect opportunity to get some fabulous pieces for the fast approaching festive season." & _
"<p>Please feel free to contact me and book an appointment." & _
"<p>I look forward to seeing you then." & _
"<p>" & photoSize & _
"<p>Kind Regards," & _
"<br>" & _
"<br><strong>Marius</strong>" & _
"<br>Assistant Store Manager" & _
"<p>"
With outlookMail
.To = clientEmail
.CC = ""
.BCC = ""
.Subject = "PRIVATE SALE"
.BodyFormat = 2
.Attachments.Add insertPhoto, 1, 0
.HTMLBody = emailMessage & Signature 'Including photo insert and signature
'.HTMLBody = emailMessage & Signature 'Only signature
.Importance = 2
.ReadReceiptRequested = True
.Display
.Send
End With
Set outlookApp = Nothing
Set outlookMail = Nothing
End Sub
Function GetBoiler(ByVal sFile As String) As String
Dim fso As Object
Dim ts As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
GetBoiler = ts.readall
ts.Close
End Function
Hi I am using below code to add chart and send email to multiple recipients. It works fine. In my sent item i can see a perfect email created and sent. But all the recipients are not able to see the charts. All they see is two red X
Sub Send_Email_Updated()
Dim olApp As Object
Dim NewMail As Object
Dim NewMail1 As Object
Dim ChartName As String
Dim ChartName1 As String
Dim SendingRng As Range
Dim htmlString As String
Dim OMail As Outlook.MailItem
Set wb = ActiveWorkbook
Set S1 = wb.Worksheets("Incident Tickets")
Set S2 = wb.Worksheets("Assets and Representatives")
Set S3 = wb.Worksheets("Email")
'Set SendingRng = Worksheets("Email").Table("A30:C43")
Set SendingRng = Worksheets("Email").Range("A30:C43")
Set olApp = CreateObject("Outlook.Application")
Set OMail = olApp.CreateItem(olMailItem)
' Group 1
If S3.Cells(7, 2) <> 0 Or S3.Cells(8, 2) <> 0 Or S3.Cells(9, 2) <> 0 Then
OMail.Display
'fill in the file path/name of the gif file app graph
ChartName = Environ$("Temp") & "\Chart 1.gif"
ActiveWorkbook.Worksheets("Email").ChartObjects("Chart 1").Chart.Export _
Filename:=ChartName, FilterName:="GIF"
'fill in the file path/name of the gif file trend graph
ChartName1 = Environ$("Temp") & "\Chart 31.gif"
ActiveWorkbook.Worksheets("Email").ChartObjects("Chart 31").Chart.Export _
Filename:=ChartName1, FilterName:="GIF"
Set NewMail = olApp.CreateItem(0)
With NewMail
.Subject = "Action Required on Incidents and Problem Candidates for GC060.1 - Group 1"
.To = "animesh.das#xyz.com"
.HTMLBody =
"<img src=" & "'" & ChartName1 & "'>" & "<br/>" & "<br/>" & "_
"<img src=" & "'" & ChartName & "'>" & "<br/>" & "<br/>" & _
.Send
End With
ChartName = vbNullString
ChartName1 = vbNullString
End If
End Sub