Email to task without changin formatting

Status
Not open for further replies.

LaoFly

New Member
Outlook version
Outlook 2016 64 bit
Email Account
Exchange Server
Hello Slipstick forum!

I got a little macro running which turns specific mails into tasks basically working as a tiny supportsystem for me to keep track of stuff at my company.
The thing is that it won't keep the formatting. I tried 3 way to do this:

Right now I just use
Code:
newTask.Attachments.Add NewItem
but I don't really like it that way as it's a mail in a task.

The second one is the 'open in word, copy, paste' method.
Code:
    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
        End If
    End If
newTask.Display
this one looks lovely, but keeps crashing every once in a while.

And simply using
Code:
 newTask.Body = NewItem.Body
resulsts in missing images, double spacing (which I have taken care of), and just odd formatting in general.

Is there any other way, or maybe some ideas to fix the crashes ?

Outlook 2010 H&B running on Server 2012R2.


If needed, I will provide further details and information.

Best wishes and thanks in advance,
Chris
 
Part of the problem is that tasks doesn't support HTML, so you can't use HTML body. I haven't tried converting the message body to RTF then pasting... not sure it will work. (MailItem.RTFBody Property (Outlook) I haven't had crash problems with the word paste method - but it could be something different between 2016 and 2010.

So basically... you are stuck unless RTF body works better than using word.
 
I tried experimenting with RTF/HTML convertion, no luck with that.
But I'll give it another shot tomorrow.

Yeah it's kinda weird. Most of the time it works just fine, then all of a sudden it crashes and disables the rules. I created a rule to check if the other rule is active, if not, activate, but when it crashes both rules are disabled. So I would need a rule to check the rule to check the rule.

I guess I'll look into it again toomorrow maybe I'll get it to work without crashing.


Oh by the way, I read many of your posts about VBA thank you really much, I appreaciate your work!
Got some pretty neat things to work because of you!

Im gonna check back tomorrow with some updates.


With kind regards,
Chris
 
Heh... it works here. I changed the macro i use to use RTF - in my case, i save the new tasks to one of two folders and use a stub macro to set the folder (and the GetCurrentItem function so it works for open or selected messages) - the task looks nice - downloaded images won't copy (even if i download the blocked content first), embedded images are not kept. Using .Body = objMail.RTFBody won't keep them either.

This screenshot is of the original message (the pink formatting was another macro test for someone last week :)) - using word to paste is in the middle and using RTF is on the right. Word gets external content.

formatting.png

This message has 3 images inserted - RTF drops them but my macro adds them as attachments.

embedded-images.png

Code:
Sub TaskRTF()
Dim Ns As Outlook.NameSpace
Set Ns = Application.GetNamespace("MAPI")
Set tasksFolder = Ns.GetDefaultFolder(olFolderTasks)
ConvertRTFToTask
End Sub


Private Sub ConvertRTFToTask()
    Dim objTask As Outlook.TaskItem
    Dim objMail As Outlook.MailItem
   
    On Error Resume Next
   Set objMail = GetCurrentItem()
   Set objTask = tasksFolder.Items.Add(olTaskItem)
 
   strRTF = StrConv(objMail.RTFBody, vbUnicode)

Debug.Print strRTF
 
With objTask
If objMail.Attachments.Count > 0 Then
     CopyAttachments objMail, objTask
End If

    .Subject = objMail.Subject
    .DueDate = Now + 3
    .StartDate = Now + 2
    .ReminderSet = True
    .ReminderTime = .DueDate + "2:00:00 PM"
    .Body = strRTF
   ' .Save
    .Display
End With

    Set objTask = Nothing
    Set objMail = Nothing
End Sub
 
Yeah when I first tried to do it, I just copied the body, removed the double spaces and reattached all images. The thing is, when someone get a mail marked as spam by our firewall, they get a mail, forward it to support and we check it and release or block it.

But the mail contains a huge amount of images. If I remove those the mail becomes cryptic and you need to take a close look just to get the information you need.

I had a workaround of not taking those mails a tasks and just forward them but well. It would be really nice if I could just get it to work properly somehow without changing the body or it's contents in any way.

Guess I won't get around the word method.


Thanks again.
 
BTW, the macro i use to copy using word and insert into tasks is here - Create Task or Appointment and Insert Selected Text - our codes are slightly different but i have no idea if mine might work better than yours.

