Preserving html format in creating tasks from email - vba

I have a little script that converts an email into a Task in my outlook.
My main frustration is that it won't preserve the html format, and deals with embedded images as attachments. I was wondering if anyone could help. I know it is possible as I've copied the body of an email directly across to the body of a task manually and it is preserved fine.
Sub ConvertSelectedMailtoTask()
Dim objApp As Outlook.Application
Dim objTask As Outlook.TaskItem
Dim objMail As Outlook.MailItem
Set objTask = Application.CreateItem(olTaskItem)
Set objApp = Application
If TypeName(objApp.ActiveWindow) = "Explorer" Then
For Each objMail In Application.ActiveExplorer.Selection
If Left(objMail.Subject, 3) = "RE:" Or Left(objMail.Subject, 3) = "FW:" Then
subj = Right(objMail.Subject, Len(objMail.Subject) - 4)
Else
subj = objMail.Subject
End If
With objTask
.Subject = subj
.Importance = objMail.Importance
.StartDate = objMail.ReceivedTime
.Body = objMail.Body
.DueDate = Date + 3
If objMail.Attachments.Count > 0 Then
CopyAttachments objMail, objTask
End If
.ReminderSet = True
.ReminderTime = Date + 2.5
.Sensitivity = olPrivate
.Save
End With
Next
ElseIf TypeName(objApp.ActiveWindow) = "Inspector" Then
Set objMail = objApp.ActiveInspector.CurrentItem
If Left(objMail.Subject, 3) = "RE:" Or Left(objMail.Subject, 3) = "FW:" Then
subj = Right(objMail.Subject, Len(objMail.Subject) - 4)
Else
subj = objMail.Subject
End If
With objTask
.Subject = subj
.Importance = objMail.Importance
.StartDate = objMail.ReceivedTime
.Body = objMail.Body
.DueDate = Date + 3
If objMail.Attachments.Count > 0 Then
CopyAttachments objMail, objTask
End If
.ReminderSet = True
.ReminderTime = Date + 2.5
.Sensitivity = olPrivate
.Save
End With
End If
Set objTask = Nothing
Set objMail = Nothing
Set objApp = Nothing
End Sub
And here is the script for the attachments
Sub CopyAttachments(objSourceItem, objTargetItem)
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldTemp = fso.GetSpecialFolder(2) ' TemporaryFolder
strPath = fldTemp.Path & "\"
For Each objAtt In objSourceItem.Attachments
strFile = strPath & objAtt.FileName
objAtt.SaveAsFile strFile
objTargetItem.Attachments.Add strFile, , , objAtt.DisplayName
fso.DeleteFile strFile
Next
Set fldTemp = Nothing
Set fso = Nothing
End Sub
Update:
I found a bit of code that uses a word document to preserve the formatting:
Sub CopyFullBody(sourceItem As Object, targetItem As Object)
Dim objDoc As Word.Document
Dim objSel As Word.Selection
Dim objDoc2 As Word.Document
Dim objSel2 As Word.Selection
On Error Resume Next
' get a Word.Selection from the source item
Set objDoc = sourceItem.GetInspector.WordEditor
If Not objDoc Is Nothing Then
Set objSel = objDoc.Windows(1).Selection
objSel.WholeStory
objSel.Copy
Set objDoc2 = targetItem.GetInspector.WordEditor
If Not objDoc2 Is Nothing Then
Set objSel2 = objDoc2.Windows(1).Selection
objSel2.PasteAndFormat wdPasteDefault
Else
MsgBox "Could not get Word.Document for " & _
targetItem.Subject
End If
Else
MsgBox "Could not get Word.Document for " & _
sourceItem.Subject
End If
Set objDoc = Nothing
Set objSel = Nothing
Set objDoc2 = Nothing
Set objSel2 = Nothing
End Sub
This doesn't seem like it would be the only solution hence updating my own post instead of answering my question as this seems a bit long winded (using another application just to give me formatting, when I can copy and paste text manually just fine all in Outlook). If anyone has any other thoughts on this/defining attachment types please carry on answering!

in the line
.Body = objMail.Body
you only ask fot the non-formatted Body. Try instead:
.Body = objMail.htmlBody
and something completely different: I just put reminders onto the emails themselves, so I have no need to create extra Tasks at all...

