How to include sender's details in email body? - vba

I have a macro in MS Word which:
Creates an Outlook email on the click of a button
Attaches the Word document to the Outlook email
I want to include the sender's details (name, email address, etc.) in the body of the email.
Dim Outlook_Object As Object
Dim Email_Object As Object
Dim This_document As Document
Application.ScreenUpdating = False
Set Outlook_Object = CreateObject("Outlook.Application")
Set Email_Object = Outlook_Object.CreateItem(olMailItem)
Set This_document = ActiveDocument
This_document.Save
With Email_Object
.Subject = "REPORT REQUEST FORM"
.Body = "This is a test email."
.To = "john.smith#gmail.com"
.Importance = olImportanceNormal
.Attachments.Add This_document.FullName
.Display
End With
Set This_document = Nothing
Set Email_Object = Nothing
Set Outlook_Object = Nothing
Application.ScreenUpdating = True

You can use the NameSpace.CurrentUser property which returns the display name of the currently logged-on user as a Recipient object. The Recipient.AddressEntry property returns the AddressEntry object corresponding to the resolved recipient. Then you can get the Name and Address properties like shown below:
Dim ns as Outlook.NameSpace
Set ns = OutlookApplication.GetNamespace("MAPI")
' to get the email address of the sender
ns.CurrentUser.AddressEntry.Address
' to get the name
ns.CurrentUser.AddressEntry.Name
To include this information to the message body you can use the Body or HTMLBody properties.

Ended up using WScript.Network
Function GetUserFullName() As String
Dim WSHnet, UserName, UserDomain, objUser
Set WSHnet = CreateObject("WScript.Network")
UserName = WSHnet.UserName
UserDomain = WSHnet.UserDomain
Set objUser = GetObject("WinNT://" & UserDomain & "/" & UserName & ",user")
GetUserFullName = objUser.FullName
End Function
Also, instead of using .body, I used .HTMLbody for the email message body [where I invoked GetUserFullName()]
.HTMLbody = "Request submitted by:" & "<br>" & GetUserFullName()

Related

Sending Email using Access VBA

I am attempting to send an email out of Access. The email is not automatically sent. I have to hit send on the email pop up.
Is there something missing in my code that is preventing the email from sending.
Dim strTo As String
Dim strMessage As String
Dim strSubject As String
strTo = "Hazat.Bangurah#umm.edu"
strSubject = "New Lab Charge Codes"
strMessage = "Attached are the New Lab Charge Codes"
DoCmd.SendObject acSendQuery, "std qry_Master to HPM Lab Standard Compare", acFormatXLSX, strTo, , , strSubject, strMessage
DoCmd.SendObject will show a warning pop-up from outlook even if you use EditMessage := False. So you can apply workaround to avoid it. First save the query to you disk and add that file as attachment. This work around can be done programmatically. Try below codes to send mail without any warning pop-up but you must set Programmatic Access to Never warn me about suspicious activity. See this post from Microsoft Answer.
Private Sub CmdSendMail_Click()
Dim strTo As String
Dim strMessage As String
Dim strSubject As String
Dim attch As String
strTo = "Hazat.Bangurah#umm.edu"
attch = "D:\MyFile.xlsx"
strSubject = "New Lab Charge Codes"
strMessage = "Attached are the New Lab Charge Codes"
' Save file to disk.
DoCmd.OutputTo acOutputQuery, "Query1", acFormatXLSX, attch, False, , , acExportQualityPrint
Call SendEmailWithOutlook(strTo, strSubject, strMessage, attch)
End Sub
'======= Function to send email =======
Public Function SendEmailWithOutlook( _
MessageTo As String, _
Subject As String, _
MessageBody As String, strAttachment As String)
' Define app variable and get Outlook using the "New" keyword
Dim OutApp As Object
Dim OutMail As Object ' An Outlook Mail item
' Create a new email object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(olMailItem)
' Add the To/Subject/Body to the message and display the message
With OutMail
.To = MessageTo
.Attachments.Add strAttachment
.Subject = Subject
.Body = MessageBody
.Send ' Send the message immediately
End With
' Release all object variables
Set OutApp = Nothing
Set OutMail = Nothing
End Function
To set Programmatic Access you must open outlook as Administrator. Then follow the screenshot below.

