How to bring up message if email closed without sending? - excel

I know this is very basic, but having a total mind blank right now.
I have my basic code to send an email in outlook, but I need to know the line to bring up an error or message if the person closes the email without sending.
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
'Sends email
With OutMail
.to = " someone#nowhere.com"
.Subject = " Rich Request"
.HTMLBody = "Please find attached new request" .Attachments.AddApplication.ActiveWorkbook.FullName
.Display
End With
Set OutApp = Nothing

Related

Modify HTMLBody of Outlook Email, based on Template, from Excel

I am trying to modify the HTML body of an Outlook email, based on a template, from Excel VBA.
My code is:
Sub Email_Button()
Dim OutApp As Outlook.Application
Dim OutMail As Outlook.MailItem
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItemFromTemplate("S:\some\path\to\file\Email.oft")
With OutMail
.Importance = olImportanceHigh
.Subject = "Subject " & Date
.Attachments.Add Application.ActiveWorkbook.FullName
.HTMLBody = WorksheetFunction.Substitute(OutMail.HTMLBody, "%target%", "replacement")
.Display
End With
' *** TIDY UP ***
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
The question is very similar to this.
I get
Run Time Error 287. Application-defined or object-defined error
on the .HTMLBody modification line.
If I remove this line the email is displayed for the user to check before hitting send.
I have referenced the Microsoft Outlook 15 Object Library.
I added:
With OutMail
.bodyFormat = olFormatHTML
But got the same error on the Substitute line so I changed the substitute to:
.HTMLBody = "<HTML><BODY>Some HTML text here</BODY></HTML>"
And the body of the email was updated.
So the error is only present when trying to use substitute or its to do with the oft.
It looks like from the debugger that there is no HTML body:
I have confirmed that body type is set to HTML both programmatically:
and by opening the oft message and checking:
The cause of the issue can be related to the Substitute method, so I'd suggest running the following code to make sure everything works correctly:
Sub CreateHTMLMail()
Dim OutApp As Outlook.Application
Set OutApp = CreateObject("Outlook.Application")
'Creates a new email item and modifies its properties.
Dim objMail As Outlook.MailItem
'Create email item
Set objMail = OutApp.CreateItemFromTemplate("S:\some\path\to\file\Email.oft")
With objMail
'Set body format to HTML
.BodyFormat = olFormatHTML
.HTMLBody = "<HTML><BODY>Enter the message text here. </BODY></HTML>"
.Display
End With
End Sub
Another aspect is Outlook security prompts. Read more about that in the "A program is trying to send an e-mail message on your behalf" warning in Outlook article.
The most probable cause is Outlook Security.
For security purposes, the HTMLBody, HTMLEditor, Body and WordEditor properties all are subject to address-information security prompts because the body of a message often contains the sender's or other people's e-mail addresses.
You can find the security configurations in HKCU\Software\Policies\Microsoft\office\16.0\outlook\security\
(change 16.0 to your office version)
There are two values that you can check, promptoomaddressbookaccess and promptoomaddressinformationaccess
Change them to 2 (or ask your system administrator), restart Outlook and try again.
More info https://support.microsoft.com/en-za/help/926512/information-for-administrators-about-e-mail-security-settings-in-outlo

Sending an Email through a VBA macro (Excel)