Keep in mind that Outlook tasks, appointments and tasks work with RTF, not HTML. hence TaskItem, ContactItem and AppointmentItem objects only expose the RtfBody property, but not HTMLBody (like MailItem does).
You will need to either convert HTML to RTF (you can try the Word Object Model for that) or use Redemption (I am its author): unlike Outlook Object Model, it exposes the RDOTaskItem.HTMLBody property and dynamically converts HTML to the native (for tasks) RTF when that property is set.

Related

Search for sent items with today's date and specific subject

I want when Outlook opens to:
Search sent items with today's date with a specific subject.
If none is found, then send the "Test" email.
If found, display messagebox that says "Email is found".
I have only been able to do #1.
Private Sub Application_Startup()
Dim MItem As MailItem
Set MItem = Application.CreateItem(olMailItem)
MItem.Subject = "Test Alert"
MItem.To = "email#abc.com"
MItem.DeferredDeliveryTime = DateAdd("n", 1, Now) 'n = minute, h=hour
MItem.Send
End Sub
Update:
This is what I've tried. It doesn't seem to be searching the Sent Items folder with the subject.
Public Function is_email_sent()
Dim olApp As Outlook.Application
Dim olNs As Outlook.NameSpace
Dim olFldr As Outlook.Folder
Dim olItms As Outlook.Items
Dim objItem As Outlook.MailItem
On Error Resume Next
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set olFldr = olNs.GetDefaultFolder(Outlook.olFolderSentMail)
For Each objItem In olFldr.Items
If objItem.Subject = "Test Alert" And _
objItem.SentOn = Date Then _
MsgBox "Yes. Email found"
Else
MsgBox "No. Email not found"
Exit For
End If
Next objItem
End Function
The main error is misuse of On Error Resume Next. Errors are bypassed, not fixed.
Public Sub is_email_sentFIX()
Dim olFldr As Folder
Dim olItms As Items
Dim objItem As Object
Dim bFound As Boolean
' Not useful here.
' Use for specific purpose to bypass **expected** errors.
'On Error Resume Next
Set olFldr = Session.GetDefaultFolder(olFolderSentMail)
Set olItms = olFldr.Items
olItms.sort "[SentOn]", True
For Each objItem In olItms
If objItem.Class = OlMail Then
Debug.Print objItem.Subject
If objItem.Subject = "Test Alert" Then
Debug.Print objItem.SentOn
Debug.Print Date
If objItem.SentOn > Date Then
MsgBox "Yes. Email found"
bFound = True
Exit For
End If
End If
End If
Next objItem
If bFound = False Then
MsgBox "No. Email not found"
End If
End Sub
If there are an excessive number of items in the Sent folder the "not found" outcome will be slow.
One possible option to the brute force way is to Restrict to the specific item, rather than using If statements.
this is some code ive used;
Sub sendmail10101() 'this is to send the email from contents in a cell
Dim obApp As Object
Dim NewMail As MailItem
Set obApp = Outlook.Application
Set NewMail = obApp.CreateItem(olMailItem)
'You can change the concrete info as per your needs
With NewMail
.Subject = Cells(21, 3).Value
.To = Cells(18, 3).Value
.Body = "Good day" & vbCrLf & "i hope you are keeping well " & vbCrLf & vbCrLf & "please can you assist with the below members infomation;" & vbCrLf & vbCrLf & vbCrLf & Cells(20, 3).Value
'.Attachments.Add ("C:\Attachments\Test File.docx")
.Importance = olImportanceHigh
.Display
End With
Set obApp = Nothing
Set NewMail = Nothing
End Sub
the next part is to search the mail box, which you can also use to search from the first initial cell;
Option Explicit
Public Sub Search_Outlook_Emails()
Dim outApp As Outlook.Application
Dim outNs As Outlook.Namespace
Dim outStartFolder As Outlook.MAPIFolder
Dim foundEmail As Outlook.MailItem
Set outApp = New Outlook.Application
Set outNs = outApp.GetNamespace("MAPI")
'Start at Inbox's parent folder
Set outStartFolder = outNs.GetDefaultFolder(Outlook.olFolderInbox).Parent
'Or start at folder selected by user
'Set outStartFolder = outNs.PickFolder
If Not outStartFolder Is Nothing Then
Set foundEmail = Find_Email_In_Folder(outStartFolder, ThisWorkbook.Sheets("Dashboard").TextBox1.Value)
If Not foundEmail Is Nothing Then
If MsgBox("Email subject: " & foundEmail.Subject & vbNewLine & vbNewLine & _
"Folder: " & foundEmail.Parent.FolderPath & vbNewLine & vbNewLine & _
"Open the email?", vbYesNo, "'" & ThisWorkbook.Sheets("Dashboard").TextBox1.Value & "' found") = vbYes Then
foundEmail.Display
End If
Else
MsgBox "", vbOKOnly, "'" & ThisWorkbook.Sheets("Dashboard").TextBox1.Value & "' not found"
End If
End If
End Sub
Private Function Find_Email_In_Folder(outFolder As Outlook.MAPIFolder, findText As String) As Outlook.MailItem
Dim outItem As Object
Dim outMail As Outlook.MailItem
Dim outSubFolder As Outlook.MAPIFolder
Dim i As Long
Debug.Print outFolder.FolderPath
Set Find_Email_In_Folder = Nothing
'Search emails in this folder
i = 1
While i <= outFolder.Items.Count And Find_Email_In_Folder Is Nothing
Set outItem = outFolder.Items(i)
If outItem.Class = Outlook.OlObjectClass.olMail Then
'Does the findText occur in this email's body text?
Set outMail = outItem
If InStr(1, outMail.Body, findText, vbTextCompare) > 0 Then Set Find_Email_In_Folder = outMail
End If
i = i + 1
Wend
DoEvents
'If not found, search emails in subfolders
i = 1
While i <= outFolder.Folders.Count And Find_Email_In_Folder Is Nothing
Set outSubFolder = outFolder.Folders(i)
'Only check mail item folders
If outSubFolder.DefaultItemType = Outlook.olMailItem Then Set Find_Email_In_Folder = Find_Email_In_Folder(outSubFolder, findText)
i = i + 1
Wend
End Function
the previous code brings us a message box to say if its been found which can be removed but maybe use the message box and an IF statement
such as;
with activeworkbook
if msgbox.value = "yes" then
range("A1:A30") = "COMPLETED" 'ASSUMING THIS IS THE INTIAL TEST RANGE IT WILL CHANGE THE SUBJECT THUS STOPPING THE FIRST MACRO
end if
end with
or if no message box then use something such as IF found then so on...
hope this helps