to use it in a rule, remove the set objmail line and change the top lines:
Sub ConvertSelectionToTask(objMail As Outlook.MailItem)

Dim objTask As Outlook.TaskItem


one other thought - if you are getting multiple messages in at once that trigger the rule, this could cause failure because the macro is busy - use the stub method - the rule grabs the message and hands it off to the macro so the rule is ready to process the next one. This is especially helpful when you do stuff that can take longer to process.

Sub TaskRTF(objMail As Outlook.MailItem)
ConvertRTFToTask objMail
End Sub

private Sub ConvertRTFToTask (objMail As Outlook.MailItem)
 
one other thought - itemadd instead of rules - you'll need something to use an if statement on -
if sender = quarantine address should work.

ETA: you could use rules to move the messages to a folder, then use itemadd to watch the folder and process the mail. If you do this, i'd mark the mail read after it's processed so you know if the macro fails.
 
Heya Diane,

sorry for the late feedback. I changed it so the mail is an attachment in the task. It is the safest way to keep it running imo.

And still it crashes after a while. The whole thing runs on a Server 2012 at the moment, the user is not logged off but locked. It runs for a while and after a while the rule crashes. So I'll just post the whole code for it here maybe you can see something that causes problems.

I edited out some parts as for sensitive information.
The code is really messy since I changed large chunks of it and didn't have the time to clean it up just yet.
There was, well, still is a function to check if certain computers are online to send them a mail to notify them about the incoming ticket, if they're offline, don't send notification. But that function just wasn't necessary so I hid it.

Again, it works fine for a while and then the rule just crashes after a bit.
I used a second rule to check if the first rule is active everytime a mail comes in, but if the first rule crashes the second one does too.

Well maybe you, or someone else finds something that I just don't see or don't know.

Many thanks in advance!

Code:
Sub ChangeSubjectForward(NewItem As Outlook.MailItem)

    On Error Resume Next

'Global Items
IncSubject = NewItem.Subject
Sender = NewItem.Sender
Dim newTask As Outlook.TaskItem
'Dim WordApp As Word.Application
'Dim wdDoc As Word.Document
Set newTask = Application.CreateItem(olTaskItem)

'logs
Dim rStats As String: rStats = Now & "--- INCOMING TICKET '" & IncSubject & "' FROM " & Sender
strFile_path = "C:\Tickets\logs\logs.txt"
Open strFile_path For Append As #1
Write #1, rStats
Close #1

'get ticket ID, +1, write new ID
Dim path As String: path = "C:\Tickets\config\lidn.txt"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile(path, 1)
        filereader = file.ReadLine
        NewNumber = CInt(filereader)
             NewNumber = NewNumber + 1
                fso.CreateTextFile(path, True).Write (NewNumber)

    newTask.Attachments.Add NewItem
  
With newTask
    .DueDate = Now
    .Subject = "Ticket#" & NewNumber & " - " & Sender & " - " & Now & " - " & " ' " & IncSubject & " ' "
    .Save
End With

'Save task in right folder
Set olNS = NewItem.Application.GetNamespace("MAPI")
Set accs = olNS.Accounts
For Each Account In accs
    If Account.AccountType = olExchange And Account.SmtpAddress = olNS.Session.DefaultStore Then
        Set pub = olNS.Folders("Public Folders" & " - " & Account.SmtpAddress).Folders("All Public Folders").Folders("Support").Folders("Tickets")
    End If
Next

Dim outObj As Outlook.Application
Dim objFolder As Outlook.MAPIFolder

Set outObj = CreateObject("outlook.application")
Set objFolder = pub
newTask.Move objFolder

With NewItem
    .Subject = Sender & " sent new support request titled: '" & IncSubject & "' at " & Now
    .Save
End With

Set Forward = NewItem.Forward
Forward.Recipients.Add me@test.com

rStats = Now & "--- SUCCESFULLY RECEIVED AND CONVERTED TICKET" & vbNewLine
strFile_path = "C:\Tickets\logs\logs.txt"
Open strFile_path For Append As #1
Write #1, rStats
Close #1
   
End Sub
 
Again, it works fine for a while and then the rule just crashes after a bit.
i wonder if it's a memory issue - since you declare the variables in the macro - set them to nothing at the end.
set newTask = nothing
Set outObj = nothing ' are you even using this variable?
Set objFolder = nothing

Does this work?
Set olNS = NewItem.Application.GetNamespace("MAPI")
Set accs = olNS.Accounts

