vba + Selection.Paste into outlook + control poition - vba

What I am trying to do is copy a chart from excel into an outlook email, but after numerous searching I am struggling.
i am having trouble positioning where the chart is pasted. I want it to paste after the last line "this is another line again " in the body of the email. It currently pastes at the start of the email before the line "test ... body"
Sub CopyAndPasteToMailBody3() ' this works but how do i control where it puts the chart?
Set mailApp = CreateObject("Outlook.Application")
Set mail = mailApp.CreateItem(olMailItem)
mail.Display
mail.To = "A#a.com"
mail.subject = "subject" & Now
mail.body = "test ... body" & vbNewLine & vbNewLine _
& "this is another line " & vbCrLf _
& "this is another line again "
Set wEditor = mailApp.ActiveInspector.wordEditor
ActiveChart.ChartArea.Copy ' chart needs to be active
wEditor.Application.Selection.Paste
' mail.send
End Sub
Note: using excel 10 on windows 7

I have found that
Set wEditor = mailapp.ActiveInspector.WordEditor
needs to be followed by
wEditor.Range(0, 0).Select
to avoid an error sometimes when you go to paste it.

You can modify the code put the Body on the Clipboard and Paste it:
Set mailApp = CreateObject("Outlook.Application")
Set mail = mailApp.CreateItem(olMailItem)
mail.Display
mail.To = "A#a.com"
mail.Subject = "subject" & Now
Dim Clip As MSForms.DataObject
Set Clip = New MSForms.DataObject
Clip.SetText ("test ... body" & vbNewLine & vbNewLine _
& "this is another line " & vbCrLf _
& "this is another line again " & vbNewLine & " ")
Clip.PutInClipboard
Set wEditor = mailApp.ActiveInspector.wordEditor
wEditor.Application.Selection.Paste
ActiveChart.ChartArea.Copy ' chart needs to be active
wEditor.Application.Selection.Paste
' mail.send
In this case you can assembly the mail as you want.
MSForms.DataObject need to have the Reference: Microsoft Form 2.0 Object Library (FM20.DLL)

You can try also with another code (in this case the image are temporary saved on disk):
Sub CopyAndPasteToMailBody4() ' this works but how do i control where it puts the chart?
Set mailApp = CreateObject("Outlook.Application")
Set mail = mailApp.CreateItem(0)
mail.Display
mail.To = "A#a.com"
mail.Subject = "subject" & Now
Dim Stri As String
Stri = "test ... body" & vbNewLine & vbNewLine _
& "this is another line " & vbCrLf _
& "this is another line again " & vbNewLine & " "
ActiveChart.Export "e:\0\C1.png"
Stri = Stri & "<img src='e:\0\C1.png'>"
mail.HTMLBody = Stri
' mail.send
End Sub
On my PC the first code ask me some permission, with the second code no...

Related

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 to pass email address and password for creating emails in GMail?

I need my Access Database to create emails that are sent at the press of a button.
This works for Outlook, and I adapted the code for Gmail.
I don't want to hardcode the email username and password. I want to pick it up from a combobox on the main form.
I get the error
Private Sub Email_Allocation_List_Click()
Dim newMail As CDO.Message
Dim mailConfiguration As CDO.Configuration
Dim fields As Variant
Dim msConfigURL As String
On Error GoTo errHandle
Set newMail = New CDO.Message
Set mailConfiguration = New CDO.Configuration
mailConfiguration.Load -1
Set fields = mailConfiguration.fields
With newMail
.Subject = "subject"
.From = [Forms]![Main form]![EmailAddress].Column(1)
.To = "email address"
.CC = "email address"
.BCC = ""
.TextBody = "Hello, " & vbNewLine & vbNewLine & _
"Please find attached todays list of lines to be allocated." & _
vbNewLine & vbNewLine & "Kind Regards." & vbNewLine & vbNewLine & "Carly"
.AddAttachment "file location"
End With
msConfigURL = "http://schemas.microsoft.com/cdo/configuration"
With fields
.Item(msConfigURL & "/smtpusessl") = True
.Item(msConfigURL & "/smtpauthenticate") = 1
.Item(msConfigURL & "/smtpserver") = "smtp.gmail.com"
.Item(msConfigURL & "/smtpserverport") = 465
.Item(msConfigURL & "/sendusing") = 2
.Item(msConfigURL & "/sendusername") = [Forms]![Main form]![EmailAddress].Column(1)
.Item(msConfigURL & "/sendpassword") = [Forms]![Main form]![EmailAddress].Column(2)
.Update
End With
newMail.Configuration = mailConfiguration
newMail.Send
MsgBox "E-Mail has been sent", vbInformation
exit_line:
'// Release object memory
Set newMail = Nothing
Set mailConfiguration = Nothing
Exit Sub
errHandle:
MsgBox "Error: " & Err.Description, vbInformation
GoTo exit_line
End Sub
I checked the comboboxes work with a text box.
After a lot of messing around, you are correct, the code is fine - and it was reading the contents of the combo box correctly - however GMail didn't accept the log in information if there was a capital letter on the email address!!! Now working beautifully.