Is there a way to change a Word document's filename and email subject using combobox data (VBA)?

I'm trying to set up a form so that when a subject - in the example I have, it's animals - is selected from a ComboBox, it changes both the file name and also the subject line of the email. Currently, it just sends an email when you click the submit button, but I need to differentiate between files depending on which subject is selected. I've tried searching for an answer, but I've so far not come across anything related.
The ComboBox has four entries in it. Tiger, Monkey, Elephant, Giraffe.
The ComboBox is named "Animals" and it's tag is "ComboBox1"
Unfortunately, for whatever reason, I am unable to upload a picture, but it is a "Combo Box Content Control" if that helps. Apologies, I have limited knowledge of this stuff, it's mostly been trial and error to get me to this point and borrowing other pieces of code.
Any suggestions would be helpful.
Private Sub Submit_Click()
Dim objOutlook As Object
Dim objOutlookMsg As Object
Dim objInspector As Object
Dim objDoc As Word.Document
Dim objRange As Range
Dim sDocname As String
ActiveDocument.Save
sDocname = ActiveDocument.FullName
If Len(ActiveDocument.Path) = 0 Then
MsgBox "Document is not saved!"
GoTo lbl_Exit
End If
On Error Resume Next
Set objOutlook = GetObject(, "Outlook.Application")
If Err <> 0 Then
MsgBox "Outlook is not running."
GoTo lbl_Exit
End If
On Error GoTo 0
Set objOutlookMsg = objOutlook.createitem(0)
With objOutlookMsg
.To = "email#emailaddress.com"
.Cc = ""
.Subject = "Favourite Animal is "
.attachments.Add sDocname
Set objInspector = .GetInspector
Set objDoc = objInspector.WordEditor
Set objRange = objDoc.Range(0, 0)
.Display
objRange.Text = "My favourite animal is the "
.Send
End With
lbl_Exit:
Set objDoc = Nothing
Set objRange = Nothing
Set objOutlookMsg = Nothing
Set objInspector = Nothing
Set objOutlook = Nothing
Exit Sub
End Sub
What about something like this?
Private Sub Submit_Click()
Dim objOutlook As Object
Dim objOutlookMsg As Object
Dim objInspector As Object
Dim objDoc As Word.Document
Dim objRange As Range
Dim sDocname As String
'new declarations.
Dim cmb As ContentControl
Dim sSelText As String
'get a reference of the combobox.
Set cmb = ThisDocument.SelectContentControlsByTag("Combobox1")(1)
'get the selected item in a variable.
sSelText = cmb.Range.Text
Set cmb = Nothing
'enforce making a selection.
If sSelText = "DEFAULT_TXT" Then 'write here the default text of your combobox.
MsgBox "Please select subject from the dropdown menu.", vbCritical, "No selection!"
Else
ActiveDocument.Save
sDocname = ActiveDocument.FullName
If Len(ActiveDocument.Path) = 0 Then
MsgBox "Document is not saved!", vbCritical, "Error!"
GoTo lbl_Exit
End If
On Error Resume Next
Set objOutlook = GetObject(, "Outlook.Application")
If Err <> 0 Then
MsgBox "Outlook is not running."
GoTo lbl_Exit
End If
On Error GoTo 0
Set objOutlookMsg = objOutlook.createitem(0)
With objOutlookMsg 'use the selected item as you wish.
.To = "email#emailaddress.com"
.Cc = ""
.Subject = "Favourite Animal is " & sSelText
.attachments.Add sDocname & "_" & sSelText
Set objInspector = .GetInspector
Set objDoc = objInspector.WordEditor
Set objRange = objDoc.Range(0, 0)
.Display
objRange.Text = "My favourite animal is the " & sSelText
.Send
End With
End If
lbl_Exit:
Set objDoc = Nothing
Set objRange = Nothing
Set objOutlookMsg = Nothing
Set objInspector = Nothing
Set objOutlook = Nothing
End Sub