Have you tried removing on error resume next and seeing if it hangs?

If any of the variables are used every time, it might be better to set them globally at startup - you'd definitely need to restart outlook after the rules crash though as that will kill the variable.
 
Thanks for the reply.

Do the variables persist even when the macro is done?
If so a memory issue could be the case. Didn't think of that.

I put the = nothing statement at the end of the code, let's see if it changes anything.
And yeah I use the outObj but just once to move the task to the folder.

I just replaced the on error resume next with a on error goto errorhandler I used in another macro which comes in handy but I didn't think about using it here for some reason.

Code:
ErrorHandler:
  If Err.Number <> 0 Then
     msg = "Error# " & Str(Err.Number) & " generated by " _
         & Err.Source & Chr(13) & "Line: " & Erl & Chr(13) & Err.Description
    
     rStats = Now & " - ERROR - " & msg
        strFile_path = "C:\Tickets\logs\logs.txt"
        Open strFile_path For Append As #1
        Write #1, rStats
        Close #1
            Resume Next
     End If

This should give me at least a proper error log.

And I already set up a task schedule to restart outlook twice a day - just to make sure.


I'll test it with the nothing statements and check back once I got some results.

Thanks again.

cheers
Chris
 
Oooooh and I just realized what you mean.

Code:
Dim outObj As Outlook.Application
Dim objFolder As Outlook.MAPIFolder

Set outObj = CreateObject("outlook.application")
Set objFolder = pub
newTask.Move objFolder

I just scrapped that whole part and simply use
newTask.Move pub
Don't know why I didn't do that beforehand :D
 
Okay, so we had a long weekend here and guess what, it crashed. At some point between the 24. and this morning it crashed and deactivated the rules.

And I didnt get any logs about it.

So I assume that it's not the code but Outlook as the code would give me at least some kind of error.

Eventviewer doesn't show anything but "Addins where loaded".


I just tested it and got an "Error running the operation" for both rules.
Logs still won't show anything. So the script doesn't even run.
It just crashes without doing anything. But why?

The rule just says "If receiving mail, run script". Why would it crash before even running the script ?

I'm all out of ideas here.



Kind Regards,
Chris
 
Was the logging working before the 24th?

You aren't using 2016 on to run the scripts, correct? They are disabling run a script rules in 2016 - not sure if it will be back ported to earlier versions. Scripts need to be enabled using a reg key. Run-a-Script Rules Missing in Outlook 2016
 
If I do an error on purpose it works and logs it.
No logs between 24th and today though.

The Server is 2012 R2 and is running Outlook 2010 H&B.

This is getting more and more frustrating.

I send a test mail every now and then, remote log on the server and there it is the shiny blinking window "The operation failed" and the rules are disabled again after working fine for hours or sometimes even a few days.

No logs though.
 
(correction) What is the error handler? I'm wondering if it fails on something and isn't handling the error.
 
Pretty much this at the very end of the code:

Code:
ErrorHandler:
  If Err.number <> 0 Then
     msg = "Error # " & str(Err.number) & " generated by " _
         & Err.Source & Chr(13) & "Line: " & Erl & Chr(13) & Err.Description
     MsgBox msg, , "Error", Err.HelpFile, Err.HelpContext
   
     Dim rStats As String: rStats = Now & " - ERROR - " & msg
        strFile_path = "C:\Tickets\logs\logs.txt"
        Open strFile_path For Append As #1
        Write #1, rStats
        Close #1
            Resume Next
     End If

But then again if I force an error by for example NewItems.XYZ it gives me a proper log about it.
 
Remove MsgBox msg, , "Error", Err.HelpFile, Err.HelpContext - if you aren't in front of the console to dismiss the message box, outlook will basically hang.

resume next in the write routine should push it on without forcing the rule to die - as long as it gets triggered by the code.

Also, use a stub macro to test the code manually on a selected message using the step into command so you can watch it run.


Code:
Sub RunScript()
Dim objApp As Outlook.Application
Dim objItem As MailItem
Set objApp = Application
Set objItem = objApp.ActiveExplorer.Selection.Item(1)

'macro name you want to run goes here
OpenLinks objItem

End Sub
 