RunTime Error '2147467259 (80004005)' Sending Email from VBA Code

I am trying to send an email of a file from my VB code. I have a linked table that has email addresses in it, but I am getting the run time error '-2147467259 (80004005)' We Need to Know Who to Send this to. Make sure you enter atleast one name'
Public Function sendmail(mailSub As String, mailTo As String, _
Optional msgBody As String, Optional mailCC As String, _
Optional mailBCC As String, Optional mailFrom As String, _
Optional pathToAttach As String) As Boolean
Dim oApp As Object, oMail As Object, oAttach As Object
sendmail = False
Set oApp = CreateObject("Outlook.Application")
Set oMail = oApp.CreateItem(0) 'olMailItem=0
Set oAttach = oMail.Attachments
With oMail
.BodyFormat = 2 'olFormatHTML=2, olFormatPlain=1, olFormatRichText=3
.SentOnBehalfOfName = mailFrom
.To = mailTo
.CC = mailCC
.BCC = mailBCC
.Subject = mailSub
.htmlBody = msgBody & "<BR>" & .htmlBody
.Recipients.ResolveAll
End With
If pathToAttach & "" <> "" Then oAttach.Add pathToAttach, olByValue, 1
oMail.Send '<<This is where I am getting the error
oMail.Display
sendmail = True
Exit Function
End Function
Public Function getEmails(Address_type As String) As String
Dim rst As Recordset, tbl_Email As String
tbl_Email = "tbl_Email" ' Change this as needed
On Error GoTo no_rec
Set rst = CurrentDb.OpenRecordset("SELECT * FROM " & tbl_Email & " WHERE " & _
Address_type & "=TRUE")
rst.MoveLast
rst.MoveFirst
While Not rst.EOF
getEmails = getEmails & rst![Email] & ";"
rst.MoveNext
Wend
no_rec:
If Not rst Is Nothing Then rst.Close
Set rst = Nothing
End Function
Firstly, there is no reason to call both Send and Display: if you are displaying the message, you should not call Send - the user will click the Send button.
If you replace the call to Send with Save, do you see the recipients in the message shown to the user?

How to assign a recipient to .To?

I convert a worksheet into a PDF and am trying to have that PDF emailed to me and copied to another person. All of this will be assigned to an action button/trigger.
Option Explicit
Sub SendExcelFileAsPDF()
Dim OutlookApp As Outlook.Application
Dim emItem As Object
Dim Receipt As String, Subject As String
Dim Message As String, Fname As String
Dim Recipient As Outlook.Recipient
Recipient = "xxxxx.xxxxx#fedex.com"
Subject = "Weekly Critical Items" & " " & Range("L1")
Message = Range("D2") & Range("J2") & "Weekly Critical Items submitted" &
Range("L1") & " " & "in PDF Format"
Message = Message & vbNewLine & vbNewLine & "Offload Ops"
Fname = Application.DefaultFilePath & "/" & ActiveWorkbook.Name & ".pdf"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=Fname
Set OutlookApp = New Outlook.Application
Set emItem = OutlookApp.CreateItem(olMailItem)
With emItem
.To = Recipient = "xxxxx.xxxxx#fedex.com"
.Subject = Subject
.Body = Message
.Attachements.Add Fname
.Send
End With
Set OutlookApp = Nothing
End Sub
The recipient line is where I am having issues. When I run the debugger, it's giving
Run-Time error '91: Object variable or with block variable not set
I would dim recipient as string and update the .to assignment:
Change
Dim Recipient As Outlook.Recipient
.To = Recipient = "dennis.aikens#fedex.com"
to
Dim Recipient As string
.To = Recipient
This line
.To = Recipient = "dennis.aikens#fedex.com"
Should be just
.To = Recipient

Differences between when we manually forward and email versus when we use a macro to forward an email in outlook