Runtime Error 424: Object not Defined"- While Sending Email Using Outlook 2013

I am using below code to send multiple emails through outlook, this code is working fine when I use Excel 2007 and Outlook 2007 however when I tried to run same code in Excel 2013 and Outlook 2013 it is throwing an error "Runtime Error 424: Object not Defined" in the below code:
Set Doc = olMail.GetInspector.WordEditor
Can somebody please check below coding and let me know what do I need to change if I want to use same macro in 2013 version?
Sub Msmail()
Dim otlApp As Object
Dim olMail As Object
Set otlApp = CreateObject("Outlook.Application")
Set olMail = otlApp.CreateItem(olMailItem)
Set mainWB = ActiveWorkbook
Worksheets("Mail").Select
ActiveSheet.Calculate
Total_Site = Range("Total_Site")
For Site_Count = 1 To Total_Site
Application.StatusBar = False
ActiveSheet.Calculate
Range("Site_Count") = Site_Count
ActiveSheet.Calculate
If Range("Send_Email") = "Y" Then
Set mainWB = ActiveWorkbook
Set olMail = otlApp.CreateItem(olMailItem)
Set Doc = olMail.GetInspector.WordEditor '<~ ERROR 424 HERE
SendID = mainWB.Sheets("Mail").Range("To_List").Value
CCID = mainWB.Sheets("Mail").Range("Cc_List").Value
Subject = mainWB.Sheets("Mail").Range("Subject_Line").Value
Body = mainWB.Sheets("Summary").Range("Mail_Body").Value
AttachFile = mainWB.Sheets("Mail").Range("StrPath").Value
StrPath = ActiveSheet.Range("StrPath").Value
With olMail
.To = SendID
If CCID <> 0 Then
.CC = CCID
End If
.Subject = Subject
mainWB.Sheets("Summary").Range("Mail_Body").Copy
Set WrdRng = Doc.Range
.Display
WrdRng.Paste
'StrPath = Range("StrPath").Value
StrFile = Range("StrFile").Value & "*.*"
StrFile = Range("StrFile").Value
.Attachments.Add StrPath & "\" & StrFile
.Send
End With
End If
Next Site_Count
End Sub
OK - so there appear to be quite a lot of issues with the current code; you have duplication of code and non-dimensioned variables. I have tried to condense the code down, added direct references and this will hopefully make it more readable and (should maybe) work, but it's untested... I don't have the ranges set out in relevant sheets and no data to test it
Sub msMail()
Dim olApp As Object: Set olApp = CreateObject("Outlook.Application")
Dim olMail As Object
Dim Total_Site As Range, Doc As Variant, WrdRng As Range
Dim StrPath As String, StrFile As String, Site_Count As Long
Dim wbMain As Workbook: Set wbMain = ThisWorkbook
Dim wsMail As Worksheet: Set wsMail = wbMain.Worksheets("Mail")
Dim wsSumm As Worksheet: Set wsSumm = wbMain.Worksheets("Summary")
With wsMail
.Calculate ' Not sure why this is included...
Set Total_Site = Range("Total_Site")
For Site_Count = 1 To Total_Site.Count
''Application.StatusBar = False
Range("Site_Count") = Site_Count
If Range("Send_Email") = "Y" Then
Set olMail = olApp.CreateItem(olMailItem)
Set Doc = olMail.GetInspector.WordEditor
If Not Doc Is Nothing Then
With olMail
.To = wsMail.Range("To_List")
.CC = IIf(wsMail.Range("Cc_List") <> 0, wsMail.Range("Cc_List"), "")
.Subject = wsMail.Range("Subject_Line")
wsSumm.Range("Mail_Body").Copy
Set WrdRng = Doc.Range
.Display
WrdRng.Paste
StrPath = wsMail.Range("StrPath")
StrFile = wsMail.Range("StrFile")
.Attachments.Add StrPath & "\" & StrFile
' .Send
End With
End If
End If
Next Site_Count
End With
End Sub