Status
Not open for further replies.
Similar threads
Thread starter Title Forum Replies Date
S Create Outlook Task from Template and append Body with Email Body Outlook VBA and Custom Forms 4
P Can I create a Rule that sends me an email when I get a Task? Using Outlook 2
Z VBA to convert email to task, insert text of email in task notes, and attach copy of original email Outlook VBA and Custom Forms 4
D Using a VBA Custom Form to Send Reoccurring Email Upon Task Completion Outlook VBA and Custom Forms 4
W Deleting Sent Task Email, Deletes the task from my list Using Outlook 1
S Task Update coming as email and not updating task Using Outlook 3
Diane Poremsky Create a Task from an Email using a Rule Using Outlook 0
Bachelle Macro to Update Existing Task from New Email Outlook VBA and Custom Forms 3
E Send a Reminder/Task to certain Email Recipient Using Outlook 5
Diane Poremsky Create Tasks from Email and move to different Task folders Using Outlook 0
D Script to parse email and set a task Outlook VBA and Custom Forms 1
S Create task with email URL instead of attachment Outlook VBA and Custom Forms 4
J Format change when dragging from email to Task Using Outlook 1
A Create Task from Email and put body & email as attachment into task notes Outlook VBA and Custom Forms 17
H Create a Task by Draft-EMail > Task+Reminder not Working Outlook VBA and Custom Forms 1
L Creating a Task from Email and Attaching Original Email Outlook VBA and Custom Forms 6
I VBA Recurring Task Converted From Email Using Outlook 2
C Visual Basic auto create task from email including attachments Using Outlook 9
M Send email on task creation? Using Outlook 2
T Email to Task Rule Using Outlook 2
S Tasks are handled through email but deleted email removes task history? Exchange Server Administration 3
A Send Email to Task while sending to Email address Outlook VBA and Custom Forms 1
G Tasks - convert email to task & attach email Outlook VBA and Custom Forms 6
K send email when task changes Outlook VBA and Custom Forms 3
K Copy Entire Email Content - Paste into new Task Outlook VBA and Custom Forms 2
P Email address auto-completes work fine on laptop, but no longer on desktop Using Outlook 2
H Copying email address(es) in body of email and pasting in To field Outlook VBA and Custom Forms 1
A Search folder and move the email Outlook VBA and Custom Forms 0
P VBA to add email address to Outlook 365 rule Outlook VBA and Custom Forms 0
farrissf Outlook 2016 Optimizing Email Searches in Outlook 2016: Seeking Insights on Quick Search vs Advanced Search Features Using Outlook 0
D Delete selected text in outgoing email body Outlook VBA and Custom Forms 0
F Graphics in email / Mac recipient garbled Using Outlook 0
D Outlook VBA forward the selected email to the original sender’s email ID (including the email used in TO, CC Field) from the email chain Outlook VBA and Custom Forms 2
Witzker Outlook 2019 Macro to seach in all contact Folders for marked Email Adress Outlook VBA and Custom Forms 1
E Outlook 365 Save Selected Email Message as .msg File - oMail.Delete not working when SEARCH Outlook VBA and Custom Forms 0
S Email Macros to go to a SHARED Outlook mailbox Draft folder...NOT my personal Outlook Draft folder Using Outlook 2
R Outlook 365 VBA AUTO SEND WITH DELAY FOR EACH EMAIL Outlook VBA and Custom Forms 0
G Print email attachments when hit subfolder Outlook VBA and Custom Forms 1
C Spam Email? Using Outlook 2
G Automatically delete email when a condition is met Outlook VBA and Custom Forms 1
E Save Selected Email Message as .msg File - digitally sign email doesn't works Outlook VBA and Custom Forms 1
S Email was migrated from GoDaddy to Microsoft exchange. We lost IMAP ability Exchange Server Administration 1
R Outlook 365 How to integrate a third-party app with Outlook to track email and sms? Using Outlook 2
S Paperclip icon shows without attachment in email under Sent folder Using Outlook 0
B Outlook 2019 Automatically move email after assigning category Using Outlook 4
Rupert Dragwater How to permanently remove an email address Using Outlook 9
K vba code to auto download email into a specific folder in local hard disk as and when any new email arrives in Inbox/subfolder Outlook VBA and Custom Forms 0
F Auto changing email subject line in bulk Using Outlook 2
F Want to add second email to Outlook for business use Using Outlook 4
kburrows Outlook Email Body Text Disappears/Overlaps, Folders Switch Around when You Hover, Excel Opens Randomly and Runs in the Background - Profile Corrupt? Using Outlook 0

Similar threads

Back
Top