I haven't noticed manually forwarding an email using outlook (2016) forward button is giving me different result from when I use a macro to forward it. Here is my macro:
Sub W()
Dim helpdeskaddress As String
Dim objMail As Outlook.MailItem
Dim strbody As String
Dim oldmsg As String
Dim senderaddress As String
Dim addresstype As Integer
' Set this variable as your helpdesk e-mail address
helpdeskaddress = "blah#blah.com"
Set objItem = GetCurrentItem()
Set objMail = objItem.Forward
' Sender E=mail Address
senderaddress = objItem.SenderEmailAddress
'Searches for # in the email address to determine if it is an exchange user
addresstype = InStr(senderaddress, "#")
' If the address is an Exchange DN use the Senders Name
If addresstype = 0 Then
senderaddress = objItem.SenderName
End If
'adds the senders e-mail address as the created by object for the ticket and appends the message body
strbody = "#created by " & senderaddress & vbNewLine & vbNewLine & objItem.Body
objMail.To = "receiver#blah.com"
objMail.Subject = objItem.Subject
objMail.Body = strbody
' remove the comment from below to display the message before sending
'objMail.Display
'Automatically Send the ticket
objMail.Send
MsgBox ("The email has been sent for verification. You may receive a report in a few moments.")
Set objItem = Nothing
Set objMail = Nothing
End Sub
and a function to obtain the current email object item:
Function GetCurrentItem() As Object
Dim objApp As Outlook.Application
Set objApp = Application
On Error Resume Next
Select Case TypeName(objApp.ActiveWindow)
Case "Explorer"
Set GetCurrentItem = _
objApp.ActiveExplorer.Selection.Item(1)
Case "Inspector"
Set GetCurrentItem = _
objApp.ActiveInspector.CurrentItem
Case Else
End Select
End Function
When I forward an email, I can see all images (linked to another website on the Internet) I am forwarding but when I use the following macro, all I see is the text inside the email. Is there anyway I can make the following macro to do the similar job as manually forwarding does?
To forward the original content, use HTMLBody instead of Body:
strbody = "HTML-encoded content"
objMail.HTMLBody = strbody & objMail.HTMLBody
Sample HTML Format specific text in Outlook

How to send outlook email automatically using Excel UserForm?

Thanks for any help with this. I have a userform I've made that gathers criteria from the user and then when they hit submit it opens Outlook and emails that data to me.
I'm having 2 issues. The first is that when I try to use SENDKEYS method I'm running into the spell check feature stopping the email from actually sending without the user needing to go through it. Is there a way to bypass spell check and send the email?
Secondly, I couldn't find a way to actual send an email automatically without using SENDKEYS but I'm sure there is a better way out there to send the email rather than manipulating the window with TAB key strokes.
Private Sub SubmitButton_Click()
Dim OutApp As Object
Dim OutMail As Object
Dim strBody, RequestName, ProductName, Month, TestName, Summary As String
If Me.RequesterNameTxt.Value <> "" And Me.ProductCombo.Value <> "" And Me.MonthCombo.Value <> "" And Me.TestNameCombo <> "" Then
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
RequestName = Me.RequesterNameTxt.Value
ProductName = Me.ProductCombo.Value
Month = Me.MonthCombo.Value
TestName = Me.TestNameCombo.Value
Summary = Me.SummaryTxt.Value
strBody = "<HTML><BODY>"
strBody = "Requester Name: " & RequestName & "<BR>" & "Product Name: " & ProductName & "<BR>" & "Month: " & Month & "<BR>" & _
"Test Name: " & TestName & "<BR>" & "<BR>" & "Summary of Request: " & Summary
strBody = strBody & "</BODY></HTML>"
On Error Resume Next
With OutMail
.To = "example#gmail.com;"
.CC = ""
.bcc = ""
.Subject = "QA Service Request"
.htmlBody = strBody
.send 'This fixed my issue. I had this as .Display which opens email up and doesn't send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
Application.SendKeys ("%s")
Else: MsgBox "Please fill out all form data before submitting request. Thank you!"
End If
End Sub
You need to use the Send method of Outlook items instead. The Send method sends an item using the default account specified for the session. In a session where multiple Microsoft Exchange accounts are defined in the profile, the first Exchange account added to the profile is the primary Exchange account, and is also the default account for the session. To specify a different account to send an item, set the SendUsingAccount property to the desired Account object and then call the Send method.
Also I'd recommend using the Recipients property for adding recipients instead. The property returns a Recipients collection that represents all the recipients for the Outlook item.