Forward selected emails without non-PDF attachments

I am trying to send a completed work email containing multiple PDF attachments, I wish send only the PDF files to the recipient and avoid any other atttachments such as excel files or image files only pdf to be forwarded.
P.S. note email may have more than 1 attachments with combination of pdfs, excels, images, however only pdfs have to be forwarded. I'm unable to find how to code that part. please see below my existing code.
Sub Send2Recipient()
' Send Completed Message to Recipient
On Error Resume Next
Dim oApp As Outlook.Application
Dim objFolder As Outlook.MAPIFolder
Set oApp = New Outlook.Application
Set objNS = Application.GetNamespace("MAPI")
Set objInbox = objNS.GetDefaultFolder(olFolderInbox)
Set objFolder = objInbox.Folders("Helpdesk")
Dim oEmail As Outlook.MailItem
Dim strFile As String
Dim sFileType As String
'Require that this procedure be called only when a message is selected
If Application.ActiveExplorer.Selection.Count = 0 Then
Exit Sub
End If
For Each objItem In Application.ActiveExplorer.Selection
If objFolder.DefaultItemType = olMailItem Then
If objItem.Class = olMail Then
Response = MsgBox("Forward message (" + item.Subject + ") to Appended Subject")
Set myforward = objItem.Forward
myforward.Body = "Scan Only"
myforward.Subject = "Scan Only"
myforward.Recipients.Add "DHL.GB01PREV#dhl.com"
myforward.Display
End If
End If
Next
End Sub
Updated VBA script
Sub Send2New()
' Send Completed Message to Accenture
On Error Resume Next
Dim oApp As Outlook.Application
Dim objFolder As Outlook.MAPIFolder
Set oApp = New Outlook.Application
Set objNS = Application.GetNamespace("MAPI")
Set objInbox = objNS.GetDefaultFolder(olFolderInbox)
'Set objFolder = objInbox.Folders("Helpdesk")
Dim oEmail As Outlook.MailItem
Dim strFile As String
Dim sFileType As String
Dim bk, fg As Integer
'Require that this procedure be called only when a message is selected
If Application.ActiveExplorer.Selection.Count = 0 Then
Exit Sub
End If
For Each objItem In Application.ActiveExplorer.Selection
If objFolder.DefaultItemType = olMailItem Then
If objItem.Class = olmail Then
Response = MsgBox("Forward message (" + Item.Subject + ") to Appended Subject")
Set myforward = objItem.Forward
myforward.Body = "Scan Only"
myforward.Subject = "Scan Only"
myforward.Recipients.Add "xyz#abc.com"
myforward.Display
bk = myforward.Attachments.Count
fg = 1
For i = 1 To bk
If InStr(LCase(myforward.Attachments(fg).FileName), ".pdf") = 0 Then
myforward.Attachments(fg).Delete
Else: fg = fg + 1
End If
Next i
End If
End If
Next
End Sub
I have created two macros for you.
The first, Investigate, outputs information about attachments to the Immediate Window. There are four types of attachment. A “standard” attachment is of type “By Value”. I have never seen an OLE attachment and do not know what such an attachment is. I have seen the other types but not for many years.
The second, ForwardEmailsWithoutNonPdfAttachments(), demonstrates the functionality you seek. I have sent emails containing a selection of attachments from my Gmail account to my Outlook account and have used the macro to send them back with the non-PDF attachments deleted. These attachments were all “By Value” attachments. I am not sure what would happen if you tried to forward emails with other types of attachments which is the reason for the first macro. This macro is not very elegant but it demonstrates the techniques necessary to meet your objective.
Option Explicit
Public Sub Investigate()
Dim AttachType As String
Dim Exp As Outlook.Explorer
Dim InxAttach As Long
Dim ItemCrnt As MailItem
Dim NumAttach As Long
Dim NumSelected As Long
Set Exp = Outlook.Application.ActiveExplorer
NumSelected = Exp.Selection.Count
If NumSelected = 0 Then
Debug.Print "No emails selected"
Else
For Each ItemCrnt In Exp.Selection
With ItemCrnt
Debug.Print "From: " & .SenderName & " | Subject: " & .Subject
For InxAttach = 1 To .Attachments.Count
' There are four types of attachment:
' * olByValue 1
' * olByReference 4
' * olEmbeddedItem 5
' * olOLE 6
With .Attachments(InxAttach)
Select Case .Type
Case olByValue
AttachType = "Val"
Case olEmbeddeditem
AttachType = "Ebd"
Case olByReference
AttachType = "Ref"
Case olOLE
AttachType = "OLE"
Case Else
AttachType = "Unk"
End Select
Debug.Print AttachType & " " & .FileName & " | " & .DisplayName
End With ' .Attachments(InxAttach)
Next ' ItemCrnt
End With
Next
End If
End Sub
Sub ForwardEmailsWithoutNonPdfAttachments()
Dim AttachType As String
Dim Exp As Outlook.Explorer
Dim InxAttach As Long
Dim ItemCopy As MailItem
Dim ItemOrig As MailItem
Dim NumAttach As Long
Dim NumSelected As Long
Set Exp = Outlook.Application.ActiveExplorer
NumSelected = Exp.Selection.Count
If NumSelected = 0 Then
Debug.Print "No emails selected"
Else
For Each ItemOrig In Exp.Selection
Set ItemCopy = ItemOrig.Copy
With ItemCopy
.Subject = "FW: " & .Subject
' Delete all original recipients
Do While .Recipients.Count > 0
.Recipients.Remove (1)
Loop
' Add new recipient
.Recipients.Add "tonydallimore23#gmail.com"
If .Attachments.Count > 0 Then
For InxAttach = .Attachments.Count To 1 Step -1
With .Attachments(InxAttach)
' This will stop the macro if an attachment is not a regular attachment
Debug.Assert .Type = olByValue
If LCase(Right$(.FileName, 4)) <> ".pdf" Then
.Delete
End If
End With ' .Attachments(InxAttach)
Next InxAttach
End If
.Send
End With ' ItemCopy
Set ItemCopy = Nothing
Next ItemOrig
End If
End Sub

