Getting Email Addresses for Recipients (Outlook) - email

I have a code that I was able to string together that logs my sent emails into an excel sheet so i can use that data for other analysis.
In it, I have it resolving the name into an email as outlook shortens it ("Jimenez, Ramon" = email#address.com) as outlook configured this and it works when i send an email to anyone in my company as they are in my address book.
Now, when I email anyone outside it defaults to lastName, firstName so it is not converting this and logging it.
I thought the code I have in here already does this, but I guess not. I have already come this far and I am NOT a software guru at all. Does anyone have insight on how I can also include this as well?? Please see code below:
Private WithEvents Items As Outlook.Items
Const strFile As String = "C:\Users\a0227084\Videos\work\test.xlsx"
Private Sub Application_Startup()
Dim OLApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set OLApp = Outlook.Application
Set objNS = OLApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderSentMail).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
FullName = Split(Msg.To, ";")
For i = 0 To UBound(FullName)
If i = 0 Then
STRNAME = ResolveDisplayNameToSMTP(FullName(i))
Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
ElseIf ResolveDisplayNameToSMTP(FullName(i)) <> "" Then
STRNAME = ResolveDisplayNameToSMTP(FullName(i))
Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
End If
Next i
'Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
Sub tes2t()
End Sub
Function getRecepientEmailAddress(eml As Variant)
Set out = CreateObject("System.Collections.Arraylist") ' a JavaScript-y array
For Each emlAddr In eml.Recipients
If Left(emlAddr.Address, 1) = "/" Then
' it's an Exchange email address... resolve it to an SMTP email address
out.Add ResolveDisplayNameToSMTP(emlAddr)
Else
out.Add emlAddr.Address
End If
Next
getRecepientEmailAddres = Join(out.ToArray(), ";")
End Function
Function ResolveDisplayNameToSMTP(sFromName) As String
' takes a Display Name (i.e. "James Smith") and turns it into an email address (james.smith#myco.com)
' necessary because the Outlook address is a long, convoluted string when the email is going to someone in the organization.
' source: https://stackoverflow.com/questions/31161726/creating-a-check-names-button-in-excel
Dim OLApp As Object 'Outlook.Application
Dim oRecip As Object 'Outlook.Recipient
Dim oEU As Object 'Outlook.ExchangeUser
Dim oEDL As Object 'Outlook.ExchangeDistributionList
Set OLApp = CreateObject("Outlook.Application")
Set oRecip = OLApp.Session.CreateRecipient(sFromName)
oRecip.Resolve
If oRecip.Resolved Then
Select Case oRecip.AddressEntry.AddressEntryUserType
Case 0, 5 'olExchangeUserAddressEntry & olExchangeRemoteUserAddressEntry
Set oEU = oRecip.AddressEntry.GetExchangeUser
If Not (oEU Is Nothing) Then
ResolveDisplayNameToSMTP = oEU.PrimarySmtpAddress
End If
Case 10, 30 'olOutlookContactAddressEntry & 'olSmtpAddressEntry
Dim PR_SMTP_ADDRESS As String
PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
ResolveDisplayNameToSMTP = oRecip.AddressEntry.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS)
End Select
End If
End Function
Sub Write_to_excel(str1 As String, str2 As String, str3 As String)
Dim xlApp As Object
Dim sourceWB As Workbook
Dim sourceWH As Worksheet
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.EnableEvents = False
End With
Set sourceWB = Workbooks.Open(strFile, False, False)
Set sourceWH = sourceWB.Worksheets("Sheet1")
sourceWB.Activate
With sourceWH
lastrow = .Cells(.rows.Count, "A").End(xlUp).Row
End With
sourceWH.Cells(lastrow + 1, 1) = str1
sourceWH.Cells(lastrow + 1, 2) = str2
sourceWH.Cells(lastrow + 1, 3) = str3
sourceWB.Save
sourceWB.Close
End Sub
Error message and corrected code
Regards,
Ramon

First of all, there is no need to create a new Application instance in the ResolveDisplayNameToSMTP method:
Set OLApp = CreateObject("Outlook.Application")
Instead, you can use the Application property available in the Outlook VBA editor out of the box.
Second, you need to use the following code to get the SMTP address from the AddressEntry object:
Dim PR_SMTP_ADDRESS As String
Set PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
ResolveDisplayNameToSMTP = oRecip.AddressEntry.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS)
Instead of the following line:
ResolveDisplayNameToSMTP = oRecip.AddressEntry.Address
Read more about that in the How to get the SMTP Address of the Sender of a Mail Item using Outlook Object Model? article.