How to insert an existing signature block into Outlook .htmlbody from Word VBA [duplicate]

This question already has answers here:
How to add default signature in Outlook
(15 answers)
Closed 6 years ago.
I have completed this code to populate the body of an Outlook email, however, I do not know how I can use my existing signature block already created in Outlook. When I create a new, reply or forward email, my signature is there, but when I create the email with this code it does not appear. What I'm trying to accomplish here is to have my signature (or any signature for that matter) appear into the email created by this code.
Private Sub emailbutton_Click()
'No-option email sending
Dim OL As Object
Dim EmailItem As Object
Dim Doc As Document
Application.ScreenUpdating = False
Set OL = CreateObject("Outlook.Application")
Set EmailItem = OL.CreateItem(olMailItem)
Set Doc = ActiveDocument
If VName.Value = "" Then
Doc.SaveAs ("Quotation_Blank 2016")
Else
Doc.SaveAs2 ("QFORM" & "_" & JNumber.Value & "_" & VName.Value)
End If
With EmailItem
.Subject = "QFORM" & "_" & JNumber.Value & "_" & VName.Value
'HTMLbody
msg = "<b><font face=""Times New Roman"" size=""3"" color=""blue"">INTEGRATED ASSEMBLY </font></b><br>" _
& " 1200 Woodruff Rd.<br>" _
& " Suite A12<br>" _
& " Greenville, SC 29607<br><br>" _
& "We have recently released subject project, which will contain assemblies to be outsourced. You have been selected to build these assemblies according to the attachment.<br><br>" _
& "As part of this process, please review the quotion form attached and inidcate your acceptance. If adjustments and-or corrections are required please feel free to contact us for quick resolution.<br><br>" _
& "<b><font face=""Times New Roman"" size=""3"" color=""Red"">NOTE: </font></b>" _
& "The information on attached quotation form is not a contract and only an estimate of predetermined costs per hourly rate for outsource assemblies. <br><br>" _
& "*******For your records you may wish to print out the completed quote form. <br><br>" _
& "Thank you, <br><br>" _
& "<b>HARTNESS INTERNATIONAL </b><br>" _
& "H1 Production Control" & vbNewLine & Signature
.HTMLBody = msg
If VName.Value = "INTEGRATED ASSEMBLY" Then
.To = "XXX.com;"
.CC = "XXX.com;" & "XXX.com;"
.Importance = olImportanceNormal 'Or olImportanceHigh Or olImportanceLow
.Attachments.Add Doc.FullName
.Display
ElseIf VName.Value = "LEWALLEN" Then
.To = "XXX.com;"
.CC = "XXX.com;" & "XXX.com;"
.Importance = olImportanceNormal 'Or olImportanceHigh Or olImportanceLow
.Attachments.Add Doc.FullName
.Display
End If
End With
Application.ScreenUpdating = True
Set Doc = Nothing
Set OL = Nothing
Set EmailItem = Nothing
End Sub
I think you need to call the .HTMLBody again after you insert msg.
So for example:
.HTMLBody = msg & .HTMLBody
Should get the signature. I'm not deep enough into programming to know why though.
Do you have Option Explicit set in your module?
I don't see where you've set Signature or declared it so it's probably empty and not giving you an error message.
I think you need to retrieve it first by pulling in the blank Body
Something like this should work
With EmailItem
.Display
signature = .body
.Subject = "QFORM" & "_" & JNumber.Value & "_" & VName.Value
' and so on ..
`
The code was successful with inputting a with statement to display the EmailItem - along with recalling .HTMLBody following the msg.. Please see full code below.
Private Sub emailbutton_Click()
'No-option email sending
Dim OL As Object
Dim EmailItem As Object
Dim Doc As Document
Application.ScreenUpdating = False
Set OL = CreateObject("Outlook.Application")
Set EmailItem = OL.CreateItem(olMailItem)
Set Doc = ActiveDocument
With EmailItem
.Display
End With
Signature = EmailItem.body
With EmailItem
.Subject = "QFORM" & "_" & JNumber.Value & "_" & VName.Value
'HTMLbody
msg = "<b><font face=""Times New Roman"" size=""4"" color=""blue"">INTEGRATED ASSEMBLY </font></b><br>" _
& " 1200 Woodruff Rd.<br>" _
& " Suite A12<br>" _
& " Greenville, SC 29607<br><br>" _
& "We have recently released subject project, which will contain assemblies to be outsourced. You have been selected to build these assemblies according to the attachment. <br><br>" _
& "As part of this process, please review the quotation form attached and indicate your acceptance. If adjustments and-or corrections are required, please feel free to contact us for quick resolution. <br><br>" _
& "<b><font face=""Times New Roman"" size=""4"" color=""Red"">NOTE: </font></b>" _
& "The information on attached quotation form is not a contract and only an estimate of predetermined costs per hourly rate for outsource assemblies. <br><br>" _
& "*******For your records you may wish to print out the completed quote form. <br><br>" _
& "Thank you, <br><br>" _
& "<b>HARTNESS INTERNATIONAL </b><br>" _
& "H1 Production Control <br>" _
& vbNewLine & Signature
.HTMLBody = msg & .HTMLBody
If VName.Value = "INTEGRATED ASSEMBLY" Then
.To = "ryan#integratedassembly.com;"
.CC = "jfournier#hartness.com;" & "jmarshone#hartness.com;"
.Importance = olImportanceNormal 'Or olImportanceHigh Or olImportanceLow
.Attachments.Add Doc.FullName
.Display
ElseIf VName.Value = "LEWALLEN" Then
.To = "jessica.andrews#patriot-automation.com;"
.CC = "jfournier#hartness.com;" & "jmarshone#hartness.com;"
.Importance = olImportanceNormal 'Or olImportanceHigh Or olImportanceLow
.Attachments.Add Doc.FullName
.Display
End If
End With
If VName.Value = "" Then
Doc.SaveAs ("Quotation_Blank 2016")
Else
Doc.SaveAs2 ("QFORM" & "_" & JNumber.Value & "_" & VName.Value)
End If
Application.ScreenUpdating = True
Set Doc = Nothing
Set OL = Nothing
Set EmailItem = Nothing
End Sub

Runtime error if contact in Outlook doesn't exist

When I complete a piece of work I email it to certain people. It depends on the work who gets it.
If any person in the list leaves, changes job or has an email change the code will bug out saying
Run Time error -2147467259(80004005), Outlook Does Not Recognise One Or More Names
If I manually copy the email addresses in the list and pop them into Outlook and send I'll get an email back saying the user doesn't exist or has been changed.
I have tried On Error Resume Next and On Error Goto. I have added MS Outlook 14.0 Object Libary, SharePoint Social Provider, Social Provider Extensibility and Outlook View control from the references.
The code bugs out on the .send
Sub EMailer()
Application.ScreenUpdating = False
strfilepath = "\\DFZ70069\Data\199711009\workgroup\Res Plan Team\Performance Management\Specialised Reporting\Debit & Credit Reporting\Masters\Sent Reports\"
strArea = "Recipients" '..........................................................................................
'Get list of recipients for email
For Each cell In Worksheets("EMails").Range(sRange)
If cell.Value = "" Then GoTo Continue
strmaillist = strmaillist & cell.Value + ";"
Continue:
Next
[B1].Value = strmaillist
If bMyEmail = True Then
strmaillist = strmaillist & MyEmailAddress
End If
'Display email list
Dim AckTime As Integer, InfoBox As Object
Set InfoBox = CreateObject("WScript.Shell")
AckTime = 1
Select Case InfoBox.Popup("Sending " & sReportName & " emails to " & vbNewLine & strArea, _
AckTime, "Message Box", 0)
Case 1, -1
End Select
'SEND EMAIL
'set up Body of email............
strbody = "Please find attached " & sReportName & " Report " & " _" & strDate & vbLf & vbLf & _
strComments & vbLf & _
strComments2 & vbLf & _
"" & vbLf & _
eMailName & vbLf & _
"MI & Performance Reporting Team" & vbLf & _
sline2 & vbLf & _
sline3 & vbLf & vbLf & _
sLine4
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = strmaillist
.CC = ""
.BCC = ""
.Subject = sReportName & " Report " & strDate
.HTMLBody = "Set to HTML" & vbLf & vbLf & ""
.Body = strbody
.Attachments.Add (strfilepath & sTemplateName)
.send ' bugs out here
End With
Set OutMail = Nothing
Set OutApp = Nothing
ThisWorkbook.Activate
Sheets("Sheet1").Select
Application.ScreenUpdating = True: Application.ScreenUpdating = False
Sheets("Sheet1").Select
Range(sRange2).Value = sConclusion '.
Application.ScreenUpdating = True: Application.ScreenUpdating = False
End Sub
You can try to check the validity of the recipient before sending, by using the .Resolve method of the Recipient object. Only valid recipients can be kept in the Recipient list of the mail item.
You might try this:
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.Subject = sReportName & " Report " & strDate
.HTMLBody = "Set to HTML" & vbLf & vbLf & ""
.Body = strbody
.Attachments.Add (strfilepath & sTemplateName)
For Each cell In Worksheets("EMails").Range(sRange)
If cell.Value <> "" Then
set r = .Recipients.Add(cell.value)
If Not r.Resolve then r.Delete '<~~ Removes invalid recipients
End If
Next
.send
End With

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