Outlook VB Script to Create Task From Email - not creating task

I've got the following script which should for all that I can see, work without issue (and in fact at one point yesterday was working - but I must have inadvertently changed something when trying to clean up the code because it's no longer working today).
Perhaps another set of eyes can help me. I have a rule setup to set these emails into their own folder and run the script in Outlook. That works without issue - the issue comes from the script itself.
The subject of the emails that come in that get filtered are generally something like this:
"Ticket: 328157 School: BlahBlah Issues: Problems with flux capacitor"
The idea is that the script will create a task with the appropriate priority level and put it in the appropriate category (and include just the stuff in the subject after 'School"' because the ticket # is not important).
Here is the script:
Sub MakeTaskFromMail(MyMail As Outlook.MailItem)
Dim strID As String
Dim olNS As Outlook.NameSpace
Dim olMail As Outlook.MailItem
Dim objTask As Outlook.TaskItem
'Get Specific Email based on ID
strID = MyMail.EntryID
Set olNS = Application.GetNamespace("MAPI")
Set olMail = olNS.GetItemFromID(strID)
Set objTask = Application.CreateItem(olTaskItem)
'**************************
'*****SET TASK SUBJECT*****
'**************************
Dim sInput As String
Dim sOutput As String
'get the email subject
sInput = olMail.Subject
'get all the text after School: in the subject
sOutput = Mid(sInput, InStr(sInput, "School:") + 8)
Dim priorityUrgentString As String
Dim priorityHighString As String
Dim priorityMediumString As String
Dim priorityLowString As String
'Set Priority Strings to check for to determine category
priorityUrgentString = "Priority: Urgent"
priorityHighString = "Priority: High Priority"
priorityMediumString = "Priority: Medium"
priorityLowString = "Priority: Project"
'check to see if ticket is Urgent
'if urgent - due date is today and alert is set for 8am
If InStr(olMail.Body, priorityUrgentString) <> 0 Then
With objTask
.Subject = sOutput
.DueDate = olMail.SentOn
.Body = olMail.Body
.Categories = "Urgent"
.Importance = olImportanceHigh
.ReminderSet = True
.ReminderTime = objTask.DueDate
End With
'check to see if ticket is High Priority
'if High Priority - due date is today - alert is set for 8am
ElseIf InStr(olMail.Body, priorityHighString) <> 0 Then
With objTask
.Subject = sOutput
.DueDate = olMail.SentOn + 2
.Body = olMail.Body
.Categories = "High"
.Importance = olImportanceHigh
.ReminderSet = True
.ReminderTime = objTask.DueDate + 2
End With
'check to see if its a medium priority
'if medium - due date is set for 7 days, no alert
ElseIf InStr(olMail.Body, priorityMediumString) <> 0 Then
With objTask
.Subject = sOutput
.DueDate = olMail.SentOn + 7
.Body = olMail.Body
.Categories = "Medium"
.Importance = olImportanceNormal
End With
'check to see if its a project priority
'if project - due date is set for 21 days, no alert
ElseIf InStr(olMail.Body, priorityLowString) <> 0 Then
With objTask
.Subject = sOutput
.DueDate = olMail.SentOn + 21
.Body = olMail.Body
.Categories = "Project"
.Importance = olImportanceLow
End With
End If
'Copy Attachments
Call CopyAttachments(olMail, objTask)
'Save Task
objTask.Save
Set objTask = Nothing
Set olMail = Nothing
Set olNS = Nothing
End Sub
Sub CopyAttachments(objSourceItem, objTargetItem)
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldTemp = fso.GetSpecialFolder(2) ' TemporaryFolder
strPath = fldTemp.Path & "\"
For Each objAtt In objSourceItem.Attachments
strFile = strPath & objAtt.FileName
objAtt.SaveAsFile strFile
objTargetItem.Attachments.Add strFile, , , objAtt.DisplayName
fso.DeleteFile strFile
Next
Set fldTemp = Nothing
Set fso = Nothing
End Sub
What I can see without running the script is this:
You will have to save the TaskItem, after setting it (use .Save as the last line within the With)
Also, you will probably have to set the ReminderTime matching the mailitem
.ReminderTime = olMail.SentOn
instead of
.ReminderTime = objTask.DueDate
because it isn't saved yet