Related

Attaching access form and subform data in mail body

Thanks in advance :), I am trying to attach the data of subform also in mail body.
Current Status: I am able to attach Main forms data and generate mail but unable to attach subform's data as it only includes the first row, Tryied doing it through Subform and query both but no success. I will prefer to do it by subform itself. Subform's Name is : "subUpdateOrder". VB Code:
Private Sub InformCustomer_Click()
On Error GoTo Err_InformCustomer_Click
Dim CustName As String ' Customer Name
Dim varTo As Variant '-- Address for SendObject
Dim stText As String '-- E-mail text
Dim DelDate As Variant '-- Rec date for e-mail text
Dim stSubject As String '-- Subject line of e-mail
Dim stOrderID As String '-- The Order ID from form
Dim detailQry As String
'Dim stHelpDesk As String '-- Person who assigned ticket
'Dim strSQL As String '-- Create SQL update statement
'Dim errLoop As Error
CstName = Me![CustName]
varTo = Me![CustEmail]
stSubject = ":: Update - Oder Status ::"
stOrderID = Me.[OdrID]
DelDate = Me.[OdrDeliveryDate]
stText = "Dear" & CstName & _
"You have been assigned a new ticket." & Chr$(13) & Chr$(13) & _
"Order Number: " & stOrderID & Chr$(13) & _
"Please refer to your order status " & Chr$(13) & _
"Exp Delevery Date: " & DelDate & Chr$(13) & Chr$(13) & _
dQuery & Chr$(13) & _
"This is an automated message. Please do not respond to this e-mail."
'Write the e-mail content for sending to assignee
DoCmd.SendObject , , acFormatTXT, varTo, , , stSubject, stText, True
Err_InformCustomer_Click:
MsgBox Err.Description
End Sub
Form Img: Form and Command1 button to run the code
It would be something like (to insert before CstName = Me![CustName]):
Dim dQuery As String
Dim rs As DAO.Recordset
Set rs = Me!NameOfYourSubformCONTROL.Form.RecordsetClone
While Not rs.EOF
dQuery = dQuery & rs![Brand Name].Value & vbTab & rs![Model Name].Value & vbTab & rs![Color].Value & vbCrLF
Wend
Set rs = Nothing

Referancing form in DoCmd.SearchForRecord when using Navigation form - Access

I have a Mainform with textbox and button to search subform record
it works fine when i directly open Mainform and searching desire record
but when i open my form in Navigaition form it gives me error.
Download My Access Project What i have tried.
Below is my code:
Private Sub cmdSearch_Click()
Dim MainFK As Long
MainFK = DLookup("MainformID", "Subform", "SubformID =" & Me.txtSearch)
Debug.Print MainFK
DoCmd.SearchForRecord acDataForm, "Mainform", acFirst, "MainformID=" &MainFK
End Sub
See Screen Shot:
I think DoCmd.SearchForRecord is tricky on subforms. Try this instead:
Private Sub cmdSearch_Click()
Dim MainFK As Long
Dim rs As DAO.Recordset
Dim WhereStr As String
MainFK = DLookup("MainformID", "Subform", "SubformID =" & Me.txtSearch)
WhereStr = "MainformID=" & MainFK
With Me.Form
Set rs = .RecordsetClone
rs.FindFirst WhereStr
If _
rs.NoMatch _
Then
MsgBox "Subform record not match to mainform record"
Else
.Bookmark = rs.Bookmark
End If
End With
End Sub
Here's your file back: https://drive.google.com/file/d/0B-J5B7nFljZiLVJ1dEtoTVQwcXc/view?usp=sharing

File attachment using SMTP in VB6

