VBA Outlook does not generate new mailitem from this code - excel

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:

Related

Send mails, using oft template, with addresses in Excel

I used the below coding earlier for some other type of mail but this time is not sending the mails.
Also not picking the email IDs and data given in Excel.
I have to send mails to different people with CC to their respective managers. I updated their Email IDs in Excel but the details updated in Excel are not taking and a draft mail is created without anything in To and CC.
Sub Send_Recertification_From_Excel()
Dim oXlWkBk As Excel.Workbook ' Excel Work Book Object
Dim oOLApp As Outlook.Application
Dim oOLMail As MailItem
Dim lRow As Long
Dim olMailItem
Dim sMailID As String
Dim sSalutation As String
Dim sName As String
Dim sDetails As String
Dim sSubject As String
Dim mailsSentString As String
Dim templateName As String
templateName = "C:\Users\m540797\Desktop\Recertification\Recertifications"
On Error GoTo Err_Trap
Set oXlWkBk = ActiveWorkbook
Set oOLApp = GetObject(, "Outlook.Application")
If oOLApp Is Nothing Then
MsgBox "Please Open Outlook.."
Exit Sub
End If
Dim i As Integer
For i = 6 To 50
If Len(Trim(Sheet1.Cells(i, 1))) > 1 Then
Set oOLMail = oOLApp.CreateItemFromTemplate(templateName)
sMailID = Sheet1.Cells(i, 4)
sSubject = "Recertification"
With oOLMail
.BodyFormat = olFormatHTML
.HTMLBody = Replace(.HTMLBody, "<NAME>", Sheet1.Cells(i, 3))
.SentOnBehalfOfName = "my mail ID given here"
.To = sMailID
.Subject = sSubject
.CC = Sheet1.Cells(i, 6)
.Send
End With
oOLMail.Send
Else
Exit For
End If
Next i
MsgBox "Mails successfully sent to :" + vbCrLf + mailsSentString + vbCrLf + "with using the template :" + templateName
Destroy_Objects:
If Not oOLApp Is Nothing Then Set oOLApp = Nothing
Err_Trap:
If Err <> 0 Then
MsgBox Err.Description, vbInformation, "VBADUD AutoMail"
Err.Clear
GoTo Destroy_Objects
End If
End Sub
Not giving any error just says mail sent successfully but it is lying in draft.

Add email attachment(s) from excel to outlook based on condition

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

Embed image not showing on email

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

Problem Attaching Excel File to Email with VBA

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

Improve process of taking email address from spreadsheet

I have a spreadsheet that I have set up to automatically pdf and email nightly based on email addresses I have listed out on a hidden worksheet. I currently have to dim seperate variable for each address and then specify which cell each variable equals. This works but I feel like there must be a better way to do this. Specifically, I would like to not have to add or delete dim'ed variables if I delete or add additional addresses to the list. Here is the code I am using:
Sub PDF_Email()
Dim OutLookApp As Object
Dim OutLookMailItem As Object
Dim myAttachment As Object
Dim MDir As String
Dim MName As String
Dim Address1 As String
Dim Address2 As String
Dim Address3 As String
Dim Address4 As String
Dim Address5 As String
Dim Address6 As String
Dim Address7 As String
Dim Address8 As String
Dim Address9 As String
Dim Address10 As String
Dim Address11 As String
Set OutLookApp = CreateObject("Outlook.application")
Set OutLookMailItem = OutLookApp.CreateItem(0)
Set myAttachment = OutLookMailItem.Attachments
Address1 = Worksheets("EmailList").Cells(1, 1).Value
Address2 = Worksheets("EmailList").Cells(2, 1).Value
'Prevent Macro from running if different user
Const AllowedName As String = "nbelair"
If Environ("username") <> AllowedName Then
Exit Sub
End If
MName = ActiveSheet.Name & " " & Format(Now() - 1, "dddd, mmmm, d, yyyy")
MDir = ActiveWorkbook.Path
ChDir "Y:\SMHC Management Team\Daily Labor Management\Dashboard\Archived
Dashboards" 'Update to
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"Y:\SMHC Management Team\Daily Labor Management\Dashboard\Archived
Dashboards\" & MName & ".pdf", OpenAfterPublish:=True 'Update
With OutLookMailItem
.To = Address1 & ";" & Address2
.Subject = "SMHC Daily Labor Management Dashboard - " & Format(Now() - 1,
"dddd, mmmm, d, yyyy")
.Body = "Attached please find the SMHC Daily Labor Management Dashboard for
" _
& Format(Now() - 1, "dddd, mmmm, d, yyyy") & ". You are receiving this
email because you are currently " _
& "on the distribution list for this report. If you have any questions
" _
& "or concerns regarding this email or report please let me know by
responding to this email or contacting me at 207 467 6983."
myAttachment.Add "Y:\SMHC Management Team\Daily Labor
Management\Dashboard\Archived Dashboards\" & MName & ".pdf"
.Display
.Send
End With
'Clear Outlook Variables
Set OutLookMailItem = Nothing
Set OutLookApp = Nothing
'Quit
ThisWorkbook.Saved = True
Application.Quit
End Sub
Being new to coding, I would greatly appreciate any thoughts or suggestions someone might have. I am quickly falling in love with coding and welcome the chance to learn something new!
Thank You
The first loop builds the string of To:
The second loop builds the string of CC:
Email addresses span column F for To and column G for CC
Dim i As Integer
Dim EmailTo As String
Dim EmailCC As String
For i = 2 To 30
EmailTo = EmailTo & ThisWorkbook.Sheets("Email").Range("F" & i) & ";"
Next i
For i = 2 To 30
EmailCC = EmailCC & ThisWorkbook.Sheets("Email").Range("G" & i) & ";"
Next i
ThisWorkbook.Sheets("Dash").Range("C2:Q63").Select
ThisWorkbook.EnvelopeVisible = True
With ThisWorkbook.Sheets("Dash").MailEnvelope
.Introduction = ""
.Item.To = EmailTo
.Item.CC = EmailCC
.Item.Subject = "Subject " & Date
.Item.Display
End With

Resources