I've spent the last couple days trying to figure this out, I've managed to stop all the errors, however the email doesn't show up in my inbox. I've tried to change everything up and still it doesn't show up.
The main purpose is to send an entire workbook to an email with a button (I've binded the button to the macro)
Anyways, here's the code I have already
Sub Send_mail()
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "example#email.com"
.From = "example#email.com"
.CC = ""
.BCC = ""
.Subject = "Assunto"
.Body = "Corpo"
.Attachments.Add ActiveWorkbook.FullName
.Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
(ps I did change the email to post this, it's not what I have in the code)
Please remove .From = "example#email.com"
Mail will go with attachment from outlook default mail address.
In Microsoft Documentation From is not listed while To, cc, BCC etc are included . So syntax wise it is wrong. It works for me after removing .From
You can see from list below
Methods
Properties
Actions
AlternateRecipientAllowed
Application
Attachments
AutoForwarded
AutoResolvedWinner
BCC
BillingInformation
Body
BodyFormat
Categories
CC
Class
Companies
Conflicts
ConversationID
ConversationIndex
ConversationTopic
CreationTime
DeferredDeliveryTime
DeleteAfterSubmit
DownloadState
EntryID
ExpiryTime
FlagRequest
FormDescription
GetInspector
HTMLBody
Importance
InternetCodepage
IsConflict
IsMarkedAsTask
ItemProperties
LastModificationTime
MarkForDownload
MessageClass
Mileage
NoAging
OriginatorDeliveryReportRequested
OutlookInternalVersion
OutlookVersion
Parent
Permission
PermissionService
PermissionTemplateGuid
PropertyAccessor
ReadReceiptRequested
ReceivedByEntryID
ReceivedByName
ReceivedOnBehalfOfEntryID
ReceivedOnBehalfOfName
ReceivedTime
RecipientReassignmentProhibited
Recipients
ReminderOverrideDefault
ReminderPlaySound
ReminderSet
ReminderSoundFile
ReminderTime
RemoteStatus
ReplyRecipientNames
ReplyRecipients
RetentionExpirationDate
RetentionPolicyName
RTFBody
Saved
SaveSentMessageFolder
Sender
SenderEmailAddress
SenderEmailType
SenderName
SendUsingAccount
Sensitivity
Sent
SentOn
SentOnBehalfOfName
Session
Size
Subject
Submitted
TaskCompletedDate
TaskDueDate
TaskStartDate
TaskSubject
To
ToDoTaskOrdinal
UnRead
UserProperties
VotingOptions
VotingResponse

Excel VBA save email after sent, only show preview email not sent email

I want to save the email in my local folder, and I saw this link
https://www.mrexcel.com/forum/excel-questions/361751-vba-saving-email-only-after-send-pushed.html
which basically use the class module to save the email after sending it out.
However the problem is, the email saved is the preview email (email that is being displayed before you send the email) instead of sent email (email in which you cannot edit anything anymore)
Dim cls_OL As New clsOutlook
Public objMail_SentMsg As Object
Public Emailpath As String
Sub SendEmail()
Dim OutMail As Object
Set cls_OL.obj_OL = CreateObject("Outlook.Application")
cls_OL.obj_OL.Session.Logon
Set OutMail = cls_OL.obj_OL.CreateItem(0)
Set objMail_SentMsg = OutMail
Emailpath = "V:\test\emailname.msg"
With OutMail
On Error Resume Next
'Assume this all strings variables are fine
.HTMLBody = strmsgContent1 & strmsgContent2
.to = ToEmail
.CC = CC
.BCC = BCC
.Subject = Subject
.Display
End With
Set OutMail = Nothing
End Sub
Option Explicit
Public WithEvents obj_OL As Outlook.Application
Private Sub obj_OL_ItemSend(ByVal Item As Object, Cancel As Boolean)
objMail_SentMsg.SaveAs Emailpath
Set obj_OL = Nothing
End Sub
It saved the email succesfully but as mentioned, only saved the preview/display email not the sent email.
Thank you so much for your help.
Instead of ItemSend monitor the SentItems folder with ItemAdd.
Do not save objMail_SentMsg, save the item identified by ItemAdd as being added to the folder.
If necessary to differentiate mail not to be saved, set up some unique characteristic in the mail when it is created.

Send Emails via Excel VBA one at a time

I am using MS Excel and Outlook 2013. I am trying to automate an Excel spreadsheet that sends 5 emails to a specified address using Outlook.
The trick is I want each message to display one at a time and only move on to the next message when the user either hits Send or closes the message. Here is what I have so far:
Sub Send_Emails()
Dim OutApp As Object: Set OutApp = CreateObject("Outlook.Application")
Dim OutMail As Object: Set OutMail = OutApp.CreateItem(0)
'Send Email
With OutMail
.to = "john.doe#mycompany.com"
.Subject = "This is the Subject"
.Body = "This is message"
.Display
End With
On Error Resume Next:
OutMail = Nothing
OutApp = Nothing
End Sub
Sub Send_Five_Emails()
For i = 1 To 5 'Send email 5 times
Call Send_Emails
Next i
End Sub
The problem with this code is that it displays all 5 message windows at once. Is there a way to make the Close event of one message window trigger the Displaying of the next one, so as to make them appear one at a time?
I appreciate the help.
Use .Display (True)
The expression.Display(Modal) argument is used with all objects except for the Explorer and MAPIFolder objects, True to make the window modal. The default value is False.
See Display Method on MSDN

Send a second E-Mail automatically once the first E-Mail is sent (Excel-VBA-Code)

I have the following VBA Code to send an E-Mail:
Sub First_Email()
If ExitAll = False Then
Dim OApp As Object, OMail As Object, signature As String
Set OApp = CreateObject("Outlook.Application")
Set OMail = OApp.CreateItem(0)
With OMail
.Display
End With
signature = OMail.HTMLbody
With OMail
.To = "test#test.de"
.Subject = "First E-Mail"
.HTMLbody = "<p> Once I click on the send button for this E-Mail I want that the E-Mail in the code below is sent as well.</p>"
End With
Set OMail = Nothing
Set OApp = Nothing
Else
End If
End Sub
This code opens Outlook with the E-Mail described above. Since the user should still have the chance to modify the E-Mail before it is sent the code does not automatically send the E-Mail.
Once the user clicks the Send Button the E-Mail is sent. Now, I want to achieve that the E-Mail below is automatically send as well once the user clicks the Send Button for the first E-Mail:
Sub Second_Email()
If ExitAll = False Then
Dim OApp As Object, OMail As Object, signature As String
Set OApp = CreateObject("Outlook.Application")
Set OMail = OApp.CreateItem(0)
With OMail
.Display
End With
signature = OMail.HTMLbody
With OMail
.To = "test#test.de"
.Subject = "Second E-Mail"
.HTMLbody = "<p> Once I click on the send button for the first E-Mail I want that this E-Mail is sent as well.</p>"
.send
End With
Set OMail = Nothing
Set OApp = Nothing
Else
End If
End Sub
In contrast to the first E-Mail the user does not have the chance to moidfy the second E-Mail before it is sent. It should immediately be sent once the user clicks the Send Button of the first E-Mail.
Do you know how I can achieve to send a second E-Mail automatically once the user clicks the Send Button in the first E-Mail?
You could use ItemSend in Outlook. In the ThisOutlookSession module.
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
If Item.To = "test#test.de" Then
If Item.Subject = "First E-Mail" Then
Set OMail = CreateItem(0)
With OMail
.To = "test#test.de"
.Subject = "Second E-Mail"
.HTMLbody = "<p> Once I click on the send button for the first E-Mail I want that this E-Mail is sent as well.</p>"
.send
End With
End If
end if
End Sub
Note: This will run on all mail not just the mail initiated by First_Email in Excel.

Resources