I am writing an VB6 application in which I'm making use of cdosys.dll in order to send mails. I am able to attach and send the mails but the problem that I'm facing is the attached file icon image is not getting displayed correctly (default icon image is getting displayed). Also I am not able to attach the files between two paragraphs in the body part. I am using IBM Lotus Notes mail system. Please find below the code that I'm using and also the screenshot of issue that I'm facing
Set objEmail = CreateObject("CDO.Message")
objEmail.MimeFormatted = True
objEmail.To = to address
objEmail.From = from address
objEmail.Subject = "Additional Replacement Letters : " & Format(Now, "mm/dd")
objEmail.TextBody = "Hello Team," & vbCrLf & vbCrLf & "find below the attached letters"
Set fld = FSO.GetFolder(path)
For Each fil In fld.Files
Set iBp = objEmail.AddAttachment(fil)
Next
objEmail.TextBody = "Revert to me for any concerns"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.domain.com"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send
Please help me how to solve this issue.
First, for the icons of files appearing in the attachments section. If a generic file icon is displayed, it may be because either:
your system doesn't have any/the correct MIME type defined for *.doc files (shouldn't be the case if you have Word installed);
the client cannot match any extension (and thus an icon) to the MIME type included with an attached file; or
if the recipient is viewing the emails through a web-based email system, the provider might not have/provide an image to show as an icon for those types of files.
In most cases it's the client software that is too lazy to display the appropriate icon.
Now, if you want the files to appear amid the email body, this is another story. Here an overview of what needs to be done:
First, you don't add files through IMessage.AddAttachment() but with IMessage.AddRelatedBodyPart();
When called, IMessage.AddRelatedBodyPart() will return an IBodyPart object;
Using the IBodyPart object, you need to assign a unique content ID to the piece – you can use the file name, but whatever the CID it must not contain spaces;
You then need to write your email body in HTML (so you can link to them);
In the message you'll add links to related parts as such:
Link to the file
where %CONTENT_ID_OF_THE_FILE% is the content ID you set for the file. Example:
Link to the file
There are two things you'll have to remember if you insert files this way:
You won't see any icon aside or elsewhere related to the file(s) attached, i.e. they'll appear as you set them through your HTML code. If you want any, you'll have to add images (not icon files) the same way and refer to them using the <img> tag and their content ID.
In many clients, you won't see the files in the attachments section, unless they're not being referred to in the body (or their content ID doesn't match, which is the same thing)
Here is some code. It's pretty complete, as I had to test it because I wasn't sure to remember everything correctly. Also, it is assumed you have among the references for your project Microsoft CDO for Windows 2000 Library and Microsoft Scripting Runtime.
Public Function SendNewLetters(ByVal PathForLetters As String, ByVal FromName As String, ByVal FromEmail As String, ByVal ToName As String, _
ByVal ToEmail As String, ByVal SMTPServer As String, ByVal SMTPPort As Long, ByVal SMTPUser As String, _
ByVal SMTPPassword As String, Optional ByVal UseSSL As Boolean = False, Optional ByRef ErrorCode As Long = 0, _
Optional ErrorDesc As String = vbNullString) As Boolean
On Error GoTo ErrorHandler
Const CdoReferenceTypeName = 1
Dim iMsg As CDO.Message ' Not using CreateObject() because I have the reference added
Dim sFileCID As String, sFileExt As String
Dim sIconImageSrc As String, sIconImageCID As String
Dim iBpAttachment As CDO.IBodyPart ' Will be reused more than once
Dim iBpIconImage As CDO.IBodyPart
Dim oFSO As Scripting.FileSystemObject
Dim oFolder As Scripting.Folder
Dim oFile As Scripting.File
Dim oDictAddedExtIcons As Scripting.Dictionary
Set iMsg = New CDO.Message
' Configure SMTP parameters
With iMsg.Configuration
.Fields(cdoSMTPServer) = SMTPServer
.Fields(cdoSMTPServerPort) = SMTPPort
.Fields(cdoSMTPUseSSL) = UseSSL
.Fields(cdoSMTPAuthenticate) = cdoBasic
.Fields(cdoSendUserName) = SMTPUser
.Fields(cdoSendPassword) = SMTPPassword
.Fields(cdoSMTPConnectionTimeout) = 60
.Fields(cdoSendUsingMethod) = cdoSendUsingPort
.Fields.Update
End With
' Set From and To fields
If Len(FromName) > 0 Then
' Let's say we already QP-encoded any special chars for the name
' and checked the email address
iMsg.From = FromName & " <" & FromEmail & ">"
Else
iMsg.From = FromEmail
End If
If Len(ToName) > 0 Then
' Same thing here
iMsg.To = ToName & " <" & ToEmail & ">"
Else
iMsg.To = ToEmail
End If
' Set subject (would need QP encoding as well)
iMsg.Subject = "Additional Replacement Letters : " & Format(Now, "mm/dd")
' Build the body
iMsg.HTMLBody = "<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional //EN""><html><body><p>Hello Team,<br/><br/>" & _
"Please find below the attached letters</p><div style=""display: table"">"
' Will be used to make sure icon images are only added once
Set oDictAddedExtIcons = New Scripting.Dictionary
' Add files here, one new body part for each
Set oFSO = New Scripting.FileSystemObject
If oFSO.FolderExists(PathForLetters) Then
Set oFolder = oFSO.GetFolder(PathForLetters)
For Each oFile In oFolder.Files
' IMPORTANT: Content-IDs should not contain spaces
sFileCID = Replace$(oFile.Name, " ", "_")
Set iBpAttachment = iMsg.AddRelatedBodyPart(oFile.Path, oFile.Name, CdoReferenceTypeName)
iBpAttachment.Fields.Item("urn:schemas:mailheader:content-id") = "<" & sFileCID & ">"
iBpAttachment.Fields.Update ' Dont' forget that line
sFileExt = LCase$(GetFileExtension(oFile.Name))
sIconImageSrc = vbNullString
Select Case sFileExt
Case "doc"
' We provide here the path to a 32x32 image of the doc file icon
sIconImageSrc = "C:\Users\MyUserName\Desktop\DocIcon.png"
' We could also provide images for other extensions, or
' (more involved) query the DefaultIcon for any extension from
' the registry, load the icon from the ico/exe/dll file and
' find the best size/resize if necessary (already have the
' code, but it's a *lot* of code).
Case ".."
' Add support for more
End Select
If Len(sIconImageSrc) > 0 Then
If Not oDictAddedExtIcons.Exists(sFileExt) Then
sIconImageCID = GetFilePart(sIconImageSrc) ' Is the filename for this and the next line
Set iBpIconImage = iMsg.AddRelatedBodyPart(sIconImageSrc, sIconImageCID, CdoReferenceTypeName)
' IMPORTANT: Content-IDs should not contain spaces
sIconImageCID = Replace$(sIconImageCID, " ", "_")
iBpIconImage.Fields.Item("urn:schemas:mailheader:content-id") = "<" & sIconImageCID & ">"
iBpIconImage.Fields.Update ' Dont' forget that line
oDictAddedExtIcons.Add sFileExt, sIconImageCID
sIconImageSrc = "cid:" & sIconImageCID
Else
sIconImageSrc = "cid:" & oDictAddedExtIcons.Item(sFileExt)
End If
End If
iMsg.HTMLBody = iMsg.HTMLBody & "<div style=""display: table-row""><div style=""text-align: left; " & _
"vertical-align: middle; margin-right: 10px;"">"
If Len(sIconImageSrc) > 0 Then
iMsg.HTMLBody = iMsg.HTMLBody & "<img src=""" & sIconImageSrc & """ border=""0"" />"
Else
iMsg.HTMLBody = iMsg.HTMLBody & " "
End If
iMsg.HTMLBody = iMsg.HTMLBody & "</div><div style=""display: table-cell; text-align: left; vertical-align: middle;"">"
iMsg.HTMLBody = iMsg.HTMLBody & "" & oFile.Name & ""
iMsg.HTMLBody = iMsg.HTMLBody & "</div></div>"
Next
End If
iMsg.HTMLBody = iMsg.HTMLBody & "</div><br/>"
iMsg.HTMLBody = iMsg.HTMLBody & "<p>Revert to me for any concerns.</p></body></html>"
' Send away!
iMsg.Send
SendNewLetters = True
Exit Function
ErrorHandler:
ErrorCode = Err.Number
ErrorDesc = Err.Description
SendNewLetters = False
End Function
Public Function GetFilePart(ByVal FilePath As String) As String
Dim lPos As Long
lPos = InStrRev(FilePath, "\")
If lPos > 0 Then
GetFilePart = Right$(FilePath, Len(FilePath) - lPos)
End If
End Function
Public Function GetFileExtension(ByVal FilePath As String, Optional ByVal WithDot As Boolean = False) As String
Dim lPos As Long
lPos = InStrRev(FilePath, ".")
If InStr(1, FilePath, ".") Then
If WithDot Then
GetFileExtension = Right$(FilePath, Len(FilePath) - lPos + 1)
Else
GetFileExtension = Right$(FilePath, Len(FilePath) - lPos)
End If
End If
End Function
Here is the image I used for the *.doc icon:
And this is what it would look like when sent:
I hope it works for you!

Sending Email from Visual Basic

I am working on a project and part of this project is to send emails to a list of email addresses located in SQL.
I am using the following code, which, when sent, just throws a "Sending Failed" error. Nothing else.
Can anyone please help me out with this one? I would really appreciate it.
'Connect to SQL Server database and query out only Address column to fill into DataTable
Dim con As SqlConnection = New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=FigClubs;Integrated Security=True;Pooling=False")
Dim cmd As SqlCommand = New SqlCommand("SELECT Email FROM Members", con)
con.Open()
Dim myDA As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim myDataTable As DataTable = New DataTable
myDA.Fill(myDataTable)
con.Close()
con = Nothing
'New a MailMessage instance
Dim mailMessage As MailMessage = New MailMessage()
mailMessage.From = New MailAddress(TextBox4.Text.Trim())
' Determine the mailMessage.To property based on CheckBox checked status
If CheckBox1.Checked = True Then
For Each dr As DataRow In myDataTable.Rows
mailMessage.To.Add(New MailAddress(dr.Item(0).ToString))
Next
Else
mailMessage.To.Add(New MailAddress(TextBox3.Text.Trim()))
End If
mailMessage.Subject = TextBox1.Text.Trim()
mailMessage.Body = TextBox2.Text.Trim()
Dim smtpClient As SmtpClient = New SmtpClient("smtp.google.com")
smtpClient.Port = ("587")
smtpClient.Credentials = New System.Net.NetworkCredential("HIDDEN", "HIDDEN")
smtpClient.Send(mailMessage)
Try
smtpClient.Send(mailMessage)
Catch smtpExc As SmtpException
'Log errors
MsgBox(smtpExc.Message)
Catch ex As Exception
'Log errors
MsgBox(ex.Message)
End Try
I got that code from a google search.
Any help you can provide to get this working would be so appreciated.
Thanks in advance,
Dan
EDIT - Got it to work:
Got it to work using the following. Just in case anyone else needs it:
Try
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("HIDDEN", "HIDDEN")
Smtp_Server.Port = 587
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.gmail.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress(TextBox4.Text)
e_mail.To.Add(TextBox3.Text)
e_mail.Subject = TextBox1.Text
e_mail.IsBodyHtml = False
e_mail.Body = TextBox2.Text
Smtp_Server.Send(e_mail)
MsgBox("Mail Sent")
Catch error_t As Exception
MsgBox(error_t.ToString)
End Try
Thanks guys. Hope all is well :)
Okay, here's a great solution for you...
Imports System.Net.Mail 'Namespace for sending the email
Public Class Form1 'Whatever class your doing this from...
'I tested with a button click event...
Private Sub btnSendEmail_Click(sender As Object, e As EventArgs) Handles btnSendEmail.Click
Dim dtEmails As New DataTable
Dim strEmails() As String = {"testing#yahoo.com", "testing#gmail.com"}
Dim strBuilder As New System.Text.StringBuilder 'Can be used to build a message
'This was only for my testing...
dtEmails.Columns.Add("EmailAddress")
For Each Str As String In strEmails
dtEmails.Rows.Add(Str)
Next
'Loop through our returned datatable and send the emails...'
If dtEmails.Rows.Count > 0 Then
strBuilder.AppendLine("Emails Confirmation")
strBuilder.AppendLine(" ")
For i As Integer = 0 To dtEmails.Rows.Count - 1 'Whatever your datatbale is called'
Try
Dim newMail As New Mail 'Use our new mail class to set our properties for the email'
newMail.MailMessageTo = dtEmails.Rows(i).Item("EmailAddress") 'What your email address column name is in the data table'
newMail.MailSubject = "Just a Test email!"
newMail.MailMessage = "Did you get this email, please let me know!"
If Mail.SendMail(newMail) Then
strBuilder.AppendLine("SENT - " & dtEmails.Rows(i).Item("EmailAddress").ToString.ToUpper)
Else
strBuilder.AppendLine("FAILED - " & dtEmails.Rows(i).Item("EmailAddress").ToString.ToUpper)
End If
Catch ex As Exception
Continue For
End Try
Next
End If
If strBuilder.Length > 0 Then
MessageBox.Show(strBuilder.ToString())
End If
End Sub
End Class
'You can put this class at the bottom of your class your using...This handles the emails...
Public Class Mail
Public Property MailMessageTo As String
Public Property MailMessage As String
Public Property MailSubject As String
'This will send your mail...
Public Shared Function SendMail(ByVal oMail As Mail) As Boolean
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Try
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("EMAIL", "PASSWORD")
Smtp_Server.Port = 587
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.gmail.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress("EMAIL") 'Whatever you want here'
e_mail.To.Add(oMail.MailMessageTo)
e_mail.Subject = oMail.MailSubject
e_mail.IsBodyHtml = False
e_mail.Body = oMail.MailMessage
Smtp_Server.Send(e_mail)
Return True
Catch error_t As Exception
Return False
Finally
Smtp_Server = Nothing
e_mail = Nothing
End Try
End Function
End Class
This works really well, you can edit as needed to. This is much more organized and easier to maintain for what you would need. Also another good note to remember your looping through a DataTable sending emails, you may want to put some of this on a BackgroundWorker as this can lock up the UI thread... Another thing to check when looping through your DataTable, you may want to check if the email your referencing isn't 'DBNull.value', I didn't check for that, other wise it will throw an exception.
Happy Coding!

Create Task from sent mail and include attachments

In Outlook 2010 VBA, I want to create a task when I send an email.
I want to add to the task all the attachments from the email.
I tried .Attachments.Add (is not supported), .Attachments = item.Attachments returns property is read only.
Is it possible or how can I attach the email to the task?
Public WithEvents myOlApp As Outlook.Application
Private Sub Application_MAPILogonComplete()
End Sub
Private Sub Application_Startup()
Initialize_handler
End Sub
Public Sub Initialize_handler()
Set myOlApp = CreateObject("Outlook.Application")
End Sub
Private Sub myOlApp_ItemSend(ByVal item As Object, Cancel As Boolean)
Dim intRes As Integer
Dim strMsg As String
Dim objTask As TaskItem
Set objTask = Application.CreateItem(olTaskItem)
Dim strRecip As String
Dim att As MailItem
Dim objMail As Outlook.MailItem
strMsg = "Do you want to create a task for this message?"
intRes = MsgBox(strMsg, vbYesNo + vbExclamation, "Create Task")
If intRes = vbNo Then
Cancel = False
Else
For Each Recipient In item.Recipients
strRecip = strRecip & vbCrLf & Recipient.Address
Next Recipient
With objTask
'.Body = strRecip & vbCrLf & Item.Body
.Body = item.Body
.Subject = item.Subject
.StartDate = item.ReceivedTime
.ReminderSet = True
.ReminderTime = DateSerial(Year(Now), Month(Now), Day(Now + 1)) + #8:00:00 AM#
**.Attachments.Add (item.Attachments)**
.Save
End With
Cancel = False
End If
Set objTask = Nothing
End Sub
Attachments.Add allows to pass a string as a parameter (fully queslified attachment filename) or an Outlook item (such as MailItem). Youy are passing Attachments collection as a parameter, you cannot do that.
For each attachment, save the attachment first(Attachment.SaveAsFile), then add them to the task one at a time passing the file name as the parameter.
Here is my final code
Public WithEvents myOlApp As Outlook.Application
Private Sub Application_MAPILogonComplete()
End Sub
Private Sub Application_Startup()
Initialize_handler
End Sub
Public Sub Initialize_handler()
Set myOlApp = CreateObject("Outlook.Application")
End Sub
Private Sub myOlApp_ItemSend(ByVal item As Object, Cancel As Boolean)
Dim intRes As Integer
Dim strMsg As String
Dim objTask As TaskItem
Set objTask = Application.CreateItem(olTaskItem)
Dim strRecip As String
Dim att As MailItem
Dim objMail As Outlook.MailItem
Dim Msg As Variant
strFolderPath = "C:\temp" ' path to target folder
strMsg = "Do you want to create a task for this message?"
intRes = MsgBox(strMsg, vbYesNo + vbExclamation, "Create Task")
If intRes = vbNo Then
Cancel = False
Else
For Each Recipient In item.Recipients
strRecip = strRecip & vbCrLf & Recipient.Address
Next Recipient
item.SaveAs strFolderPath & "\" & "test" & ".msg", olMSG
'item.Save
With objTask
'.Body = strRecip & vbCrLf & Item.Body
.Body = item.Body
.Subject = item.Subject
.StartDate = item.ReceivedTime
.ReminderSet = True
.ReminderTime = DateSerial(Year(Now), Month(Now), Day(Now + 1)) + #8:00:00 AM#
.Attachments.Add item
.Save
End With
Cancel = False
End If
Set objTask = Nothing
End Sub